·
Engenharia Eletrônica ·
Sinais e Sistemas
Envie sua pergunta para a IA e receba a resposta na hora
Recomendado para você
47
Scilab Manual for Digital Signal Processing
Sinais e Sistemas
UNINTER
170
Fundamentos de SCILAB
Sinais e Sistemas
UNINTER
1
Atividade Prática em Sinais e Sistemas - Exemplo 1
Sinais e Sistemas
UNINTER
1
Exercício Escolar de Sinais e Sistemas
Sinais e Sistemas
UPE
55
Princípios de Telecomunicações - Aulas 2 e 3
Sinais e Sistemas
CEFET/RJ
4
Exercício Resolvido-2023-2
Sinais e Sistemas
UTFPR
14
Lista Laplace Resolvida e Anotações com Resolução-2023 1
Sinais e Sistemas
UTFPR
1
Referências Bibliográficas
Sinais e Sistemas
CEFET/RJ
3
Lista Final-2023-1
Sinais e Sistemas
UTFPR
1
Atividade de Acompanhamento Filtros Digitais 2023 1
Sinais e Sistemas
UTFPR
Texto de pré-visualização
Manual Scilab Manual Scilab iii Índice I Scilab 1 abort 2 adddemo 3 ans 4 argn 5 backslash 6 banner 7 boolean 8 brackets 9 break 10 case 11 clear 12 clearfun 13 clearglobal 14 colon 15 comma 16 comments 17 comp 18 comparison 19 continue 21 debug 22 delbpt 23 dispbpt 24 do 25 dot 26 edit 27 else 28 elseif 29 empty 30 end 31 equal 32 errcatch 33 errclear 34 error 35 errortable 36 evstr 45 exists 46 exit 47 external 48 extraction 49 for 52 format 53 funcprot 55 funptr 56 getdebuginfo 57 getmd5 58 getmemory 59 getmodules 60 getos 61 getscilabmode 62 getshell 63 getvariablesonstack 64 getversion 65 global 66 gstacksize 67 Manual Scilab iv hat 68 ieee 69 if then else 70 insertion 71 intppty 75 invcoeff 76 iserror 77 isglobal 78 lasterror 79 left 80 less 81 macr2lst 82 macr2tree 84 matrices 85 matrix 86 mode 87 mtlbmode 88 names 89 newfun 90 null 91 parents 92 pause 94 percent 95 perl 96 plus 97 poly 98 power 99 predef 100 quit 101 quote 102 rational 103 readgateway 104 resume 105 return 106 sciargs 107 scilab 108 select 110 semicolon 111 setbpt 112 sethomedirectory 113 slash 114 stacksize 115 star 116 startup 117 symbols 118 testmatrix 119 then 120 tilda 121 try 122 type 123 typename 124 user 125 varn 126 ver 127 warning 128 what 129 where 130 whereami 131 Manual Scilab v while 132 who 133 whouser 134 whos 135 withatlas 136 withgtk 137 withjavasci 138 withmacrossource 139 withmodule 140 withpvm 141 withtexmacs 142 withtk 143 II Equações Diferenciais 144 dae 145 daeoptions 150 dasrt 152 dassl 156 feval 161 impl 162 int2d 164 int3d 166 intc 169 integrate 170 intg 172 intl 174 ode 175 odediscrete 180 odeoptionaloutput 181 oderoot 183 odedc 185 odeoptions 188 bvode 189 III Funções Elementares 203 abs 204 acos 205 acosd 206 acosh 207 acoshm 208 acosm 209 acot 210 acotd 211 acoth 212 acsc 213 acscd 214 acsch 215 adj2sp 216 amell 217 and 218 asec 219 asecd 220 asech 221 asin 222 asind 223 asinh 224 asinhm 225 asinm 226 atan 227 atand 229 Manual Scilab vi atanh 230 atanhm 231 atanm 232 base2dec 233 bin2dec 234 binomial 235 bitand 237 bitor 238 bloc2exp 239 bloc2ss 242 cat 245 ceil 246 cell2mat 247 cellstr 248 char 249 conj 251 cos 252 cosd 253 cosh 254 coshm 255 cosm 256 cotd 257 cotg 258 coth 259 cothm 260 csc 261 cscd 262 csch 263 cumprod 264 cumsum 265 dec2bin 266 dec2hex 267 dec2oct 268 delip 269 diag 270 diff 271 double 272 dsearch 273 eval 275 exp 276 eye 277 factor 278 fix 279 flipdim 280 floor 281 frexp 282 gsort 283 hex2dec 285 imag 286 imult 287 ind2sub 288 int 289 intersect 290 inttrap 292 isdef 293 isempty 294 isequal 295 isequalbitwise 296 Manual Scilab vii isinf 297 isnan 298 isreal 299 kron 300 lexsort 301 linspace 302 log 303 log10 304 log1p 305 log2 306 logm 307 logspace 308 lstsize 309 max 310 maxi 311 meshgrid 312 min 313 mini 314 minus 315 modulo 316 ndgrid 317 ndims 319 nearfloat 320 nextpow2 321 norm 322 not 323 numberproperties 324 oct2dec 326 ones 327 or 328 pen2ea 329 perms 330 permute 331 pertrans 332 primes 333 prod 334 rand 335 rat 337 real 338 resizematrix 339 round 340 sec 341 secd 342 sech 343 setdiff 344 sign 345 signm 346 sin 347 sinc 348 sind 349 sinh 350 sinhm 351 sinm 352 size 353 solve 355 sort 356 sp2adj 358 speye 359 Manual Scilab viii spones 360 sprand 361 spzeros 362 sqrt 363 sqrtm 364 squarewave 365 ssrand 366 sub2ind 368 sum 369 sysconv 370 sysdiag 372 syslin 373 tan 375 tand 376 tanh 377 tanhm 378 tanm 379 toeplitz 380 trfmod 381 trianfml 382 tril 383 trisolve 384 triu 385 typeof 386 union 388 unique 389 vectorfind 391 zeros 392 393 csgn 394 isvector 395 396 IV Funções 397 addprofiling 398 bytecode 399 bytecodewalk 400 deff 401 exec 402 execstr 404 fun2string 406 function 407 functions 409 genlib 411 getfunctionpath 412 getd 413 headcomments 414 lib 415 librarieslist 417 library 418 libraryinfo 419 listfunctions 420 macro 421 macrovar 422 plotprofile 423 profile 424 recompilefunction 425 removeprofiling 426 resetprofiling 427 Manual Scilab ix showprofile 428 varargin 429 varargout 430 whereis 431 getf 432 V Arquivos funções de EntradaSaída 434 chdir 435 fileinfo 436 getabsolutefilepath 438 getrelativefilename 439 newest 440 sscanf 441 basename 442 copyfile 443 createdir 444 deletefile 445 dir 446 dirname 447 dispfiles 448 fileext 449 fileparts 450 filesep 451 findfiles 452 fprintf 453 fprintfMat 454 fscanf 455 fscanfMat 456 fullfile 457 fullpath 458 getdrives 459 getlongpathname 460 getshortpathname 461 io 462 isdir 463 isfile 464 listfiles 465 listvarinfile 466 ls 467 maxfiles 468 mclearerr 469 mclose 470 mdelete 471 meof 472 merror 473 mfprintf 474 mscanf 475 mget 478 mgetl 480 mgetstr 481 mkdir 482 mopen 483 movefile 486 mput 487 mputl 489 mputstr 490 mseek 491 mtell 492 pathconvert 493 Manual Scilab x pathsep 494 pwd 495 removedir 496 rmdir 497 saveformat 498 scanf 501 scanfconversion 502 VI Biblioteca de Gráficos 504 GlobalProperty 505 Graphics 509 LineSpec 515 Matplot 517 Matplot1 520 Matplotproperties 522 Sfgrayplot 524 Sgrayplot 526 addcolor 529 alufunctions 530 arcproperties 531 autumncolormap 533 axesproperties 534 axisproperties 542 bar 545 barh 547 barhomogenize 549 bonecolormap 551 captions 552 champ 554 champ1 556 champproperties 558 clearpixmap 560 clf 561 color 563 colorlist 564 colorbar 585 colordef 587 colormap 588 Compoundproperties 589 contour 590 contour2d 593 contour2di 595 contourf 597 coolcolormap 599 coppercolormap 600 copy 601 delete 602 dragrect 603 draw 604 drawaxis 605 drawlater 607 drawnow 609 editcurv 610 errbar 611 eval3d 612 eval3dp 613 event handler functions 614 fac3d 617 fchamp 618 Manual Scilab xi fcontour 620 fcontour2d 621 fec 622 fecproperties 625 fgrayplot 627 figureproperties 628 fplot2d 631 fplot3d 632 fplot3d1 633 gca 634 gce 635 gcf 636 gda 637 gdf 639 ged 640 genfac3d 641 geom3d 642 get 643 getfigurehandle 645 getcolor 646 getfont 647 getlinestyle 648 getmark 649 getsymbol 650 glue 651 graduate 652 graphicsentities 653 graphicsfonts 656 graycolormap 658 grayplot 659 grayplotproperties 660 graypolarplot 662 havewindow 664 hist3d 665 histplot 666 hotcolormap 668 hsv2rgb 669 hsvcolormap 671 ishandlevalid 672 isoview 673 jetcolormap 674 labelproperties 675 legend 677 legendproperties 679 legends 682 locate 684 mesh 685 milkdrop 687 move 688 name2rgb 689 newaxes 690 nf3d 691 objecteditor 692 oceancolormap 697 oldplot 698 param3d 699 param3d1 701 param3dproperties 704 Manual Scilab xii paramfplot2d 706 pie 707 pinkcolormap 708 plot 709 plot2d 714 plot2d1 719 plot2d2 721 plot2d3 722 plot2d4 723 plot2doldversion 724 plot3d 728 plot3d1 737 plot3d2 740 plot3d3 743 plotframe 746 plzr 748 polarplot 749 polylineproperties 751 rainbowcolormap 755 rectangleproperties 756 relocatehandle 759 replot 760 rgb2name 761 rotate 762 rotateaxes 763 rubberbox 764 sca 765 scaling 766 scf 767 sd2sci 768 sda 769 sdf 770 secto3d 771 segsproperties 772 set 775 seteventhandler 777 showpixmap 778 showwindow 779 springcolormap 780 square 781 stringbox 782 subplot 784 summercolormap 785 surf 786 surfaceproperties 790 swaphandles 794 textproperties 796 title 799 titlepage 801 twinkle 802 unglue 803 unzoom 804 whitecolormap 805 winsid 806 wintercolormap 807 xarc 808 xarcs 809 xarrows 810 Manual Scilab xiii xbasc 811 xbasr 812 xchange 813 xclear 814 xclick 815 xdel 817 xfarc 818 xfarcs 819 xfpoly 820 xfpolys 821 xfrect 823 xget 824 xgetech 826 xgetmouse 828 xgraduate 830 xgrid 831 xinfo 832 xlfont 833 xload 835 xname 836 xnumb 837 xpause 838 xpoly 839 xpolys 840 xrect 841 xrects 842 xrpoly 843 xsave 844 xsegs 845 xselect 846 xset 847 xsetech 850 xsetm 852 xstring 853 xstringb 854 xstringl 855 xtitle 856 zoomrect 857 Math rendering in Scilab graphics 859 VII Gráficos exportando e imprimindo 861 driver 862 xend 863 xinit 864 xs2bmp 865 xs2emf 866 xs2eps 867 xs2fig 868 xs2gif 869 xs2jpg 870 xs2pdf 871 xs2png 872 xs2ppm 873 xs2ps 874 xs2svg 875 VIII Booleanos 876 bool2s 877 find 878 IX CACSD 879 Manual Scilab xiv black 880 bode 882 chart 884 evans 886 gainplot 887 mcircle 888 nyquist 889 routht 891 sgrid 892 zgrid 893 abcd 894 abinv 895 arhnk 899 arl2 900 arma 902 arma2p 904 armac 905 armax 906 armax1 908 arsimul 910 augment 911 balreal 913 bilin 914 bstap 915 cainv 916 calfrq 918 canon 919 ccontrg 921 cls2dls 922 colinout 923 colregul 924 contfrm 925 contmat 926 contr 927 contrss 929 copfac 930 csim 931 ctrgram 933 dbphi 934 dcf 935 ddp 936 des2ss 938 des2tf 939 dhinf 940 dhnorm 943 dscr 944 dsimul 945 dtility 946 dtsi 947 equil 948 equil1 949 feedback 950 findABCD 951 findAC 954 findBD 956 findBDK 960 findR 963 findx0BD 966 Manual Scilab xv flts 969 fourplan 972 frep2tf 973 freq 975 freson 976 fspecg 977 fstabst 978 gmargin 980 gamitg 981 gcare 982 gfare 983 gfrancis 984 gtild 986 h2norm 988 hcl 989 hinf 990 hinfst 991 hnorm 992 hankelsv 993 hinf 994 imrep2ss 997 inistate 998 invsyslin 1000 kpure 1001 krac2 1002 lcf 1003 leqr 1004 lft 1006 lin 1008 linf 1010 linfn 1011 linmeq 1012 lqe 1016 lqg 1018 lqg2stan 1019 lqgltr 1021 lqr 1022 ltitr 1024 macglov 1025 markp2ss 1026 minreal 1027 minss 1028 mucomp 1029 narsimul 1030 nehari 1031 noisegen 1032 obsgram 1033 obscont 1034 observer 1036 obsvmat 1038 obsvss 1039 pmargin 1040 parrot 1041 pfss 1042 phasemag 1043 ppol 1044 prbsa 1045 projsl 1046 Manual Scilab xvi reglin 1047 repfreq 1048 ricdesc 1050 ricc 1052 riccati 1054 rowinout 1055 rowregul 1056 rtitr 1057 sensi 1060 showmargins 1061 sident 1062 sm2des 1066 sm2ss 1067 sorder 1068 specfact 1072 ss2des 1073 ss2ss 1074 ss2tf 1076 stility 1077 stabil 1079 svplot 1080 sysfact 1082 syssize 1083 tf2des 1084 tf2ss 1085 timeid 1086 trzeros 1088 uiobserver 1090 unobs 1092 zeropen 1093 X Estruturas de Dados 1094 cell 1095 definedfields 1097 getfield 1098 hypermat 1099 hypermatrices 1100 iscell 1101 iscellstr 1102 isstruct 1103 list 1104 lsslist 1106 lstcat 1107 mlist 1108 rlist 1110 setfield 1111 struct 1112 tlist 1113 fieldnames 1114 isfield 1115 XI Shell 1116 clc 1117 lines 1118 prompt 1119 tohome 1120 XII Console 1121 console 1122 XIII Complementação 1123 completion 1124 Manual Scilab xvii XIV Gerenciador de histórico 1126 addhistory 1127 displayhistory 1128 gethistory 1129 gethistoryfile 1130 historymanager 1131 historysize 1132 loadhistory 1133 removelinehistory 1134 resethistory 1135 saveafterncommands 1136 saveconsecutivecommands 1137 savehistory 1138 sethistoryfile 1139 XV IGU 1140 1 Tree 1142 uiConcatTree 1143 uiCreateNode 1144 uiCreateTree 1145 uiDeleteNode 1146 uiDisplayTree 1148 uiDumpTree 1149 uiEqualsTree 1150 uiFindNode 1151 uiGetChildrenNode 1153 uiGetNodePosition 1154 uiGetParentNode 1155 uiInsertNode 1156 about 1158 addmenu 1159 clipboard 1161 close 1162 delmenu 1163 exportUI 1164 figure 1165 findobj 1167 gcbo 1168 getcallbackobject 1169 getinstalledlookandfeels 1170 getlookandfeel 1171 getvalue 1172 messagebox 1174 printfigure 1176 printsetupbox 1177 progressionbar 1178 rootproperties 1179 setlookandfeel 1180 setmenu 1182 toolbar 1183 toprint 1184 uicontrol 1186 uigetcolor 1191 uigetdir 1193 uigetfile 1194 uigetfont 1196 uimenu 1197 uiputfile 1199 unsetmenu 1200 Manual Scilab xviii usecanvas 1201 waitbar 1204 xchoices 1205 xchoose 1206 xchoosemodeless 1207 xdialog 1208 xmatrix 1209 xmdialog 1210 xmessagemodeless 1211 XVI Link Dinâmicoincremental 1212 call 1213 Gmake 1216 VCtoLCCLib 1217 addinter 1218 clink 1221 chooselcccompiler 1222 configurelcc 1223 configureifort 1224 configuremsvc 1225 dllinfo 1226 findlcccompiler 1227 findmsifortcompiler 1228 findmsvccompiler 1229 fort 1230 getdynlibext 1232 haveacompiler 1233 ilibbuild 1234 ilibcompile 1242 ilibforlink 1243 ilibgenMake 1245 ilibgencleaner 1247 ilibgengateway 1248 ilibgenloader 1250 ilibmexbuild 1251 ilibverbose 1252 link 1254 ulink 1256 withlcc 1257 XVII Inteiros 1258 iconvert 1259 int8 1260 inttype 1261 XVIII Interpolação 1262 bsplin3val 1263 cshep2d 1265 evalcshep2d 1267 interp 1269 interp1 1272 interp2d 1274 interp3d 1276 interpln 1278 intsplin 1279 linearinterpn 1280 lsqsplin 1284 smooth 1286 splin 1287 splin2d 1290 splin3d 1293 Manual Scilab xix XIX Funções de EntradaSaída 1295 file 1296 getenv 1299 getio 1300 getpid 1301 getscilabkeywords 1302 halt 1303 host 1304 input 1305 load 1306 oldload 1307 oldsave 1308 read 1309 read4b 1311 readb 1312 readc 1313 save 1314 setenv 1316 unix 1317 unixg 1318 unixs 1319 unixw 1320 unixx 1321 writb 1322 write 1323 write4b 1324 XX Funções de Saída 1325 disp 1326 print 1327 printf 1328 printfconversion 1329 sprintf 1332 ssprint 1333 diary 1334 mprintf 1337 msprintf 1338 prettyprint 1339 XXI Intersci 1341 intersci 1342 XXII JVM 1343 javaclasspath 1344 javalibrarypath 1345 jrepath 1346 systemgetproperty 1347 systemsetproperty 1350 withembeddedjre 1351 XXIII Álgebra Linear 1352 aff2ab 1353 balanc 1355 bdiag 1356 chfact 1357 chol 1358 chsolve 1359 classmarkov 1360 cmblin 1361 coff 1362 colcomp 1363 companion 1364 Manual Scilab xx cond 1365 det 1366 eigenmarkov 1367 ereduc 1368 expm 1369 fstair 1370 fullrf 1372 fullrfk 1373 genmarkov 1374 givens 1375 glever 1376 gschur 1377 gspec 1378 hess 1379 householder 1380 iminv 1381 inv 1382 kernel 1383 kroneck 1384 linsolve 1386 lsq 1388 lu 1390 lyap 1391 nlev 1392 orth 1393 pbig 1394 pencan 1395 penlaur 1396 pinv 1397 polar 1398 proj 1399 projspec 1400 psmall 1401 qr 1402 quaskro 1404 randpencil 1406 range 1407 rank 1408 rankqr 1409 rcond 1411 rowcomp 1412 rowshuff 1414 rref 1415 schur 1416 spaninter 1420 spanplus 1421 spantwo 1422 spec 1424 sqroot 1427 squeeze 1428 sva 1429 svd 1430 sylv 1431 trace 1432 XXIV Localização 1433 dgettext 1434 getdefaultlanguage 1435 getlanguage 1436 Manual Scilab xxi gettext 1437 LANGUAGE 1438 setdefaultlanguage 1439 setlanguage 1440 XXV Otimização e Simulação 1441 2 Neldermead 1443 fminsearch 1444 neldermead 1453 overview 1474 nmplot 1478 optimget 1489 optimplotfunccount 1491 optimplotfval 1492 optimplotx 1493 optimset 1494 3 Optimization base 1498 optimbase 1499 4 Optimization simplex 1513 optimsimplex 1514 NDcost 1530 aplat 1533 datafit 1534 derivative 1537 fitdat 1541 fsolve 1543 karmarkar 1546 leastsq 1547 list2vec 1553 lmisolver 1554 lmitool 1556 lsqrsolve 1557 numdiff 1560 optim 1562 qld 1576 qpsolve 1579 qpsolve 1582 quapro 1585 readmps 1586 recons 1590 semidef 1591 vec2list 1594 XXVI Sobrecarga 1595 overloading 1596 XXVII Polinômios 1598 bezout 1599 clean 1600 cmndred 1601 coeff 1602 coffg 1603 colcompr 1604 degree 1605 denom 1606 derivat 1607 determ 1608 detr 1609 diophant 1610 factors 1611 gcd 1613 Manual Scilab xxii hermit 1614 horner 1615 hrmt 1616 htrianr 1617 invr 1618 lcm 1619 lcmdiag 1620 ldiv 1621 numer 1622 pdiv 1623 pol2des 1624 pol2str 1625 polfact 1626 residu 1627 roots 1628 rowcompr 1629 sfact 1630 simp 1631 simpmode 1632 sylm 1633 systmat 1634 XXVIII Processamento de Sinais 1635 5 How to 1637 How to design an elliptic filter 1638 Signal 1646 analpf 1650 bilt 1652 buttmag 1654 casc 1655 cepstrum 1656 cheb1mag 1657 cheb2mag 1658 chepol 1659 convol 1660 corr 1662 cspect 1665 czt 1668 detrend 1670 dft 1672 ell1mag 1673 eqfir 1674 eqiir 1675 faurre 1676 ffilt 1677 fft 1678 fft2 1680 fftshift 1682 filtsinc 1684 filter 1685 findfreq 1686 findm 1687 frfit 1688 frmag 1689 fsfirlin 1690 group 1692 hank 1693 hilb 1694 hilbert 1695 Manual Scilab xxiii iir 1696 iirgroup 1697 iirlp 1698 intdec 1699 jmat 1700 kalm 1701 lattn 1702 lattp 1703 lev 1704 levin 1705 lindquist 1708 mese 1709 mfft 1710 mrfit 1711 asn 1712 k 1713 sn 1714 phc 1715 pspect 1717 remez 1720 remezb 1722 rpem 1724 sincd 1726 srfaur 1727 srkf 1729 sskf 1730 syredi 1731 system 1733 trans 1734 wfir 1736 wiener 1737 wigner 1738 window 1739 yulewalk 1741 zpbutt 1742 zpch1 1743 zpch2 1744 zpell 1745 XXIX Matrizes Esparsas 1746 full 1747 ludel 1748 lufact 1749 luget 1751 lusolve 1752 mtlbsparse 1753 nnz 1754 sparse 1755 spchol 1756 spcompack 1757 spget 1759 gmres 1760 pcg 1762 qmr 1766 XXX Funções Especiais 1768 besseli 1769 beta 1772 calerf 1774 dlgamma 1775 Manual Scilab xxiv erf 1776 erfc 1777 erfcx 1778 erfinv 1779 gamma 1780 gammaln 1781 legendre 1782 oldbesseli 1785 XXXI Cadeias de Caracteres Strings 1788 ascii 1789 blanks 1790 code2str 1791 convstr 1792 emptystr 1793 grep 1794 isalphanum 1795 isascii 1796 isdigit 1797 isletter 1798 isnum 1799 justify 1800 length 1801 part 1802 regexp 1803 sci2exp 1804 str2code 1805 strcat 1806 strchr 1807 strcmp 1808 strcmpi 1809 strcspn 1810 strindex 1811 string 1813 strings 1814 stripblanks 1815 strncpy 1816 strrchr 1817 strrev 1818 strsplit 1819 strspn 1820 strstr 1821 strsubst 1822 strtod 1823 strtok 1824 tokenpos 1825 tokens 1826 tree2code 1827 XXXII Cálculos Formais 1828 addf 1829 ldivf 1830 mulf 1831 rdivf 1832 subf 1833 XXXIII Data e Hora 1834 date 1835 etime 1836 getdate 1837 tic 1839 Manual Scilab xxv toc 1840 calendar 1841 clock 1842 datenum 1843 datevec 1845 eomday 1846 now 1847 realtimeinit 1848 sleep 1849 timer 1850 weekday 1851 XXXIV Estatística 1852 cdfbet 1853 cdfbin 1854 cdfchi 1855 cdfchn 1856 cdff 1857 cdffnc 1858 cdfgam 1859 cdfnbn 1860 cdfnor 1861 cdfpoi 1862 cdft 1863 center 1864 wcenter 1865 cmoment 1866 correl 1867 covar 1868 ftest 1869 ftuneq 1870 geomean 1871 harmean 1872 iqr 1873 labostat 1874 mad 1875 mean 1876 meanf 1877 median 1878 moment 1879 msd 1880 mvvacov 1881 nancumsum 1882 nand2mean 1883 nanmax 1884 nanmean 1885 nanmeanf 1886 nanmedian 1887 nanmin 1888 nanstdev 1889 nansum 1890 nfreq 1891 pca 1892 perctl 1893 princomp 1894 quart 1896 regress 1897 sample 1898 samplef 1899 Manual Scilab xxvi samwr 1901 showpca 1902 stdeviation 1903 stdevf 1904 strange 1905 tabul 1906 thrownan 1908 trimmean 1909 variance 1911 variancef 1912 XXXV ARnoldi PACKage 1913 dnaupd 1914 dneupd 1922 dsaupd 1929 dsaupd 1937 znaupd 1942 zneupd 1950 XXXVI Funções de Compatibilidade 1956 asciimat 1957 firstnonsingleton 1958 makecell 1959 mstr2sci 1960 mtlb0 1961 mtlba 1962 mtlball 1963 mtlbany 1964 mtlbaxis 1965 mtlbbeta 1966 mtlbbox 1967 mtlbclose 1968 mtlbcolordef 1969 mtlbconv 1970 mtlbcumprod 1971 mtlbcumsum 1972 mtlbdec2hex 1973 mtlbdelete 1974 mtlbdiag 1975 mtlbdiff 1976 mtlbdir 1977 mtlbdouble 1978 mtlbe 1979 mtlbecho 1980 mtlbeval 1981 mtlbexist 1982 mtlbeye 1983 mtlbfalse 1984 mtlbfft 1985 mtlbfftshift 1986 mtlbfind 1987 mtlbfindstr 1988 mtlbfliplr 1989 mtlbfopen 1990 mtlbformat 1991 mtlbfprintf 1992 mtlbfread 1993 mtlbfscanf 1994 mtlbfull 1995 mtlbfwrite 1996 Manual Scilab xxvii mtlbgrid 1997 mtlbhold 1998 mtlbi 1999 mtlbifft 2000 mtlbimp 2001 mtlbint16 2002 mtlbint32 2003 mtlbint8 2004 mtlbis 2005 mtlbisa 2006 mtlbisfield 2007 mtlbisletter 2008 mtlbisspace 2009 mtlbl 2010 mtlblegendre 2011 mtlblinspace 2012 mtlblogic 2013 mtlblogical 2014 mtlblower 2015 mtlbmax 2016 mtlbmin 2017 mtlbmore 2018 mtlbnum2str 2019 mtlbones 2020 mtlbplot 2021 mtlbprod 2022 mtlbrand 2023 mtlbrandn 2024 mtlbrcond 2025 mtlbrealmax 2026 mtlbrealmin 2027 mtlbrepmat 2028 mtlbs 2029 mtlbsetstr 2030 mtlbsize 2031 mtlbsort 2032 mtlbstrcmp 2033 mtlbstrcmpi 2034 mtlbstrfind 2035 mtlbstrrep 2036 mtlbsum 2037 mtlbt 2038 mtlbtoeplitz 2039 mtlbtril 2040 mtlbtriu 2041 mtlbtrue 2042 mtlbuint16 2043 mtlbuint32 2044 mtlbuint8 2045 mtlbupper 2046 mtlbvar 2047 mtlbzeros 2049 XXXVII Interface Java 2050 javasciSciBoolean 2051 javasciSciBooleanArray 2053 javasciSciComplex 2055 javasciSciComplexArray 2057 javasciSciDouble 2060 Manual Scilab xxviii javasciSciDoubleArray 2062 javasciSciInteger 2064 javasciSciIntegerArray 2065 javasciSciString 2066 javasciSciStringArray 2068 javasciScilab 2070 Compile and run with javasci 2072 javasci 2074 javasci FAQ 2075 XXXVIII Interface Maple 2076 sci2map 2077 XXXIX Dicas de Conversão de Matlab para Scilab 2078 AboutM2SCItools 2079 Contents 2081 Cste 2082 Equal 2083 Funcall 2084 Infer 2085 MatlabScilabcharacterstrings 2086 Operation 2087 Type 2088 Variable 2089 getcontentsinfer 2090 m2scideclare 2091 matfile2sci 2093 mfile2sci 2094 scifiles 2097 translatepaths 2099 XL Interfaces com TclTk 2100 ScilabEval 2101 TCLCreateSlave 2103 TCLDeleteInterp 2104 TCLEvalFile 2105 TCLEvalStr 2107 TCLExistArray 2109 TCLExistInterp 2110 TCLExistVar 2111 TCLGetVar 2112 TCLGetVersion 2114 TCLSetVar 2115 TCLUnsetVar 2117 TCLUpVar 2118 browsevar 2119 config 2120 editvar 2121 tkgetdir 2122 tksavefile 2123 winclose 2124 winlist 2125 XLI Texmacs 2126 pol2tex 2127 texprint 2128 XLII Manipulação de Arquivos de Som 2129 analyze 2130 auread 2131 auwrite 2132 beep 2133 lin2mu 2134 Manual Scilab xxix loadwave 2135 mapsound 2136 mu2lin 2137 playsnd 2138 savewave 2139 sound 2140 soundsec 2141 wavread 2142 wavwrite 2143 XLIII Randlib 2144 grand 2145 XLIV Ferramentas de Desenvolvimento 2151 benchrun 2152 tbxbuildcleaner 2154 tbxbuildgateway 2155 tbxbuildgatewayclean 2156 tbxbuildgatewayloader 2157 tbxbuildhelp 2158 tbxbuildhelploader 2159 tbxbuildloader 2160 tbxbuildmacros 2161 tbxbuildsrc 2162 tbxbuildergateway 2164 tbxbuildergatewaylang 2165 tbxbuilderhelp 2166 tbxbuilderhelplang 2167 tbxbuildermacros 2168 tbxbuildersrc 2169 tbxbuildersrclang 2170 testrun 2171 XLV Ferramentas de Demonstração 2175 demobegin 2176 demochoose 2177 democompiler 2178 demoend 2179 demofilechoice 2180 demofunctionchoice 2181 demomdialog 2182 demomessage 2183 demorun 2184 XLVI Planilhas 2185 readxls 2186 xlsopen 2187 xlsread 2189 excel2sci 2191 readcsv 2192 writecsv 2193 XLVII callscilab API 2194 Boolean management 2195 Complex management 2197 DisableInteractiveMode 2199 Double management 2200 GetLastJob 2202 ScilabHaveAGraph 2203 SendScilabJob 2204 SendScilabJobs 2205 StartScilab 2206 String management 2207 Manual Scilab xxx TerminateScilab 2209 callscilab 2210 Compile and run with Call Scilab 2212 creadbmat obsolete 2215 creadchain obsolete 2217 creadcmat obsolete 2219 creadmat obsolete 2221 cwritebmat obsolete 2223 cwritechain obsolete 2225 cwritecmat obsolete 2227 cwritemat obsolete 2229 fromc 2231 fromjava 2232 XLVIII FFTW 2233 fftw 2234 fftwflags 2236 fftwforgetwisdom 2238 getfftwwisdom 2239 setfftwwisdom 2240 XLIX Interfaces com UMFPACK 2241 PlotSparse 2242 ReadHBSparse 2243 cond2sp 2245 condestsp 2247 rafiter 2249 reswithprec 2251 taucschdel 2252 taucschfact 2253 taucschget 2255 taucschinfo 2257 taucschsolve 2258 taucslicense 2259 umflicense 2260 umfludel 2261 umflufact 2262 umfluget 2264 umfluinfo 2266 umflusolve 2268 umfpack 2269 L Algoritmos Genéticos 2271 codinggabinary 2272 codinggaidentity 2273 crossovergabinary 2274 crossovergadefault 2275 initgadefault 2277 mutationgabinary 2278 mutationgadefault 2279 optimga 2280 optimmoga 2282 optimnsga 2284 optimnsga2 2286 paretofilter 2288 selectiongaelitist 2289 selectiongarandom 2291 LI Arrefecimento Simulado 2293 computeinitialtemp 2294 neighfunccsa 2295 neighfuncdefault 2296 Manual Scilab xxxi neighfuncfsa 2297 neighfuncvfsa 2298 optimsa 2299 templawcsa 2301 templawdefault 2303 templawfsa 2304 templawhuang 2306 templawvfsa 2308 LII Parâmetros 2310 addparam 2311 getparam 2312 initparam 2313 isparam 2314 listparam 2315 removeparam 2316 setparam 2317 LIII Atoms 2318 Getting started 2319 Functions Summary 2321 atomsAutoloadAdd 2322 atomsAutoloadDel 2324 atomsAutoloadList 2326 atomsDepTreeShow 2327 atomsGetInstalled 2328 atomsGetLoaded 2330 atomsInstall 2331 atomsIsInstalled 2334 atomsIsLoaded 2336 atomsList 2338 atomsLoad 2339 atomsRemove 2340 atomsRepositoryAdd 2342 atomsRepositoryDel 2343 atomsRepositoryList 2344 atomsSearch 2345 atomsSetConfig 2346 atomsShow 2348 atomsSystemUpdate 2349 atomsUpdate 2350 LIV EntradaSaída de Arquivos Matlab Binários 2352 loadmatfile 2353 matfileclose 2354 matfilelistvar 2355 matfileopen 2356 matfilevarreadnext 2357 matfilevarwrite 2358 savematfile 2359 LV xcos 2361 6 Batch functions 2363 lincos 2364 scicos 2365 scicossimulate 2366 scicosim 2368 steadycos 2370 7 palettes 2372 1 Annotations palette 2372 2 Commonly used blocks palette 2375 3 Continuous time systems palette 2383 Manual Scilab xxxii 4 Demonstrations blocks palette 2408 5 Discontinuities palette 2425 6 Discrete time systems palette 2438 7 Electrical palette 2455 8 Event handling palette 2513 9 Implicit palette 2559 10 Integer palette 2564 11 Lookup tables palette 2595 12 Math operations palette 2602 13 Matrix operation palette 2649 14 Port Subsystem palette 2712 15 Signal processing palette 2719 16 Signal routing palette 2724 17 Sinks palette 2760 18 Sources palette 2815 19 Thermohydraulics palette 2868 20 User defined functions palette 2882 21 Zero crossing detection palette 2908 8 Programming xcos Blocks 2918 1 C Computational Functions 2918 2 Scilab Computational Functions 2932 3 Utilities Functions 2936 9 Scilab Data Structures 2947 1 Blocks 2947 2 CompilationSimulation 2958 3 Diagram 2966 4 Links 2971 10 Scilab Utilities Functions 2974 buildouttb 2975 createpalette 2976 getscicosversion 2977 scicosdebug 2978 var2vec 2979 vec2var 2980 xcos 2982 Menuentries 2983 LVI scilab editor 2993 editerror 2994 Editor 2995 LVII API Scilab 2999 11 Scilab Gateway API 3001 1 How to 3001 CheckColumn 3023 CheckDimProp 3024 CheckDims 3025 CheckLength 3026 CheckLhs 3027 CheckRhs 3028 CheckRow 3029 CheckSameDims 3030 CheckScalar 3032 CheckSquare 3033 CheckVector 3034 CreateListVarFrom 3035 CreateListVarFromPtr 3038 CreateVar 3041 FindOpt 3043 FirstOpt 3045 Manual Scilab xxxiii GetListRhsVar 3047 GetRhsVar 3049 GetType 3051 IsOpt 3052 Lhs 3054 LhsVar 3055 NumOpt 3057 OverLoad 3059 Rhs 3061 Scierror 3062 Scilab C Types 3063 getoptionals 3065 istk 3067 scitypes 3068 sciprint 3071 stk 3072 12 listmanagement 3073 Boolean reading Scilab gateway 3074 Boolean writing Scilab gateway 3086 Boolean sparse reading Scilab gateway 3090 Boolean sparse writing Scilab gateway 3102 Create List Scilab gateway 3106 Double reading Scilab gateway 3110 Double writing Scilab gateway 3122 Get child item Scilab gateway 3126 Item Number Scilab gateway 3129 Integer reading Scilab gateway 3132 Integer writing Scilab gateway 3144 Pointer reading Scilab gateway 3149 Pointer writing Scilab gateway 3161 Polynomial reading Scilab gateway 3165 Polynomial writing Scilab gateway 3177 Sparse reading Scilab gateway 3181 Sparse writing Scilab gateway 3193 String reading Scilab gateway 3197 String writing Scilab gateway 3209 apiscilab 3213 Boolean reading Scilab gateway 3214 Boolean writing Scilab gateway 3216 Boolean sparse reading Scilab gateway 3219 Boolean sparse writing Scilab gateway 3222 Variable Reference Scilab gateway 3225 Variable dimension Scilab gateway 3229 Variable Type Scilab gateway 3233 Variable Complexity Scilab gateway 3237 Matrix Type Scilab gateway 3241 Double reading Scilab gateway 3245 Double writing Scilab gateway 3248 Integer Precision Scilab gateway 3252 Integer reading Scilab gateway 3256 Integer writing Scilab gateway 3263 Pointer reading Scilab gateway 3270 Pointer writing Scilab gateway 3272 Polynomial Symbolic Variable Scilab gateway 3275 Polynomial reading Scilab gateway 3279 Polynomial writing Scilab gateway 3284 Sparse matrix reading Scilab gateway 3286 Sparse writing Scilab gateway 3289 Manual Scilab xxxiv String reading Scilab gateway 3292 String writing Scilab gateway 3295 LVIII Gerenciamento de ajuda online 3297 addhelpchapter 3298 apropos 3299 foo 3300 help 3301 helpfromsci 3302 helpskeleton 3304 makeindex 3305 man 3306 manedit 3310 helps 3311 xmltohtml 3312 xmltojar 3314 xmltopdf 3316 xmltops 3318 delhelpchapter 3320 xmltochm 3321 Parte I Scilab 2 Name abort Interrupção de avaliação Descrição abort interrompe a avaliação corrente e retrona ao prompt de comando Dentro de um nível de pause abort retorna ao prompt de nível 0 Ver Também quit pause break 3 Name adddemo adiciona uma entrada na lista de demonstrações adddemotitlepath Parâmetros title string o título da demonstração path string o endereço do script scilab associado à demonstração Descrição Esta função adiciona uma nova entrada na lista de demonstrações A demonstração deve ser executada por um arquivo script do Scilab Se o dado título já existir title na lista de demonstrações associada ao mesmo arquivo nada é feito Esta função checa se o arquivo existe Exemplos criando um simples script de demonstração pathTMPDIRfoosce mputldisp Hellopath adddemoMy first demopath a demonstração pode agora ser executada através do menu Demos Ver também addhelpchapter Autor Serge Steer INRIA 4 Name ans resposta Descrição ans significa resposta A variável ans é criada automaticamente quando expressões não são atribuídas ans contém a última expressão nãoatribuída 5 Name argn número de argumentos na chamada de uma função lhs rhs argn lhsargn1 rhsargn2 Descrição Esta função é usada dentro da definição de uma função Ela fornece os números de parâmetros de entrada rhs e saída lhs passados à função quando esta é chamada Geralmente é usada em definições de funções para lidar com parâmetros opcionais Ver Também function varargin 6 Name backslash divisão matricial direitaesquerda xAb Descrição denota a divisão matricial direitaesquerda xAb é a solução para Axb Se A é quadrada e nãosingular xAb unicamente definida é equivalente a xinvAb mas as computações são menos custosas Se A não é quadrada x é uma solução de mínimo quadrado ie normAxb é mínima norma euclidiana Se A é de posto coluna cheio a solução de mínimo quadrado xAb é unicamente definida há um único x que minimiza normAxb Se Anão é de posto coluna cheio então a solução de mínimo quadrado não é única e xAb em geral não é a solução com norma mínima a solução com norma mínima é xpinvAb AB é a matriz com entrada ij igual a AijBij Se A ou Bé um escalar AB é equivalente a AonesBB ou ABonesA AB é um operador sem significado predefinido Pode ser usado para definir um novo operador ver overloading com a mesma precedência que ou Exemplos Arand32b111 xAb ypinvAb xy Arand23b11 xAb ypinvAb xy Axb Ayb Arand31rand12 b111 xAb ypinvAb Axb Ayb Arand21rand13 b11 xAb ypinvAb Axb Ayb A benchmark of several linear solvers Adescrrefmtype ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa b 0onessizeA11 tic res umfpackAb printf time needed to solve the system with umfpack 3f toc tic res linsolveAb printf time needed to solve the system with linsolve 3f toc tic res Ab printf time needed to solve the system with the backslash operator 3f toc Ver Também slash inv pinv percent ieee linsolve umfpack 7 Name banner exibe banner do Scilab Windows banner Descrição Exibe banner do Scilab Exemplos clcbanner Autor Allan CORNET 8 Name boolean objetos Scilab variáveis booleanas e operadores e Descrição Uma variável booleana é T para true verdadeiro ou F for false para falsefalso Es tas variáveis podem ser usadas para definir matrizes de valores booleanos com a sintaxe usual Ma trizes de valores booleanos podem ser manipuladas como matrizes ordinárias para extraçãoinserção de elementos e concatenação Note que outras operações usuais etc não são definidas para matrizes de valores booleanos Três operadores especiais são definidos para estas matrizes b é a negação elemento a elemento de b matriz b1b2 é o and e lógico elemento a elemento de b1 e b2 matrizes b1b2 é o or ou lógico elemento a elemento de b1 e b2 matrizes Variáveis booleanas podem ser usadas para se indexar vetores ou matrizes Por exemplo aTFT retorna a submatriz feita das linhas 1 e 3 de a Matrizes esparsas de valores booleanos são suportadas Exemplos 1213 121 a15 aagt2 Ver Também matrices or and not 9 Name brackets colchetes esquerdo e direito a11a12a21a22 s1s2func Parâmetros a11a12 qualquer matriz de reais polinômios razões de polinômios lista syslin com dimensões apropriadas s1s2 qualquer nome de variável possível Descrição Colchetes esquerdo e direito são usados para notar concatenação de vetores e matrizes Estes símbolos também são usados para denotar lado esquerdo múltiplo para a chamada de uma função Dentro de colchetes de concatenação espaços vazios ou vírgulas significam concatenação de colu nas e pontosevírgulas ou retronos de carro significa concatenação de linhas Nota para evitar confusões é melhor utilizar vírgulas ao invés de espaços vazios para separar colunas Dentro de lados esquerdos múltiplos os nomes das variáveis de vem ser separados por vírgulas Exemplos 69964 sqrt1 0 1 i 2 i 3 this isa stringvector spoly0s1s2s tf2ss1stf2ss2s usschurrand33 Ver Também comma semicolon 10 Name break palavrachave para interromper um laço loop significa interromper neste ponto Descrição Dentro de um laço for ou while loop o comando break força o fim do laço Exemplos k0 while 11 kk1 if k gt 100 then breakend end Ver Também while if for abort return 11 Name case palavrachave usada na estrutura select significa caso Descrição Palavra chave usada na estrutura select case Usea do seguinte modo select expressão0 case expressão1 then instruções1 case expressão2 then instruções2 case expressãon then instruçõesn else instruções end Ver Também select while end for 12 Name clear cancela variáveis clear a Descrição Este comando cancela variáveis que não estão protegidas Ele remove as variáveis nomeadas do am biente Por si só clear cancela todas as variáveis exceto as protegidas por predef Logo os dois comandos predef0 e clear removem todas as variáveis Normalmente variáveis protegidas são bibliotecas padrões e variáveis com o prefixo Note a sintaxe particular clear a e não cleara Note também que a não cancela a mas define a como uma matriz vazia Ver Também predef who 13 Name clearfun remove função primitiva retclearfunname Descrição clearfunname remove a primitiva name do conjunto de primitivas funções builtin clearfun retorna t ou f Esta função permite renomear uma primitiva uma primitiva Scilab pode ser substituída por uma função definida pelo usuário Para usuários experientes Ver Também newfun funptr 14 Name clearglobal cancela variáveis globais clearglobal clearglobal nam1 namn clearglobalnam1 namn Parâmetros nam1 namn nomes de variáveis válidos Descrição clearglobal cancela todas as variáveis globais clearglobal nam1 namn cancela as variáveis globais dadas por seus nomes Note que clearglobal limpa apenas as variáveis globais as cópias locais destas variáveis não são destruídas Exemplos global a b c a1b2c3 whoglobal clearglobal b whoglobal Ver Também global who 15 Name colon operador dois pontos Descrição Colon symbol can be used to form implicit vectors see also linspace logspace jk é o vetor j j1k vazio se jk jdk é o vetor j jd jmd A notação de dois pontos também pode ser usada para retirar linhas colunas e elementos selecionados de vetores e matrizes ver também extractioninsertion A é o vetor de todos os elementos de A considerados como uma única coluna Aj é a jésima coluna de A Ajk é AjAj1Ak Ajk é AjAj1Ak Aw preenche a matriz A com entradas de w tomados coluna a coluna se w é uma matriz Ver Também matrix for linspace logspace 16 Name comma separador de colunas instruções e argumentos Descrição Vírgulas são usadas para separar parâmetros em funções ou para separar entradas em vetores linhas Espaços vazios podem ser usados para separar entradas em um vetor linha mas é preferível que se use vírgulas Também é usada para separar instruções do Scilab Use para que o resultado não seja exibido na tela Exemplos a123456 a1b1c2 Ver Também semicolon brackets 17 Name comments comentários Descrição Uma seqüência de duas barras fora de uma definição de string marca o início de um comentário As barras tanto quanto o restante dos caracteres até o fim das linhas não são interpretados Dentro de uma função as primeiras linhas de comentário até a primeira instrução ou linha vazia podem ser usadas para fornecer o conteúdo padrão para a documentação de ajuda da função help da função Exemplos g981 a gravidade textab function ymyfunctionx myfunction computa yx21 x deve ser um vetor ou uma matriz yx21 endfunction help myfunction 18 Name comp compilação de função Scilab compfunction opt Parâmetros function uma função scilab nãocompilada tipo 11 opt flag com valor 0 padrão 1 ou 2 Descrição compfunction compila a função function Funções compiladas e interpretadas são equiva lentes mas geralmente as compiladas são mais rápidas As funções fornecidas nas bibliotecas padrões são compiladas A definição online bem como a sintaxe curta dos comandos exec e deff geram funções compiladas Então comp tem que ser usado apenas em casos bem particulares Para se produzir uma função não compilada devese usar exec ou deff com a opção n O valor opt2 faz com que a função seja compilada para definição de perfil Note que ago ra é possível adicionar a instrução de definição de perfil após a compilação utilizando a função addprofiling A opção obsoleta opt1 era específica para propósitos de análise de códigos e agora é ignorada ie tratada como opt0 Note na compilação a função original é modificada e nenhum objeto novo é criado Ver Também type deff exec function addprofiling profile 19 Name comparison comparação operadores relacionais ab ab ou ab ab ab ab ab Parâmetros a qualquer tipo de variável para comparações de igualdade ab ab ab e restrita a arrays de pontos flutuantes reais e inteiros para comparações relacionadas à ordem ab ab abab b qualquer tipo de variável para comparações de igualdade ab ab a b e restrita a arrays de ponto flutuantes reais e inteiros para comparações relacionadas à ordem ab ab abab Descrição Duas classes de operadores devem ser distinguidas Comparações de igualdade e desigualdade ab ab ou de modo equivalente ab Estes operadores se aplicam a quaisquer tipos de operandos Comparações de ordem ab ab abab Estes operadores se aplicam apenas a arrays de pontos flutuantes reais e inteiros A semântica dos operadores de comparação também depende dos tipos de operandos Com variáveis arrays como arrays de pontos flutuantes ou inteiros arrays lógicos arrays de strings arrays de polinômios ou razões de polinômios arrays de manipuladores listas o seguinte se aplica Se a e b são avaliados como arrays do mesmo tipo e dimensões idênticas a comparação é realizada elemento a elemento e o resultado é um array de booleanos da comparação Se a e b são avaliados como arrays do mesmo tipo mas a ou b é um array 1 por 1 o elemento é comparado com cada elemento do outro array O resultado é um array de booleanos com o tamanho do operando nãoescalar Em outros casos o resultado é o booleano f Se os tipos de dados dos operandos são diferentes mas compatíveis como pontos flutuantes e inteiros uma conversão de tipo é realizada antes da comparação Com outros tipos de operandos como function libraries o resultado é t se os objetos são idênticos e f em outros casos Comparação de igualdade entre operandos com tipos de dados incompatíveis retorna f comparison 20 Exemplos comparações elemento a elemento 153 154 151 4 2 3 0 1 list123list133 comparações objeto a objeto 11043 foo3 1 list1231 isequallist1231 isequal1101 comparação com conversão de tipo int3211 int32115 int3215int83 ppoly0sc p0 ppoly1sc0 Ver Também less boolean isequal 21 Name continue Palavrachave para passar o controle para a próxima iteração de um laço loop significa continuar Descrição Dentro de um laço for ou while o comando continue passa o contole para a próxima iteração do laço no qual aparece pulando quaisquer sentenças restantes entre esta instrução e a instrução end do laço Exemplos for k110Kkif kgt2ampklt8 then continuedisphelloendkend for j12 x for k110if kgtj1ampklt8 then continueendxxkend x end Ver Também while for break return Autor Serge Steer INRIA 22 Name debug nivel de depuração debugging debugging level debuglevelint levelintdebug Parâmetros levelint inteiro de 0 a 4 Descrição Para os valores 0 1 2 3 ou 4 de levelint define vários níveis de depuração Isto é voltado para o analisador sintático não para scripts Scilab Para usuários mais experientes do Scilab 23 Name delbpt deleta pontos de parada breakpoints delbptmacroname linenumb Parâmetros macroname string linenumb escalar inteiro ou vetor de inteiros Descrição Deleta o ponto de parada na linha linenumb na função macroname linenumb pode ser um vetor linha ou coluna de inteiros ou um único escalar Se linenumb for omitido todos os pontos de parada da função macroname são deletados Se ambos macroname e linenumb são omitidos todos os pontos de parada em todas as funções são deletados Exemplos setbptfoo1setbptfoo10delbptfoo10dispbpt delbptfoo1dispbpt setbptfoo14setbptfoo19setbptfoo26setbptfoo38dispbpt delbptfoo2dispbpt delbptdispbpt delbptfoo1256dispbpt Ver Também setbpt dispbpt pause resume 24 Name dispbpt exibe breakpoints pontos de parada dispbpt Descrição dispbpt exibe todos os breakpoints ativos inseridos nas funções Ver Também setbpt delbpt pause resume 25 Name do palavrachave de linguagem para laços loops significa faça Descrição Pode ser usado dentro de instruções for ou while para separar a definição de variável do laço e o conjunto de instruções do mesmo Ver Também for while 26 Name dot símbolo de ponto 12333 ab 123 456 Descrição É usado para marcar pontos vírgulas decimais em números 325 e 0001 op usado em conjunto com outros símbolos de operadores forma outros operadores Operações multiplicativas elemento a elemento são obtidas utilizandose ou Por exemplo C A B é a matriz com elementos cij aijbij O produto de Kronecker é notado por Note que quando o ponto segue um número é sempre parte deste 2x é avaliado como 20x e 2 x há um espaço entre 2 e é avaliado como 2x Marca de continuação Dois ou mais pontos ao fim de uma linha ou seguidos por um comentário indicam que a próxima linha será uma continuação Linhas de continuação são manipuladas por um processador que constrói uma linha lógica longa de uma dada seqüência de linhas de continuação Então marcas de continuação podem ser usadas para cortar uma linha em qualquer ponto Exemplos ponto decimal 1345 usado como parte de um operador x1 2 3x2 x um espaço é requerido entre 2 e o ponto usado como marcas de continuação T123primeiro elemento 456 segundo elemento a aqui eu começo um grande string mas não quero continuar aqui e aqui eu continuo y12 45 Ver Também star hat slash backslash 27 Name edit edição de funções editfunctionname Parameters functionname string Descrição Se functionname for o nome de uma função Scilab definida editfunctionname tente abrir o arquivo associado functionnamesci Se functionname for o nome de uma função Scilab indefinida edit cria o arquivo functionnamesci no diretório TMPDIR Exemplos editedit abre o editor com o texto dessa função editmyfunction abre o editor para uma nova função Ver Também manedit 28 Name else palavrachave usada na estrutura ifthenelse significa senão Descrição Usado com if Ver Também if 29 Name elseif palavrachave usada na estrutura ifthenelse significa senão se Descrição Ver ifthenelse 30 Name empty matriz vazia Descrição denota a matriz vazia É definida de modo único e possui 0 linha e 0 coluna ie size 00 As seguintes convenções convenientes foram feitas A A A A A A A A inv detcondrcond1 rank0 Funções de matrizes retornam ou produzem uma mensagem de erro quando não há resposta óbvia Sistemas lineares vazios listas syslin podem ter várias linhas ou colunas Exemplos spoly0s A s s1 A A Arand22 AAA1 sizeAA svd wssrand222 wrw sizewr w1ss2tfwr sizew1 Ver Também matrices poly string boolean rational syslin 31 Name end Palavrachave end significa fim Descrição Usado no fim de estruturas de laço ou condicionais for while if select devem ser terminados por end Ver Também for while if select 32 Name equal atribuição ou comparação sinal de igualdade Descrição Atribuição o sinal de igualdade é usado para denotar a atribuição de valores a variáveleis A sintaxe pode ser aexpr onde a é um nome de variável e expr uma expressão do Scilab cuja avaliação conduz a um único resultado abexpr onde ab são nomes de variáveis e expr uma expressão do Scilab cuja avaliação conduz a tantos resultados quanto o número de variáveis dadas Comparação o sinal de igualdade também é usado em operadores de comparação ab denota comparação de igualdade entre os valores das expressões a e b ab denota comparação de desigualdade entre os valores das expressões a e b ab e ab denotam comparações de ordem entre os valores de a e b Ver comparison para detalhes semânticos Exemplos a sin32 M 21338576676906388 us schurM 110 4 12 Ver Também less great boolean isequal comparison 33 Name errcatch Armadilha para erros errcatchn action option errcatch Parâmetros n inteiro action option strings Descrição errcatch fornece uma ação manipulador de erros quando um erro do tipo n ocorre n tem o seguinte significado Se n0 n é o número do erro a ser apanhado Se n0 todos os erros devem ser apanhados action é um dos seguintes strings pause uma pausa é executada quando se apanha o erro Esta opção é útil para propósitos de depuramento Use whereami para obter informações sobre o contexto corrente continue a próxima instrução na função ou em arquivos executáveis é executada a instrução corrente é ignorada É possível verificar se um erro ocorreu utilizando a função iserror function Não se esqueça de apagar o erro utilizando a função errclear o quanto antes Esta função é útil para recuperação de erros Em muitos casos o uso de errcatchncontinue pode ser substituído pelo uso da função execstr ou da estrutura de controle try control structure kill modo padrão todas as funções intermediárias são canceladas e o Scilab retorna ao prompt de nível 0 stop interrompe a sessão do Scilab corrente útil quando o Scilab é chamado por um programa externo option é o string nomessage para cancelar mensagens de erro Para retornar ao modo padrão entre errcatch1kill ou de modo semelhante errcatch1errcatch é um equivalente obsoleto a errcatch1 As ações de errcatch se aplicm ao contexto corrente de avaliação function exec pause e a todos os subníveis Uma segunda chamada a errcatch em um subnível esconde a inicial para este sub nível Se uma segunda chamada a errcatch é feita no mesmo nível o efeito da primeira é removido Quando chamado no contexto de uma função do Scilab ou em exec o errcatch é automaticamente reiniciado quando a função retorna Ver Também try errclear iserror whereami execstr 34 Name errclear limpeza de erros errclearn Descrição Limpa a ação manipulador de erros conectada ao erro de tipo n Se n é positivo é o número do erro limpo caso contrário todos os erros são limpos caso padrão Ver Também errcatch iserror lasterror 35 Name error mensagens de erro errormessage n errorn errornpos Parâmetros message um string A mensagem de erro a ser exibida n um inteiro O número associado à mensagem de erro pos um inteiro Um parâmetro para a mensagem de erro Descrição error permite escrever uma mensagem de erro e manipular o erro Por padrão error interrompe a execução corrente e retorna ao nível de prompt Este padrão pode ser modificado utilizandose as funções errcatch ou execstrerrcatch errormessage imprime o string contido em message O número associado à mensagem de erro é 10000 errormessagen imprime o string contido em message O número associado à mensagem de erro é dado por n Este número deve ser maior que 10000 errorn imprime a mensagem de erro predefinda associada ao número de erro n Algumas mensagens de erro predefinidas requerem um parâmetro ver errortable Neste caso o argumento pos deve ser usado errornpos para fornecer o valor do parâmetro Em outros casos o parâmetro é ignorado Ver errortable para uma lista das mensagens de erro e seus números associados Exemplos errormy error message error43 error523 Ver Também warning errcatch execstr lasterror 36 Name errortable tabela de mensagens de erros Description Esta página fornece a tabela e mensagens de erros predefinidas e seus números associados Algumas dessas mensagens de erro são utilizadas pelo próprio Scilab para erros de parser ou erros de builtins específicos Algumas outras são de uso mais geral e podem ser utilizadas por funções do Scilab As com asteríscos são aquelas para as quais a sintaxe errornpos é manipulada 1 Incorrect assignment atribuição incorreta 2 Invalid factor fator inválido 3 Waiting for right parenthesis esperava parêntese direito 4 Undefined variable s variável indefinida s 5 Inconsistent columnrow dimensions dimensões de colunalinha inconsistentes 6 Inconsistent rowcolumn dimensions dimensões de linhacoluna inconsistentes 7 Dot cannot be used as modifier for this operator ponto não pode ser usado como modificador para ste operador 8 Inconsistent addition adição inconsistente 9 Inconsistent subtraction subtração inconsistente 10 Inconsistent multiplication multiplicação inconsistente 11 Inconsistent right division divisão esquerdadireita inconsistente 12 Inconsistent left division divisão direitaesquerda inconsistente 13 Redefining permanent variable redefinição de variável permanente 14 Eye variable undefined in this context variável eye identidade indefinida neste contexto 15 Submatrix incorrectly defined submatriz definida incorretamente 16 Incorrect command comando incorreto 17 Stack size exceeded Use stacksize function to increase it tamanho de pilha excedido Use a função stacksize para aumentálo 18 Too many variables muitas variáveis 19 Problem is singular o problema é singular 20 Wrong type for argument d Square matrix expected tipo errado para o argumento d esperava matriz quadrada 21 Invalid index índice inválido 22 Recursion problems Sorry problemas de recursão Perdão 23 Matrix norms available are 1 2 inf and fro normas de matriz disponíveis são 12inf e fro 24 Convergence problem problema de convergência 25 Bad call to primitive s chamada ruim à primitiva s errortable 37 26 Too complex recursion recursion tables are full recursão muito complexa as tabelas de recursão estão cheias 27 Division by zero divisão por zero 28 Empty function função vazia 29 Matrix is not positive definite a matriz não é positiva definida 30 Invalid exponent expoente inválido 31 Incorrect string string incorreto 32 Singularity of log or tan function singularidade da função log ou tan 33 Too many muitos 34 Incorrect control intruction syntax sintaxe incorreta de instrução de controle 35 Syntax error in an ifa while or a select instruction erro de sintaxe em uma instrução if while ou select 36 Wrong input argument d argumento de entradad incorreto 37 Incorrect function at line d função incorreta na linha d 38 Wrong file name nome de arquivo incorreto 39 Incorrect number of arguments número incorreto de argumentos 40 Waiting for end of command esperava fim do comando 41 Incompatible output argument argumento de saída incompatível 42 Incompatible input argument argumento de entrada incompatível 43 Not implemented in scilab não implementado no Scilab 44 Wrong argument d argumento d incorreto 45 Null matrix argument d matriz nula argumento número d 46 Incorrect syntax sintaxe incorreta 47 End or else is missing faltando end ou else 48 Input line longer than buffer size d linha de entrada maior que tamanho de buffer d 49 Incorrect file or format arquivo ou formato incorreto 50 Subroutine not found s subrotina não encontrada s 52 Wrong type for argument d Real matrix expected tipo errado para o argumento d esper ava matriz de reais 53 Wrong type for input argument d Real or complex matrix expected tipo errado para o argumento d esperava matriz de reais ou de complexos 54 Wrong type for input argument d Polynomial expected tipo errado para o argumento d esperava polinômio 55 Wrong type for argument d String expected tipo errado para o argumento d esperava string errortable 38 56 Wrong type for argument d List expected tipo errado para o argumento d esperava lista 57 Problem with comparison symbol problema com símbolo de comparação 58 Function has no input argument a função não tem argumento de entrada 59 Function has no output a função não tem saída 60 Wrong size for argument Incompatible dimensions tamanho errado para o argumento dimensões incompatíveis 61 Direct access file give format arquivo de acesso direto fornecer formato 62 End of file at line d fim do arquivo na linha d 63 d graphic terminal d terminais gráficos 64 Integration fails falha de integração 65 d logical unit already used d unidade lógica já utilizada 66 No more logical units available não há mais unidades lógicas disponíveis 67 Unknown file format formato de arquivo desconhecido 68 Fatal error Your variables have been saved in the file s 69 Floating point exception exceção de ponto flutuante 70 Too many arguments in fort max 30 muitos argumentos em fort máximo de 30 71 This variable is not valid in fort esta variável não é válida em fort 72 s is not valid in this context s não é válido neste contexto 73 Error while linking erro no linking 74 Leading coefficient is zero coeficiente regente é 0 75 Too high degree max 100 grau muito alto no máximo 100 76 For xval with typevald is not implemented in Scilab para xval com typevald não há implementação no Scilab 77 s wrong number of rhs arguments s número incorreto de argumentos do lado direito 78 s wrong number of lhs arguments s número incorreto de argumentos do lado esquerdo 79 Indexing not allowed for output arguments of resume indexação não permitida para argumentos de saída de resume 80 Incorrect function argument ns função incorreta argumento n s 81 s Wrong type for argument d Real or complex matrix expected s tipo errado para o argumento d esperava matriz de reais ou de complexos 82 s Wrong type for argument d Real matrix expected s tipo errado para o argumento d esperava matriz de reais 83 s Wrong type for argument d Real vector expected s tipo errado para o argumento d esperava vetor de reais 84 s Wrong type for argument d Scalar expected s tipo errado para o argumento d esperava escalar errortable 39 85 Host does not answer host não responde 86 Uncontrollable system sistema incontrolável 87 Unobservable system sistema inobservável 88 sfact singular or asymmetric problem sfact problema singular ou assimétrico 89 Wrong size for argument d tamanho errado para o argumento d 90 Wrong type for argument d Transfer matrix expected tipo errado para o argumento d esperava matriz de transferência 91 Wrong type for argument d In state space form expected tipo errado para o argumento d esperava em forma de espaço de estados 92 Wrong type for argument d Rational matrix expected tipo errado para o argumento d esperava matriz de razões de polinômios 93 Wrong type for argument d In continuous time expected tipo errado para o argumento d esperava em tempo contínuo 94 Wrong type for argument d In discrete time expected tipo errado para o argumento d esperava em tempo discreto 95 Wrong type for argument d SISO expected tipo errado para o argumento d esperava SISO 96 Time domain of dth argument is not defined domínio de tempo do désimo argumento não está definido 97 Wrong type for argument d A system in state space or transfer matrix form expected tipo er rado para o argumento d esperava um sistema em espaço de estados ou uma matriz de transferência 98 Variable returned by scilab argument function is incorrect variável retornada pela função argu mento do Scilab está incorreta 99 Elements of dth argument must be in increasing order elementos do désimo argumento devem estar em ordem crescente 100 The elements of dth argument are not in strictly decreasing order os elementos do d ésimo argumento não estão em ordem estritamente crescente 101 Last element of dth argument first o último elemento do désimo argumento não é igual ao primeiro 102 Variable or function s is not in file s variável ou função s não está no arquivo s 103 Variable s is not a valid rational function variável s não é uma função racional válida 104 Variable s is not a valid state space representation variável s não é uma representação de espaço de estados válida 105 Undefined fonction função indefinida 106 Function name already used nome de função já utilizado 107 Too many functions are defined maximum d muitas fuñções estão definidas número máximo d 108 Too complex for scilab may be a too long control instruction muito complexo para o Scilab pode ser uma instrução de controle muito longa 109 Too large cant be displayed muito grande não pode ser exibido errortable 40 110 s was a function when compiled but is now a primitive s era uma função quando compilada mas agora é uma primitiva 111 Trying to redefine function s tentando redefinir a função s 112 Cannot allocate more memory não pode alocar mais memória 113 Too large string string muito grande 114 Too many linked entry points muitos pontos de entradas linkados 115 Stack problem detected within a loop problema de empilhamento detectado dentro de um laço 116 Wrong value for argument d valor errado para o argumento d 117 List element number d is Undefined elemento número d da lista é indefinido 118 Wrong type for argument d Named variable not an expression expected tipo errado para o argumento d esperava variável nomeada não uma expressão 119 Indices for nonzero elements must be given by a 2 column matrix índices para elementos não nulos devem ser fornecidos por uma matriz de duas colunas 121 Incompatible indices for nonzero elements índices incompatíveis para elementos nãonulas 122 Logical unit number should be larger than d número de unidade lógica deve ser maior que d 123 Function not bounded from below função não limitada por baixo 124 Problem may be unbounded too high distance between two consecutive iterations o problema pode ser ilimitado distância muito alta entre duas iterações consecutivas 126 Inconsistent constraints restrições inconsistentes 127 No feasible solution não há solução viável 128 Degenerate starting point ponto de partida degenerado 129 No feasible point has been found nenhum ponto viável foi encontrado 130 Optimization fails back to initial point a otimização falhou de volta ao ponto inicial 131 optim stop requested by simulator ind 0 optim parada requerida pelo simulador ind0 132 optim incorrect input parameters optim parâmetros de entrada incorretos 133 Too small memory memória muito pequena 134 optim problem with initial constants in simul optim problema com constantes iniciais em simul 135 optim bounds and initial guess are incompatible optim limites e palpite inicial são incompatíveis 136 optim this method is NOT implemented optim este método NÃO é implementado 137 NO hot restart available in this method NÃO há recomeço rápido disponível neste método 138 optim incorrect stopping parameters optim parâmetros de parada incorretos 139 optim incorrect bounds optim limites incorretos 140 Variable s must be a list variável s deve ser uma lista errortable 41 141 Incorrect function argument nd função incorreta argumento n d 142 Hot restart dimension of working table argument nd recomeço rápido dimensão da mesa de trabalho argumento nd 143 optim df0 must be positive optim df0 deve ser positivo 144 Undefined operation for the given operands operação indefinida para os dados operandos 201 s Wrong type for argument d Real or complex matrix expected s tipo errado para o argumento d esperava matriz de reais ou complexos 202 s Wrong type for argument d Real matrix expected s tipo errado para o argumento d esperava matriz de reais 203 s Wrong type for argument d Real vector expected s tipo errado para o argumento d esperava vetor de reais 204 s Wrong type for argument d Scalar expected s tipo errado para o argumento d esperava escalar 205 s Wrong size for argument d dd expected s tamanho errado para o argumento d esperava dd 206 s Wrong size for argument d d expected s tamanho errado para o argumento d esperava d 207 s Wrong type for argument d Matrix of strings expected s tipo errado para o argumento d esperava matriz de strings 208 s Wrong type for argument d Boolean matrix expected s tipo errado para o argumento d esperava matriz de booleanos 209 s Wrong type for argument d Matrix expected s tipo errado para o argumento d esperava matriz 210 s Wrong type for argument d List expected s tipo errado para o argumento d esperava lista 211 s Wrong type for argument d Function or string external function expected s tipo errado para o argumento d esperava função ou string função externa 212 s Wrong type for argument d Polynomial expected s tipo errado para o argumento d esperava polinômio 213 s Wrong type for argument d Working integer matrix expected s tipo errado para o argumento d esperava matriz de inteiros operante 214 Argument d of s wrong type argument expecting a vector Argumento d de s tipo de argumento errado esperava um vetor 215 dth argument type must be boolean désimo argumento deve ser booleano 216 Wrong type for argument d Boolean or scalar expected s tipo errado para o argumento d esperava booleano ou escalar 217 Wrong type for argument d Sparse matrix of scalars expected s tipo errado para o argumento d esperava matriz esparsa de escalares 218 Wrong type for argument d Handle to sparse lu factors expected s tipo errado para o argumento d esperava manipulador para fatores lu esparsos errortable 42 219 Wrong type argument d Sparse or full scalar matrix expected s tipo errado para o argu mento d esperava matriz de escalares esparsa ou completa 220 Null variable cannot be used here variável nula não pode ser usada aqui 221 A sparse matrix entry is defined with two differents values uma entrada da matriz esparsa é definida com dois valores diferentes 222 s not yet implemented for full input parameter s ainda não foi implementado para parâmetro de entrada completa 223 It is not possible to redefine the s primitive this way see clearfun não é possível redefinir a primitiva s desta forma ver clearfun 224 Type data base is full banco de dados de tipos está cheio 225 This data type is already defined este tipo de dado já foi definido 226 Inequality comparison with empty matrix comparação de desigualdade com matriz vazia 227 Missing index faltando índice 228 Reference to the cleared global variable s referência à variável global limpa s 229 Operands of and operations must not contain NaN of Inf operandos de e não devem conter NaN ou Inf 230 semidef fails semidef falhou 231 Wrong type for first input argument Single string expected tipo errado para o primeiro argu mento de entrada esperava string único 232 Entry name not found nome de entrada não encontrado 233 Maximum number of dynamic interfaces reached número máximo de interfaces dinâmicas alcançado 234 link expecting more than one argument link experava mais que um argumento 235 link problem with one of the entry point link problema com um dos pontos de entrada 236 link the shared archive was not loaded link o arquivo compartilhado não foi carregado 237 link Only one entry point allowed On this operating system link apenas um ponto de entrada permitido neste sistema operacional 238 link First argument cannot be a number primeiro argumento não pode ser um número 239 You cannot link more functions maxentry reached você não pode mais linkar funções número máximo de entradas alcançado 240 File s already exists or directory write access denied arquivo s já existe ou o acesso à escrita de diretório foi negado 241 File s does not exist or read access denied arquivo s não existe ou o acesso à leitura foi negado 242 Binary direct access files must be opened by file arquivos binários de acesso direto devem ser abertos por file 243 C file logical unit not allowed here unidade lógica do arquivo C não permitida aqui errortable 43 244 Fortran file logical unit not allowed here unidade lógica do arquivo FORTRAN não permitida aqui 245 No input file associated to logical unit d nenhum arquivo de entrada associado à unidade lógica d 246 Function not defined for given argument types função não definida para os tipos de argumentos fornecidos 247 Wrong value for argument d the lu handle is no more valid valor errado para o argumento d o manipulador lu não é mais válido 248 Wrong value for argument d Valid variable name expected valor errado para o argumento d esperava nome de variável válido 249 Wrong value for argument d Empty string expected valor errado para o argumento d esperava string vazio 250 Recursive extraction is not valid in this context extração recursiva não é válida neste contexto 251 bvode ipar dimensioned at least 11 bvode ipar dimensionado em pelo menos 11 252 bvode ltol must be of size ipar4 bvode ltol deve ser de tamanho ipar4 253 bvode fixpnt must be of size ipar11 bvode fixpnt deve ser de tamanho ipar11 254 bvode ncomp must be less than 20 bvode ncomp deve ser menor do que 20 255 bvode m must be of size ncomp bvode m deve ser de tamanho ncomp 256 bvode summ must be less than 40 bvode summ deve ser menor do que 40 257 bvode summ must be less than 40 bvode summ deve ser menor do que 40 258 bvode input data error bvode erro de dado de entrada 259 bvode no of subintervals exceeds storage bvode número de subintervalos excede o armazena mento 260 bvode Th colocation matrix is singular bvode a matriz de colocação é singular 261 Interface property table is full tabela de propriedades de interface está cheia 262 Too many global variablesmax number is d muitas variáveis globais O máximo é d 263 Error while writing in filedisk full or deleted file erro ao escrever em um arquivo disco cheio ou arquivo deletado 264 Wrong value for argument d Must not contain NaN or Inf valor errado para o argumento d não deve conter NaN ou Inf 265 A and B must have equal number of rows A e B devem ter o mesmo número de linhas 266 A and B must have equal number of columns A e B devem ter o mesmo número de colunas 267 A and B must have equal dimensions A e B devem ter dimensões iguais 268 Invalid return value for function passed in argd valor de retorno inválido para função pas sado no argumento d 269 Wrong value for argument d eigenvalues must have negative real parts valor errado para o argumento d autovalores devem ter partes reais negativas errortable 44 270 Wrong value for argument d eigenvalues modulus must be less than one valor errado para o argumento d módulos dos autovalores não devem ser menores que 1 271 Size varying argument aeye arg d not allowed here argumento de variação de tamanho aeye arg d não permitido aqui 272 endfunction is missing está faltando endfunction 273 Instruction left hand side waiting for a dot or a left parenthesis lado esquerdo da instrução esperava por um ponto ou parêntese esquerdo 274 Instruction left hand side waiting for a name lado esquerdo da instrução esperava um nome 275 varargout keyword cannot be used here palavrachave varargout não pode ser usada aqui 276 Missing operator comma or semicolon faltando operador vírgula ou pontoevírgula 277 Too many commands defined muitos comandos definidos 278 s Input arguments should have the same formal variable name s argumentos de entrada devem ter o mesmo nome de variável formal Ver Também warning errcatch execstr lasterror 45 Name evstr avaliação de expressões HevstrZ HierrevstrZ Parâmetros Z matriz de strings M ou listMSubexp M matriz de strings Subexp vetor de strings H matriz ierr inteiro indicador de erro Descrição Retorna o resultado da avaliação da matriz de strings M Cada elemento da matriz deve definir uma expressão Scilab válida Se a avaliação de M levar a um erro a versão de valor de único retorno HevstrM levanta erro de modo usual A versão de dois valores de retorno HierrevstrM por outro lado não produz erro mas retorna o número de erro em ierr Se Z é uma lista Subexp é um vetor de strings que define subexpressões que são avaliadas antes da avaliação de M Estas subexpressões devem ser referidas como k em M onde k é o índice da subexpressão em Subexp evstra1 não é válido use execstr ao invés Exemplos a1 b2 Zab evstrZ a1 b2 Zlist112a1b1 evstrZ Ver Também execstr 46 Name exists verifica existência de variáveis existsname where Parâmetros name string where um caractere opcional com possíveis valores l local n nolocal and a all O valor padrão é all Descrição existsname retorna 1 se a variável chamada name existe e 0 em caso contrário Aviso uma função que utiliza exists pode retornar um resultado que depende do ambiente existsnamelocal retorna 1 se a variável chamada name existe no ambiente local da função corrente e 0 em caso contrário existsnamenolocal retorna 1 se a variável chamada name existe em qualquer nível do ambiente de chamamento incluindo o nível principal do shell do Scilab da função corrente e 0 em caso contrário Aviso a função exists não verifica se a variável existe no espaço de nomes global Exemplos defffoox dispexistsa12existsa12local dispexistsxexistsxlocal foo1 a12foo1 function level1 function level2 dispexistsaall dispexistsalocal dispexistsanolocal endfunction level2 endfunction function go a1 level1 endfunction go Ver Também isdef isglobal whereis type typeof macrovar 47 Name exit termina a sessão Scilab corrente Descrição Termina a sessão Scilab corrente Ver Também quit abort break return resume 48 Name external objeto Scilab função ou rotina externa Descrição Função ou rotina externa para uso com comandos específicos Uma external é uma função ou rotina que é usada como argumento em algumas primitivas de alto nível tais como ode optim schur A seqüência de chamamento da external função ou rotina é imposta pela primitiva de alto nível que configura os argumentos da external Por exemplo a função externa costfunc é um argumento da primitiva optim Sua seqüência de chama mento deve ser fgindcostfuncxind e optim a primitiva de otimização de alto nível é invocada como segue optimcostfunc Aqui costfunc a função de custo a ser minimizada pela primitiva optim avalia ffx e g gradiente de f em x ind é um inteiro Seu uso é esclarecido na ajuda de optim Se a função externa necessita de outros valores estas variáveis podem ser definidas em seu ambiente Elas também podem ser colocadas em uma lista Por exemplo a função externa fgindcostfuncxindabc é válida para optim se o external função externa é listcostfuncabc e a chamada a optim é então optimlistcostfunca1b1c1 Um external também pode ser uma rotina FORTRAN ou C isto é conveniente para acelerar computações TO nome da rotina é fornecido para a primitiva de alto nível como um string A seqüência de chama mento da rotina também é imposta Rotinas FORTRAN ou C podem ser dinamicamente linkadas ligadas conectadas ver link Ver Também ode optim impl dassl intg schur gschur 49 Name extraction extração de entradas de matrizes e listas xi xij xijk li lk1kni ou llistk1kni lk1knij or llistk1knlistij Parâmetros x matriz de qualquer tipo possível l variável do tipo lista ij k índices k1kn índices Descrição CASO DE MATRIZES i j k podem ser escalares reais ou vetores ou matrizes com elementos positivos rxij constrói a matriz r tal que rlkxintilintjk para l de 1 a sizei e k de 1 a sizej O valor máximo de i j deve ser menor do que ou igual a sizex1 sizex2 rxi com x uma matriz 1x1 contrói a matriz r tal que rlkxintilintik para l de 1 a sizei1 e k para 1 a sizei2 Note que nesse caso o índice i é válido apenas se todas as suas entradas são iguais a 1 rxi com x um vetor linha constrói o vetor linha r tal que rlxintil para l de 1 a sizeii deve ter valor máximo menor do que ou igual a sizex rxi com x uma matriz com uma ou mais colunas constrói o vetor coluna r tal que rl l de 1 a sizei contém a entrada intil do vetor coluna formado pela concatenação das colunas de x i deve ter valor máximo menor do que ou igual a sizex O símbolo significa todos os elementos rxi constrói uma matriz r tal que rlkxintilk para l de 1 a sizei and k from 1 to sizex2 extraction 50 rxj constrói a matriz r tal que rlkxlintjk para l de 1 a sizer1 e k de 1 a sizej rx constrói o vetor coluna r formado pelas concatenações das colunas de x É equivalente a matrixxsizex1 vetor de booleanos Se um índice i ou j é um vetor de booleanos é interpretado como findi ou respec tivamente findj um polinômio Se um índice i ou j é um vetor de polinômios ou um vetor de polinômios implícito é interpretado como hornerim ou respectivamente hornerjn onde m e n são as dimensões associadas a x Mesmo se este recurso funcionar para todos os polinômios é recomendado utilizar polinômios em para legibilidade Para matrizes com mais de duas dimensoes verhypermatrices a dimensionalidade é automati camente reduzida quando as dimensões mais a direita são 1 CASO DE LISTAS OU TLISTS Se estiverem presentes os ki fornecem o endereço para uma entrada de sublista da estrutura de dados l Eles permitem uma extração recursiva sem cópias intermediárias As instruções lk1kni e llistk1kni são interpretadas como lk1 lk1 lkn lkn1kn lkni e as instruções lk1knij e llistk1knlistij são interpretadas como lk1 lk1 lkn lkn1kn lknij i e j podendo ser quando pontos de endereço sobre mais de um componente da lista a instrução deve ter tantos argumentos do lado esquerdo quanto os componentes selecionados Mas se a sintaxe de extração é usada dentro da seqüência de chama mento de entrada de uma função cada componente da lista retornado é adicionado à seqüência de chamamento da função Note que llist é o mesmo que l i e j podem ser escalares reais ou vetores ou matrizes de elementos positivos r1rnli extrai os elementos ik da lista l e armazenaos em variáveis rk para k de 1 a sizei O símbolo significa todos os elementos um vetor de booleanos Se i é um vetor de booleanos é interpretado como findi um polinômio Se i é um vetor de polinômios ou um vetor de polinômios implícito é interpretado como hornerim onde msizel Mesmo que este recurso funcione para todos os polinômios é recomendado utilizar polinômios em para legibilidade k1kn podem ser escalares reais posistivos extraction 51 um polinômio interpretado como hornerkim onde m é o tamanho da sublista correspondente string associado ao nome da entrada da sublista Observações Para tipos de matrizes softcoded como funções racionais e sistemas lineares de espaços de estados a sintaxe xi não pode ser usada para extração de elementos de vetores devido a confusões com extração de elementos de listas A sintaxe x1j ou xi1 deve ser usada Exemplos CASO DE MATRIZES a1 2 34 5 6 a12 a1 12 a1 a311 a1 a6 a at f f t at f2 3 a121 a112 a xteste x1 11 11 1 b1ss1s1 b11 b1 b2 o numerador CASO DE LISTAS OU TLISTS llist1qwerws l1 abl3 2 l xtlistl23 forma um tlist com os últimos dois componentes de l dtslist1tlistxab102 3 dts2a dts2b12 abdts2ab Ver Também find horner parents 52 Name for palavrachave de linguagem para laços loops significa para Descrição Usado para definir laços loops sua sintaxe é for variávelexpressão instrução instruçãoend for variável expressão do instrução instruçãoend Se expressão é uma matriz ou um vetor linha variável toma como valores os valores de cada coluna da matriz Um caso particular utiliza o operador colon para criar vetores linhas regularmente espaçados e re monta a formas de laço for tradicionais for variablen1stepn2 end Se expressão é uma lista variável toma como valores as entradas sucessivas da lista Aviso o número de caracteres usados para definir o corpo de qualquer instrução condicional if while for ou selectcase deve ser limitado a 16k Exemplos laços for tradicionais n5 for i 1n for j 1n aij 1ij1endend for j 2n1 ajj j end a for j 411 dispjend laço decrescente laço em colunas de matrizes for eeye33eend for va write6vend for j1nvaj write6vend laço em listas de entradas for llist12example lend Ver Também while end do 53 Name format impressão de números e formato de exibição formattypelong v format formatm Parâmetros type string long inteiro número máximo de digitos padrão 10 v um vetor para o formato corrente onde v1 é o de tipo de formato 0 para e e 1 para v v2 número de dígitos m um vetor para ajuste de novo formato m1 número de digitos m2 tipo de formato 0 para e e 1 para v Descrição Ajusta o formato de impressão corrente através do parâmetro type é um dos seguintes v para um formato variável default e para o formato e notação científica long define o número máximo de dígitos padrão 10 format retorna o vetor que indica o fomato corrente primeiro componente é o tipo do formato 1 se v 0 se e o segundo componente é o número de digitos No formato variável entradas de vetores que são menores que eps vezes o valor absoluto máximo das entradas era exibido como 0 em versões anteriores do Scilab Não é mais o caso a função de clean pode ser usada para ajustar as entradas negligenciáveis para zeros Exemplos xrand15 formatv10x format20x formate10x format20x x100 eps formate10x formatv10x format 54 formatv Ver Também write disp print 55 Name funcprot alterna o modo de proteção de funções Scilab protfuncprot funcprotprot Parâmetros prot inteiro com valores possíveis 01 ou 2 Descrição Funções Scilab são variáveis funcprot permite especificar o que o Scilab faz quando tais variáveis são redefinidas Se prot0 nada especial é feito Se prot1 o scilab exibe uma mensagem de aviso quando a função é redefinida modo padrão Se prot2 o scilab exibe uma mensagem de erro quando a função é redefinida Exemplos funcprot1 deffxfooaxa deffxfooaxa1 foo33 funcprot0 deffxfooaxa deffxfooaxa1 foo33 56 Name funptr codificação de primitivas numptr funptrname Parâmetros name string nome de uma primitiva numptr o número de rotina interno da primitiva Descrição Fução utilitária para usuários mais experientes apenas para retornar o número de rotina interno numptr da primitiva name numptr é formado a partir do número de interface fun e do número de rotina fin da primitiva em sua interface por numptr 100fun fin fin 100 De numptr podese obter o número de interface fun floornumptr100 que pode ser útil para ligar uma interface dinâmica com seus argumentos passados por referência ver seção de exemplos Exemplos Suponha que você queira carregar alguns códigos através das facilidades de carregamento dinâmico oferecidas por addinter Por padrão os argumentos são passados por valores mas se você quiser passálos por referência você pode fazer o seguinte nome sendo o nome scilab de uma das rotinas com interface addinterfilesspnamesfcts argumentos passados por valores numinterface floorfunptrnome100 intpptynuminterface argumentos agora passados por referência Note que se você digitar o seguinte intppty você verá todas as interfaces funcionando por referência Ver Também clearfun newfun intppty addinter 57 Name getdebuginfo retorna informações sobre o Scilab para o debug getdebuginfo dynamicinfo getdebuginfo dynamicinfostaticinfo getdebuginfo Descrição getdebuginfo retorna informações sobre o Scilab para o debug dynamicinfo getdebuginfo retorna informações sobre o seu sistema operacional dynamicinfostaticinfo getdebuginfo retorna informações sobre o seu sistema operacional e sobre o Scilab Ver Também getversion Autor AC 58 Name getmd5 retorna soma de verificação md5 resgetmd5filename resgetmd5ParamStringstring Parâmetros res resultado md5 string filename nome do arquivo string ou matrizes de strings ParamString string ou matrizes de strings Descrição getmd5 retorna a soma de verificação md5 de um arquivo ou um string Exemplos getmd5ola mundostring getmd5ola mundostring getmd5ola mundostring getmd5 SCImodulescoreetccorestart getmd5 SCImodulescoreetccorestart corequit Autor AC 59 Name getmemory retorna as memórias livre e total do sistema free totalgetmemory Descrição getmemory retorna a memória livre do sistema em kilooctetos free totalgetmemory retorna as memórias livre e total do sistema em kilooctetos Autor AC 60 Name getmodules retorna a lista de módulos instalados no Scilab resgetmodules Parâmetros res uma matriz de strings Descrição Retorna a lista de módulos instalados no Scilab Ver Também withmodule Autor Ac 61 Name getos retorna o nome e a versão do Sistema Operacional OSgetos OSVersiongetos Descrição getos retorna o nome e a versão do Sistema Operacional Exemplos OSgetos OSversiongetos Autor AC 62 Name getscilabmode retorna o modo do Scilab mode getscilabmode Descrição Retorna o modo do Scilab Quatro são os possíveis modos STD API NW NWNI API o Scilab é lançado como um API STD o Scilab padrão gui plot NW Scilab em linha de comando com esboços NWNI Scilab em linha de comando sem quaisquer gráficos Exemplos getscilabmode Ver Também scilab 63 Name getshell retorna o interpretador de comando corrente getshell Descrição getshell retorna o interpretador de comando corrente Exemplos getshell Autor Allan CORNET 64 Name getvariablesonstack retorna nomes de variáveis em na pilha Scilab sgetvariablesonstack sgetvariablesonstacklocal sgetvariablesonstackglobal Parâmetros s uma matriz de strings Descrição Retorna na variável s nomes de variáveis na pilha do Scilab getvariablesonstacklocal retorna o nome das variáveis locais na pilha getvariablesonstackglobal retorna o nome das variáveis globais na pilha As variáveis são organizadas na ordem alfabética Exemplos getvariablesonstack getvariablesonstacklocal getvariablesonstackglobal Ver Também who 65 Name getversion retorna o nome da versão do Scilab versiongetversion versionoptsgetversion vergetversionscilab versioninfogetversionscilabstringinfo vergetversionmodule versioninfogetversionmodulestringinfo Parâmetros version um string versioninfo um string sobre a versão ver um vetor de inteiros ver1 versão maior ver2 versão menor ver3 versão de manutençãp ver4 timestamp GIT opts um vetor de strings de 7 entradas compiler pvm tk modelicac releasemode releasedate releasetime Descrição Retorna em version o nome da versão do Scilab e em opts build options opções de construção que podem ser usadas para determinar se o Scilab foi construído em pvm tk ou modelicac Exemplos getversion versionoptsgetversion vergetversionscilab verstrgetversionscilabstringinfo vergetversionoverloading verstrgetversionoverloadingstringinfo Ver Também getmodules 66 Name global define variável global globalnam1namn global nam1 namn Parâmetros nam1 namn nomes de variáveis válidos Descrição De um modo simples cada função do Scilab possui suas próprias variáveis locais e pode ler todas as variáveis criadas no espaço de trabalho base ou pelas funções de chamamento A palavrachave global permite realizar leituras ou escritas de variáveis através de funções Qualquer atribuição àquela variável em qualquer função está disponível para todas as outras funções que a declaram como variável global Se a variável global não existe não possui valor na primeira vez em que você escrever a declara como global será inicializada como matriz nula Exemplos primeiro o ambiente de chamamento e uma função compartilham uma variável global a a1 deffyf1xglobal aax2ya2 f12 a segundo três funções compartilham variáveis deffinitdataglobal A C A10C30 deffletsgoglobal A C dispA C70 deffletsgo1global C dispC initdata letsgo letsgo1 Ver Também who isglobal clearglobal gstacksize resume 67 Name gstacksize Ajustaretorna a pilha global do Scilab gstacksizen gstacksizemax gstacksizemin szgstacksize Parâmetros n inteiro o tamanho da pilha global requerido dado em número das palavras de dupla precisão sz vetor de duas entradas total used Descrição Scilab armazena variáveis globais em uma pilha gstacksizen permite ao usuário aumentar ou diminuir o tamanho da pilha O tamanho máximo permitido depende da quantidade de memória livre e do espaço de troca swap space disponível no momento Note que o Scilab pode aumentar automaticamente o tamanho da pilha global quando necessário szgstacksize retorna um vetor de duas entradas que contém os tamanhos de pilha global total e usado correntes gstacksizemax permite que o usuário aumente o tamanho desta pilha global ao máximo gstacksizemin permite que o usuário diminua o tamanho desta pilha global para máximo Ver Também who stacksize 68 Name hat exponentiation Ab Descrição Exponenciação de matrizes ou vetores por um vetor constante Se A é um vetor ou uma matriz retangular a exponenciação é feita elemento a elemento no sentido usual Para matrizes quadradas a exponenciação é feita no sentido matricial Para matrizes de booleanos polinômios ou razões de polinômios o expoente deve ser um inteiro Observações 123b é interpretado como 123b Em tais casos o ponto é parte do operador não do número Para dois números reais ou complexos x1 e x2 o valor de x1x2 é o valor principal determinado por x1x2 expx2logx1 Exemplos 24 0513 1 22 41i spoly0s 1 2 s4 s 11 s1 Ver Também exp inv 69 Name ieee ajusta o modo de exceção de ponto flutuante modieee ieeemod Parâmetros mod escalar inteiro com possíveis valores 01ou 2 Descrição ieee retorna o modo de exceção de ponto flutuante corrente 0 exceção de ponto flutuante produz um erro 1 exceção de ponto flutuante produz um aviso 2 exceção de ponto flutuante produz um Inf ou NaN infinito ou não é número ieeemod ajusta o modo corrente de excessão de ponto flutuante O valor de modo incial é 0 Observações Exceções de ponto flutuante emergentes em alguns algoritmos de bibliotecas ainda não são manipu ladas pelos modos ieee Exemplos ieee110 ieee210log0 Ver Também errcatch 70 Name if then else Execução condicional significa se então senão if expressão1 then sentenças elseif expressãoi then sentenças else sentenças end Descrição A sentença if avalia sentenças lógicas e executa um grupo de sentenças se a expressão é verdadeira As expressõesi são expressões com valores numéricos ou booleanos Se as expressõesi são matrizes a condição é verdadeira somente se todas as entradas da matriz são true verdadeiro ou diferentes de 0 Os opcionais elseif e else propiciam execução de grupos de sentenças alternativas A palavra chave end keyword que corresponde ao iftermina o último grupo de sentenças A estrutura de linhas dada acima não é importante a única restrição é que cada palavrachave thendeve estar na mesma linha de sua palavrachave if ou elseif correspondente A palavrachave then pode ser substituída por um retorno de carro ou uma vírgula Aviso o número de caracteres utilizados para definir o corpo de qualquer instrução condicional if while for or selectcase deve ser limitado a 16k Exemplos i2 for j 13 if i j then aij 2 elseif absij 1 then aij 1 else aij 0 end end Ver Também try while select boolean end then else 71 Name insertion atribuição ou modificação parcial de variáveis assignation atribuição parcial de variáveis xija xia lia lk1knia or llistk1knia lk1knija or llistk1knlistija Parâmetros x matriz de qualquer tipo l lista ij índices k1kn índices com valores inteiros a novo valor de entrada Descrição CASO DE MATRIZES Se x é uma matriz os índices i e j podem ser Escalares reais vetores ou matrizes neste caso os valores fornecidos como índices devem ser inteiros e apenas suas partes inteiras são levadas em consideração Se a é uma matriz com dimensões sizeisizej xija re torna uma nova matriz x tal que xintilintjkalk para l de 1 a sizei e k de 1 a sizej as outras entradas iniciais de x não são modificadas Se a é um escalar xija retorna uma nova matriz x tal que xintilintjka para l de 1 a sizei e k de 1 a sizej as outras entradas iniciais de x não são modificadas Se o valor máximo de i ou j exceder a dimensão correspondente da matriz x o array x é previamente estendido para as dimensões requeridas com entradas 0 para matrizes padrões strings de comprimento 0 para matrizes de strings e valores falsos para matrizes de booleanos xij cancela linhas especificadas por i se j corresponde a todas as colunas de x ou cancela colunas especificadas por j se i corresponde a todas as linhas de x Em outros casos xij produz um erro xia com a um vetor retorna a nova matriz x tal que xintilal para l de 1 a sizei outras entradas iniciais de x não são modificadas xia com a um escalar retorna uma nova matriz x tal que xintila para l de 1 a sizei outras entradas iniciais de x não são modificadas insertion 72 Se o valor máximo de i exceder sizex1 x é previamente estendida para a dimensão requerida com entradas 0 para matrizes padrões strings de comprimento 0 para matrizes de strings e valores falsos para matrizes de booleanos Se x é uma matriz 1x1 a pode ser um vetor linha respectivamente coluna com dimensão sizei A matriz x resultante é um vetor linha respectivamente coluna Se x é um vetor linha a deve ser um vetor linha de dimensão sizei Se x é um vetor coluna a deve ser um vetor coluna de dimensão sizei Se x é uma matriz geral a deve ser um vetor linha ou coluna de dimensão sizei e o valor máximo de i não pode exceder sizex xi cancela entradas especificadas por i O símbolo O símbolo significa todos os elementos xia é interpretado como xi1sizex2a xja é interpretado como x1sizex1ja xa retorna em x a matriz a de forma redefinida de acordo com as dimensões de x sizex deve ser igual a sizea Vetores de booleanos se um índice i ou j é um vetor de booleanos é interpretado como findi ou respec tivamente findj Polinômios se um índice i ou j é um vetor de polinômios ou um vetor de polinômios implícito é interpretado como hornerim ou respectivamente hornerjn onde m e n são as dimensões associadas de x Mesmo se esse recurso funcionar para todos os polinômios é recomendado utilizar polinômios em para legibilidade CASO DE LISTAS OU TLISTS Se estiverem presentes os ki fornecem o endereço para uma entrada de sublista da estrutura de dados l data structure Eles permitem uma extração recursiva sem cópias intermediárias As instruções lk1knia e llistk1knia são interpretadas como lk1 lk1 lkn lkn1kn lkni a lkn1kn lkn lk1 lk1 insertion 73 E as instruções lk1knija e llistk1knlistija são interpretadas como lk1 lk1 lkn lkn1kn lknij a lkn1kn lkn lk1 lk1 i pode ser Um escalar real nãonegativo l0a adiciona uma entrada à esquerda da lista lia configura a entrada i da lista l como a Se isizel l é previamente estendido com entradas de comprimento 0 indefinidas linull suprime a iésima entrada da lista Um polinômio Se i é um polinômio é interpretado como hornerim onde msizel Mesmo se este recurso funcionar para todos os polinômios é recomendado utilizar polinômios em para legibilidade k1kn podem ser Escalares reais positivos Polinômios interpretados como hornerkim onde m é o tamanho da sublista corre spondente Strings associados a nomes de entradas de uma sublista Observações Para tipos de matrizes softcoded como funções racionais e sistemas lineares de espaços de estados a sintaxe xi não pode ser usada para inserção de entradas em vetores devido a confusões com inserção de entradas em listas A sintaxe x1j ou xi1 deve ser usada Exemplos CASO DE MATRIZES a1 2 34 5 6 a1210 a1 1212 a185 a131177 44 99 a1s a6s1 a16 at f133 a12124 a11187 a123 xteste x4 545 b1ss1s1 b110 b1b11 insertion 74 b21 2 o numerador CASO DE LISTAS OU TLISTS llist1qwerws l1Modificado l0Adicionado l6mais umadicionado dtslist1tlistxab102 3 dts2a33 dts2b12100 Ver Também find horner parents extraction 75 Name intppty ajusta propriedades de passagem de argumentos de interface funsintppty intpptyfun Parâmetros fun inteiro um número de interface ver funptr funs vetor de inteiros vetor de números de interface ver funptr Descrição Os programas de interface pode ser escritos de duas formas diferentes para o modo de passagem de argumento de funções No primeiro modo que é o padrão os argumentos são passados por valor A sintaxe é a seguinte fooA12 o argumento associado a A será passado por valores uma cópia de A é feita antes de foo i ser chamada e o argumento associado a 12 será passado por valor No segundo modo os argumentos podem ser passados por referência se houver argumentos nomea dos nenhuma cópia do valor da variável é feita intpptyfun com fun0 diz ao Scilab que a interface com o número fun pode manipular argumentos passados por referência A sintaxe é a seguinte fooA12 O argumento associado a A será passado por referência e o argumento associado a 12 será passado por valor Aviso a declaração de interface com número fun pode manipular argumentos passados por referência se não for o caso de produzir resultados imprevisíveis intpptyfun com fun0 suprime esta propriedade para para a interface fun intppty retorna o vetor de interfaces que manipulam argumentos passados por referência Esta função pode ser útil para interfaces dinamicamente carregadas ver addinter Ver Também funptr addinter 76 Name invcoeff constrói uma matriz de polinômios a partir de seus coeficientes PinvcoeffCdname Parâmetros C matriz grande de coeficientes d grau da matriz de polinômios Parâmetro opcional com valor padrão d1sizeCc sizeCr name string fornecendo o nome da variável polinomial valor padrão x Descrição PinvcoeffMpk quando k é compatível com o tamanho de Mp size retorna uma matriz de polinômios de grau k CC0C1Ck and P C0 C1x Ckxk Exemplos Aint10rand26 Construindo uma matriz de polinômios de grau 1 PinvcoeffA1 normcoeffPA Usando valor padrão para o grau P1invcoeffA normcoeffP1A Ver Também poly degree coeff 77 Name iserror teste de ocorrência de erros iserrorn Descrição Testa se um número de erro n ocorreu após uma chamada a errcatch iserror retorna 1 se o erro ocorreu e 0 caso contrário n0 é o número do erro todos os erros são testados com n0 Ver Também error errcatch 78 Name isglobal verifica se uma variável é global tisglobalx Parâmetros x qualquer variável t um valor booleano Descrição isglobalx retorna true verdadeiro se x tiver sido declarada como variável global e false falso em caso contrário Exemplos isglobal1 global a isglobala Ver Também global clearglobal who 79 Name lasterror retorna a última mensagem de erro registrada strlasterror opt strnlasterroropt strnlinefunclasterroropt Parâmetros str vetor de strings ou matriz vazia a última mensagem de erro registrada n inteiro 0 ou o último número de erro registrado line inteiro 0 ou o último número de linha da função registrado func string o último nome da função registrado opt booleano se t for registrado a mensagem é limpa O padrão é t Descrição Cada vez que um erro ocorre o manipulador de erros do Scilab o registra em tabelas tables internas apenas o último erro é retido A função lasterror permite obter a mensagem de erro o número de erro a função corrente se houver e a linha corrente da função corrente destas tabelas O número de linha reportado é o número da linha física onde o último erro ocorreu Note que versões Scilab anteriores à 50 reportavam o número da linha lógica do último erro A diferença realmente importa apenas se a função em erro inclui linhas continuadas antes do ponto onde o erro ocorreu Esta função é útil quando usada em conjunto com errcatch ou execstr A mensagem de erro pode ser retida para uma futura chamada a lasterror usando lasterrorf Exemplos ierrexecstrazzzzzzzerrcatch if ierr0 then displasterrorend Ver Também errcatch execstr error errclear editerror 80 Name left colchete esquerdo a11a12a21a22 s1s2func Parâmetros a11a12 matriz de qualquer tipo compatível com dimensões compatíveis s1s2 qualquer nome de variável possível Descrição Colchetes esquerdo e direito são usados para concatenação de vetores e matrizes Estes símbolos também são utilizados para denotar um lado esquerdo múltiplo para uma chamada de função Dentro de colchetes de concatenação espaços em branco ou vírgulas significam concatenação de colunas pontosevírgulas e retornos de carro significam concatenação de linhas Nota para evitar confusões é preferível que se use vírgula no lugar de espaços em branco para separar colunas Dentro de colchetes de lado esquerdo múltiplo nomes de variáveis devem ser separados por vírgula Exemplos 69964 sqrt1 0 1 i 2 i 3 this isa stringvector spoly0s1s2s tf2ss1stf2ss2s usschurrand33 Ver Também comma semicolon 81 Name less comparação menor do que great comparação maior do que Descrição Símbolo de comparação lógica significa diferente é o mesmo que significa menor do que significa maior do que significa maior do que significa maior do que ou igual a Ver Também if comparison equal 82 Name macr2lst conversão de função para lista txtmacr2lstfunctionname Descrição Esta primitiva converte uma versão compilada do Scilab functionname em uma lista que codifica a representação interna da função notação polonesa inversa A primeira entrada da lista é o nome da função as segunda e terceira são respectivamente os vetores das variáveis de lado esquerdo e direito lhs e rhs As entradas seguintes são registros de operação básica ou listas que contém as estruturas de controle hierárquicas como if for Registros de operação básica são descritos por um vetor de strings cujo primeiro elemento representa código do operador op code op codes significado parâmetros 0 opcode ignorado nenhum 1 não mais usado 2 referência à função ou variável nome da variável rhs lhs 3 coloca um string na pilha um string 4 coloca uma matriz vazia na pilha nenhum 5 aplica uma operação código de operação rhslhs 6 coloca um número na pilha o número 12 comando pause nenhum 13 comando break nenhum 14 comando abort nenhum 15 marca de fim da linha nenhum 17 comando quit nenhum 18 variável nomeada nome da variável 19 cria estrutura de índice recursiva comprimento do endereço número de índices finais 20 chamada a função nome da função rhs lhs 23 cria variável a partir do nome nome da variável 24 coloca uma variável de tipo 0 na pilha nenhum 25 registro de perfil número da chamada gasto de tempo 26 coloca um vetor de strings na pil ha linhas colunas seqüência de elementos 27 coloca uma referência a um builtin na pilha número da interface posição da interface nome da função 28 comando continue nenhum 29 atribuição lhs modo de exibição nome da variável rhs 30 curto circuito de expressão lógica tipo tamanho do salto jump macr2lst 83 31 comentário o comentário 99 comando return nenhum 100 chamada a um builtin obsoleto 100fun rhs lhs fin A função fun2string pode ser usada para se gerar o código inicial Exemplos EXIBIÇÃO function yfooxflag if flag then ysinx else ycosx end endfunction Lmacr2lstfoo fun2stringL Ver Também macrovar fun2string macr2tree tree2code 84 Name macr2tree conversão de função para árvore tmacr2treefunctionname Parâmetros functionname macro do Scilab t uma árvore do Scilab Descrição Esta primitiva converte uma função Scilab compilada functionname em uma árvore tlistas im bricadas que codifica a representação interna da função Deve ser usada com tree2code Exemplos treemacr2treecosh txttree2codetreeT writeio2txta Ver Também tree2code Autor VC 85 Name matrices objeto do Scilab matrizes Descrição Matrizes são objetos básicos definidos no Scilab Elas podem ser definidas como segue Ee11e12e1n e21e22e2n em1em2emn As entradas eij podem ser números reais complexos polinômios razões de polinômios strings ou booleanos Vetores são vistos como matrizes de uma linha ou uma coluna Exemplos E1234 ETF1111 spoly0sEss211s E1s0s1s1 EA11A12A21A22 Ver Também poly string boolean rational empty hypermatrices 86 Name matrix Muda a forma de vetores ou matrizes ymatrixvnm ymatrixvsizes Parâmetros v vetor matriz ou hipermatriz nm inteiros sizes vetor de inteiros y vetor matriz ou hipermatriz Descrição Para um vetor ou matriz com n x m entradas o comando ymatrixvnm ou de modo similar ymatrixvnm transforma o vetor ou matriz v em uma matriz nxm empilhando as entradas coluna a coluna de v Se uma das dimensões m ou n é igual a 1 ela é automaticamente atribuída ao quociente de tamanho v pela outra dimensão Para uma hipermatriz tal como prodsizevprodsizes o comando ymatrixvsizes ou equivalentemente ymatrixvn1n2nm transforma v em uma matriz ou hipermatriz empilhando coluna a coluna as entradas de v a primeira dimensão var iando primeiro ymatrixvsizes resulta numa matriz regular se os tamanhos são escalares ou um vetor de duas entradas Exemplos a1 2 34 5 6 matrixa16 matrixa11 matrixa32 Ver Também matrices hypermatrices ones zeros rand poly empty 87 Name mode seleciona um modo em um arquivo executável modek kmode Descrição Usado exclusivamente dentro de um arquivo executável ou uma função do Scilab modek permite mudar as informações exibidas durante a execução dependendo do valor de k k0 os novos valores de variáveis são exibidos se requeridos ver ajuda em semi ou comma k1 o arquivo executável ou a função Scilab roda silenciosamente este é o valor padrão para funções do Scilab k1 or k3 cada linha de instruções é ecoada precedida do prompt se possível Os novos valores de variáveis são exibidos se requerido Este é o padrão para arquivos executáveis k7 Os novos valores de variáveis são exibidos se requerido Cada linha de instruções é ecoada se possível e um prompt aparece após cada linha esperando por um retorno de carro Se o retorno de carro segue o caractere p a execução é pausada ver pause A exibição de linha é desabilitada para funções do Scilab compiladas ver comp Por padrão funções do Scilab são executadas no modo silencioso 1 Ver Também exec semicolon comma 88 Name mtlbmode alterna para modo de operações do Matlab mmodemtlbmode mtlbmodemmode Parâmetros mmode booleano Descrição Adições e subtrações do Scilab e do Matlab funcionam de modo diferente quando usadas com matrizes vazias Scilab a a a a a a a a Matlab a a a a mtlbmodet alterna para o modo de operações para adição e subtração do Matlab mtlbmodef volta para o modo de operações do Scilab mtlbmode retorna o valor mmode corrente Ver Também empty 89 Name names scilab names syntax Descrição Nomes de variáveis ou funções no Scilab devem começar com uma letra ou com um dos seguintes caracteres especiais Os próximos caracteres podem ser letras ou um dos seguintes caracteres especiais Nomes podem ser tão longos quanto se queira mas apenas os primeiros 24 caracteres serão levados em consideração Letras maiúsculas e minúsculas são diferentes Exemplos Nomes válidos eps A1123 Color8 MySpecialColorTablerand103 Nomes inválidos 1A b C 90 Name newfun adiciona um nome à tabela de funções newfunfunctionnamenameptr Descrição Função utilitária apenas para peritos Adiciona o nome functionname à tabela de funções conhecidas pelo interpretador nameptr é um inteiro 100funfin onde fun e fin é a codficação interna da primitiva functionname Esta função é útil para associar uma primitiva a uma rotina com interface em matusrf fun14 Usado com funptr e clearfun pode se redefinir uma primitiva por uma função com o mesmo nome Ver Também clearfun 91 Name null deleta um elemento em uma lista linull Descrição Deleta objetos dentro de uma lista Exemplos llist123 l2null retorna list13 Ver Também list clear 92 Name parents parênteses esquerdo e direito expressão funce1e2 x1x2e1e2 xij vi li Parâmetros x matriz de qualquer tipo possível v vetor linha ou coluna de qualquer tipo possível l variável tipo lista func qualquer nome de função e1e2 qualquer tipo possível de expressão Descrição Parênteses esquerdo e direito são usados para Especificar ordem de avaliação dentro de expressões Formar listas de argumentos do lado direito de uma função Dentro de lados direitos múltiplos os argumentos devem ser separados por vírgula Selecionar elementos dentro de vetores matrizes e listasVer ajuda em insertion e extraction para maiores informações x1x2e1e2 é equivalente a realizar primeiro t1 e1 t2 e2 e então x1 t1 x2 t2 onde as variáveis ti i 1 2 são visíveis ao usuário Exemplos 31 xpoly0x x102 i3eye33 a1 2 34 5 67 8 9a13a1 3a3 a3 a133 a2 1 a1101112 parents 93 wssrand222ssprintw ssprintw1 ss2tfw1 llist1234 abcdl l1novo vt1 1 1 1 1 xyz123 Ver Também colon comma brackets list extraction insertion 94 Name pause modo de pausa invoca teclado Descrição Alterna para o modo pause inserido no código de uma função pause interrompe a execução da mesma recebese um símbolo de prompt para indicar o nível de pause exemplo 1 O usuário está agora num novo espaço de trabalho em que todas as variáveis de nível infeiror em particular todas as variáveis da função estão disponíveis Para retornar ao espaço de trabalho de chamamento entre return Neste modo return retorna as variáveis dos argumentos ao espaço de trabalho de chamamento com nomes na saída Em caso contrário as variáveis de nível infeiror são protegidas e não podem ser modificadas pause é extremamente útil para propósitos de depuramento Este modo pode ser cancelado pelo comando abort Ver Também halt return abort quit whereami where sleep 95 Name percent caractere especial Descrição Alguns nomes de variáveis predefinidas começam com tais como i para sqrt1 inf para Infinity pi para 314 T para a constante booleanatrue Ainda funções cujo nome começa com são especiais elas são usadas para primitivas e overloading sobrecarga de operadores ver overloading Por exemplo a função rmr realiza a operação de multiplicação m xy para x e y matrizes de razões de polinômios r As convenções de codificação são fornecidas pelo arquivo leiame no diretório SCIDIRmacrospercent Exemplos x1tlistx12 x2tlistx23 deffxxmxx1x2xlistxx12x22x23x23 x1x2 Ver Também overloading 96 Name perl chama script Perl utilizando um executável apropriado do sistema operacional perlperlfile perlperlfilearg1arg2 result perl Descrição perlperlfile chama o script Perl perlfile utilizando o executável Perl apropriado do sistema opera cional perlperlfilearg1arg2 chama o script Perl perlfile utilizando o executável Perl apropriado do sistema operacional e passa os argumentos arg1 arg2 e assim por diante a perlfile result perl retorna os resultados de uma chamada a Perl tentada para result Ver Também unix Autor AC 97 Name plus operador de adição XY str1str2 Parâmetros XY escalar vetor ou matriz de números polinômios ou razões de polinômios Também pode ser uma lista syslin str1str2 um string um vetor ou uma matriz de strings Descrição Adição Para operandos numéricos é a adição em sentido usual Se um dos operandos é uma matriz e o outro um escalar o escalar é adicionado a cada uma das entradas da matriz Se um dos operandos é a matriz vazia um o outro operando é retornado este comportamento padrão pode ser modificado pela função mtlbmode Para strings significa concatenação A adição também pode ser definida para outros tipos de dados através de operações softcod ed codificação suave ver overloading Ver Também 121 2 spoly0s s2 1s2 catenate See Also addf mtlbmode overloading 98 Name poly definição de polinômios ppolyax flag Parâmetros a matriz ou número real x String o nome da variável simbólica Se o string tiver mais de 4 caracteres apenas os quatro primeiros serão levados em conta flag string roots coeff valor padrão é roots Descrição Se a é uma matriz p é o polinômio característico ie determinantxeyea x sendo a variável simbólica Se v é um vetor polyvxroots é o polinômio com entradas de v como raízes e x como variável formal neste caso roots e poly são funções inversas Note que infinitas raízes fornecem zero coeficientes de grau mais elevado polyvxcoeff cria o polinômio com símbolo x e com entradas de v como co eficientes v1 é o termo constante do polinômio aqui poly e coeff são funções inversas spoly0s é a fonte para definir polinômios com símbolo s Exemplos spoly0sp1s2s2 Arand22polyAx frações racionais h12spoly14sc See Also coeff roots varn horner derivat matrices rational 99 Name power operação de potenciação tAb tAb tAb Parâmetros At matriz de escalares polinômios ou razões de polinômios b um escalar ou um vetor ou matriz de escalares Descrição AsquarebscalarSe A é uma matriz quadrada e b é um escalar então Ab é a matriz A elevada à potência b AmatrixbscalarSe b é um escalar e A uma matriz então Ab é formada pelos elementos de A elevados à potência b potenciação elemento a elemento Se A é um vetor e b é um escalar então Ab e Ab realizam a mesma operação ie potenciação elemento a elemento Ascalarbmatrix Se A é um escalar e b é uma matriz ou vetor então Ab e Ab são as matrizes ou vetores formados por abij Amatrixbmatrix Se A e b são vetores matrizes de mesmo tamanho Ab é o vetor Aibi matriz Aijbij Notas Para matrizes quadradas Ap é computada através de sucessivas multiplicações de matrizes se p is é um número inteiro positivo e por diagonalização se não for Os operadores e são sinônimos Exemplos A1 23 4 A25 A25 1102 1102 spoly0s s110 Ver Também exp 100 Name predef proteção de variáveis npredef oldnewpredefn oldnewpredefall oldnewpredefclear Descrição Função utilitária para definir as variáveis mais antigas como protegidas Variáveis protegidas não podem ser cancelada Elas não são salvas pelo comando save As variáveis mais antigas são aquelas que aparecem por último em whoget predef retorna o número de variáveis protegidas predefall ajusta todas as variáveis como protegidas também retorna o número antigo e o novo de variáveis protegidas predefclear desprotege todas as variáveis exceto as 7 últimas e também retorna o número antigo e o novo de variáveis protegidas predefn ajusta as maxn7 últimas variáveis definidas como protegidas também retorna o número antigo e o novo de variáveis protegidas Observação Um número de variáveis protegidas está configurado no arquivo de startup inicialização SCI etcscilabstart O usuário pode em particular configurar suas próprias variáveis pre definidas nos arquivos de inicialização do usuário SCIHOMEscilab e SCIHOMEscilabini Definição SCIHOME no Windows CDocuments and SettingsUserScilabScilabVersion No LinuxUnix homeUserScilabScilabVersion Ver Também clear save 101 Name quit Decresce o nível de pausa ou termina o Scilab quit Descrição O comando quit tem dois significados diferentes dependendo do contexto de chamamento Se não houver pause ativo Então o comando quit faz o Scilab terminar mesmo que o comando seja chamado dentro de uma função Se houver pause ativo Então o comando quit aborta instruções iniciadas neste nível de pausa e termina o nível de pausa corrente Exemplos Saindo do Scilab function fooxif x then quitendendfunction foot quits scilab terminando instrução iniciada num contexto de pausa function fooxif x then quitendendfunction pause foot retorna ao nível de prompt principal function foo1x mprintfP1 if x then pause mprintfP2 end mprintfP3 endfunction foo1t enter com quit no prompt seguinte Ver Também pause break abort exit 102 Name quote transpose operator string delimiter Descrição quote aspas é usado para a transposta conjugada de uma matriz quote é usado para a transposta nãoconjugada de uma matriz Aspas simples ou duplas também são usadas para definir strings strings são definidos por aspas nas extremidades Aspas simples dentro de um string são denotadas por duas aspas simples e aspas duplas são denotadas por uma aspas simples e uma dupla Exemplos 1i 2 1i 2 xIsto é um string Ele disse Bom 103 Name rational objeto do Scilab razão de polinômios Descrição Um razão de polinômios r é um quociente entre dois polinômios rnum den A representação interna de uma razão de polinômios é uma lista rtlistrnumdendtnumden é o mesmo que rnumden Uma matriz de razões de polinômios pode ser definida pela sintaxe usual por exem plo r11r12r21r22 ié uma matriz 2x2 onde rij são razões 1x1 Uma ma triz de razões de polinômios também pode ser definida como acima como uma lista tlistrnumdendtnumden com num e den matrizes de polinômios Exemplos spoly0s W1s1s1 WW Numss21sDenssssss tlistrnumdendtNumDen HNumDen syslincNumDen syslincH Num1Den1simpNumDen Ver Também poly syslin simp 104 Name readgateway retorna a lista de primitivas de um módulo readgatewaymodulename primitives readgatewaymodulename primitivesprimitivesID readgatewaymodulename primitivesprimitivesIDgatewayID readgatewaymodulename Descrição Retorna a lista de primitivas de um módulo Primitives lista de primitivas de um módulo primitivesID lista de identificadores das primitivas gatewayID lista de identificadores de portas de ligaçãos associados ao módulo Exemplos primitivesprimitivesIDgatewayID readgatewaycore primitives1 primitiva debug primitive primitivesID1 1 é o ID de debug na porta de ligação de core gatewayID1 13 é o ID da porta de ligação de core no Scilab Ver Também getmodules 105 Name resume retorna ou pára a execução de uma função e copia algumas de suas variáveis locais resume x1xnresumea1an Parâmetros x Descrição Em uma função resume pára a execução da mesma resume pára a execução de uma função e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi No modo pause permite retornar a um nível inferior resume retorna ao nível inferior e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi Em um execstr chamado por uma função resume pára a execução da função e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi resume é equivalente a return Ver Também abort break 106 Name return retorna ou pára a execução de uma função e copia algumas de suas variáveis locais return x1xnreturna1an Parâmetros x Descrição Em uma função return pára a execução da mesma return pára a execução de uma função e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi No modo pause permite retornar a um nível inferior return retorna ao nível inferior e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi Em um execstr chamado por uma função return pára a execução da função e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi resume é equivalente a return Ver Também abort break 107 Name sciargs scilab command line arguments argssciargs Descrição Esta função retorna um vetor de strings contendo os argumentos da linha de comando do Scilab As primeiras entradas de args contém o endereço do arquivo executável rodado Esta função corresponde a getarg na linguagem C Ver Também getenv 108 Name scilab principal script unix para executar o Scilab e ferramentas de miscelânea scilab Options Descrição args Arguments Se esta opção estiver presente os argumentos são passados ao Scilab Eles podem ser recebidos pela função sciargs para passagem de múltiplos argumentos use seqüências de palavras separadas por espaços entre aspas simples scilab args foo1 foo2 display Display Para uso apenas em sistemas Xwindow para ajustar um display de servidor X O display padrão é unix00 display pode ser abreviado por d debug Inicia o Scilab no debugger gdb apenas para Unixlinux e Instrução Se esta opção estiver presente então a instrução Scilab Instrução é executada primeiro logo após a execução do arquivo de inicialização no Scilab As opções e e f são mutuamente exclusivas f arquivo Se esta opção estiver presente então o script Scilab arquivo é executado primeiro logo após a execução do arquivo de inicialização no Scilab As opções e e f são mutuamente exclusivas l idioma Se esta opção estiver presente ela fica o idioma do usuário Os possíveis valores para idioma são fr para francês en para inglês e br para português brasileiro O idioma padrão é inglês O valor padrão é fixado no arquivo scilabstart mem N Ajusta o tamanho de pilha inicial para uso com a opção ns Sem a opção ns a pilha inicial é ajustada pelo script scilabstart nb Se esta opção está presente então o cartão de boasvindas não é impresso ns Se esta opção está presente o arquivo de inicialização SCIetcscilabstart e os arquiv os de inicialização do usuário SCIHOMEscilab SCIHOMEscilabini não são execu tados nouserstartup Se esta opção estiver presente os arquivos de inicialização do usuário SCIHOMEscilab SCIHOMEscilabini não são executados nw Se esta opção estiver presente então o Scilab não é executado em uma janela específica nwni Se esta opção estiver presente então o Scilab não é executado em uma janela específica e não aceita interação do usuário Esta opção pode ser utilizada com as opções f ou e scilab 109 texmacs Esta opção é reservada para TexMacs version Esta opção imprime a versão do produto e sai 110 Name select Palavrachave da estrutura select significa selecionar de acordo com a variável Descrição select expressão case expressão1 then instruções1 case expressão2 then instruções2 case expressãon then instruçõesn else instruções end Notas A única restrição é de que a palavrachave then deve estar na mesma linha que a palavrachave case correspondente A palavrachave then pode ser substituída por uma vírgula ou um retorno de carro instruçõesi são executadas se expressãoiexpressão Aviso o número de caracteres usados para definir o corpo de qualquer instrução condicional if while for ou selectcase deve ser limitado a 16k Exemplos while t do nround10rand11 select n case 0 then disp0 case 1 then disp1 else break end end Ver Também if while for 111 Name semicolon fim de expressão e separador de linhas Descrição Pontosevírgulas são usados para separar linhas em uma definição de matrizes Pontosevírgulas também podem ser usados para indicar o fim de uma instrução Neste caso indica que os resultados não serão exibidos Se desejar exibição use vírgula Exemplos a123456 a1b1c2 Ver Também comma brackets 112 Name setbpt ajusta pontos de parada setbptmacroname linenumb Parâmetros macroname string linenumb escalar inteiro ou vetor de escalares Descrição setbpt insere interativamente um ponto de parada na linha de número linenumb valor padrão é 1 da função macroname linenumb pode ser um vetor linha ou coluna dos números das linhas ou um único número de linha escalar Quando alcança o ponto de parada o Scilab avalia a linha especificada imprime o número da linha e da função Se a função não for compilada see comp a linha é exibida na tela Então o Scilab entra em modo pause no qual o usuário pode verificar os valores correntes O pause é cancelado com resume ou abort Redefinir a função não limpa pontos de parada o usuário deve deletar os pontos de parada explicitamente usando delbpt O número máximo de funções com pontos de parada habilitados deve ser menor que 100 e o número máximo de pontos de parada é 1000 Exemplos setbptfoosetbptfoo10dispbpt delbpt setbptfoo1256dispbpt Ver Também delbpt dispbpt pause resume 113 Name sethomedirectory ajusta o diretório home do Scilab homescilabhome sethomedirectory Descrição Ajusta o endereço hom do Scilab variável SCIHOME No Windows 2k e XP CDocuments and SettingsUserScilabScilabVersion No Windows Vista CUsersUserScilabScilabVersion No Unix homeUserScilabScilabVersion Autor Allan CORNET 114 Name slash divisão esquerdadireita e feedback resposta Descrição Divisão esquerdadireita xA b é a solução de xbA ba a b a b é a matriz com entradas aij bij Se b é escalar matriz 1x1 esta operação é o mesmo que abonesa mesma convenção se a é um escalar Observe que 123b é interpretado como 123b Nestes casos o ponto é parte do número não do operador significa divisão direitaesquerda Feedback de sistema SGK avalia SGeyeKG1 Este operador evita o problema de simplificação Observe que G5 é interpretado como G5 Em tais casos o ponto é parte do número não do operador Comentário comenta uma linha ie linhas que começam por são ignoradas pelo interpretador Ver Também inv percent backslash ieee 115 Name stacksize ajusta tamanho da pilha do Scilab stacksizen stacksizemax stacksizemin szstacksize Parâmetros n inteiro o tamanho da pilha requerido dado em número de palavras de dupla precisão sz vetor de duas entradas total used Descrição O Scilab armazena variáveis usuais em uma pilha stk para variáveis globais ver gstacksize stacksizen permite aumentar ou diminuir o tamanho desta pilha O máximo permitido depende da quantidade de memória livre e do espaço de troca swap space disponível no momento stacksizemax permite ao usuário aumentar o tamanho dessa pilha ao máximo stacksizemin permite ao usuário diminuir o tamanho dessa pilha ao mínimo Esta função com o argumento n pode ser usada em qualquer lugar szstacksize retorna um vetor de duas entradas que contém os tamanhos correntes de pilha total e usado Ver Também who gstacksize 116 Name star operador de multiplicação Descrição Multiplicação no sentido usual Válido para matrizes de contrantes valores booleanos polinômios ou razões de polinômios e para listas syslin o significado é de conexão de série A multiplicação elemento a elemento é denotada por xy Se x ou y é escalar matriz 1x1 é o mesmo que O produto de Kronecker é denotado por xy AB é um operador sem significado predefinido Pode ser usado para definir um novo operador ver overloading com a mesma precedência que ou Ver Também slash backslash syslin 117 Name startup arquivo de inicialização Descrição O arquivo de inicialização SCIHOMEscilab e SCIHOMEscilabini são automaticamente executados se estiverem presentes quando o Scilab é chamado junto com o arquivo scilabstar no diretório Scilab SCI Observações A última linha de um arquivo de inicialização deve ser terminada por uma nova linha a ser levada em conta Definição de SCIHOME no Windows CDocuments e SettingsUserScilabScilabVersion ou no Vista CUserAppDataRoamingScilabScilabVersion No LinuxUnix homeUserScilabScilabVersion Ver Também scilab 118 Name symbols nomes dos operadores Scilab Descrição Use os nomes seguintes para obter ajuda em um símbolo específico operator nome na ajuda do Scilab quote aspas plus sinal de mais minus sinal de menos star estrela asterísco slash barra backslash barra invertida dot ponto equal igual less desigualdades tilda til left colchete esquerdo right colchete direito parents parênteses percent colon doispontos comma vírgula semi pontoevírgula hat chapéu circunflexo power potência or barra vertical ou lógico and e comercial e lógico kron produto de Kronecker Observações Por razões históricas símbolos diferentes podem representar o mesmo operador tem o mesmo significado que tem o mesmo significado que tem o mesmo significado que tem o mesmo significado que É altamente recomendável que não se use esses recursos pois eles serão removidos futuramente Ver Também overloading 119 Name testmatrix gera algumas matrizes particulares ytestmatrixnamen Parâmetros name um string n inteiros tamanho da matriz y matriz n x m Descrição Cria algumas matrizes particulares testmatrixmagin retorna um quadrado mágico de tamanho n testmatrixfrkn retorna a matriz de Franck testmatrixhilbn é a matriz inversa da matriz n x n de Hilbert Hij 1ij1 120 Name then Palavrachave usada na estrutura ifthenelse significa então Descrição Usado com if Ver Também if 121 Name tilda não lógico m Parâmetros m matriz de valores booleanos Descrição m é a negação de m 122 Name try início de um bloco try numa instrução de controle trycatch significa tentar catch início de um bloco catch numa instrução de controle trycatch significa prender try statements catch statements end Descrição A instrução de controle trycatchpode ser usada para gerenciar códigos que possivelmente pode riam gerar erros Quando uma instrução de controle trycatch é executada normalmente apenas as sentenças entre as palavraschaves try e catchsão executadas Contudo se um erro ocorre durante a execução de uma dessas sentenças o erro é registrado as sentenças restantes até catchsão puladas e as sentenças entre as palavraschaves catch e end são executadas usandose o modo de manipulação de erros padrão ver errcatch A mensagem de erro registrada pode ser recuperada pela função lasterror As sentenças catch tanto quanto a palavrachave catch podem ser omitidas se nenhuma sentença alternativa for fornecida Note que também é possível utilizar a função execstr com o argumento errcatch para manipulação de erros Isto pode ser particularmente útil para manipulação de erros sintáticos Exemplos filepathTMPDIRwrong try umopenfilepathr xmget10cu catch dispo arquivo filepath não pode ser lido usando valores padrões para x x110 end errormessageerrornumberlasterrort Ver Também error execstr if lasterror errcatch Autor Serge Steer INRIA 123 Name type tipo de variável itypex Parâmetros x objeto Scilab i inteiro Descrição typexretorna um inteiro que indica o tipo de x como segue 1 uma matriz constante de reais ou complexos 2 uma matriz de polinômios 4 uma matriz de valores booleanos 5 uma matriz esparsa 6 uma matriz de valores booleanos esparsa 7 uma matriz esparsa do Matlab 8 uma matriz de inteiros armazenados em 1 2 ou 4 bytes 9 uma matriz de manipuladores gráficos 10 uma matriz de strings 11 uma função nãocompilada código Scilab 13 uma função compilada código Scilab 14 uma biblioteca de funções 15 uma lista 16 uma lista com tipo typed list ou tlist 17 uma lista com tipo orientada matricialmente mlist 128 um ponteiro ver lufact 129 polinômio de tamanho implícito usado para indexação 130 intrínseco do Scilab código C ou Fortran Ver Também typeof 124 Name typename associa um nome ao tipo de variável types namestypename typenamenametype Parameters types vetor coluna de inteiros os códigos dos tipos de cada tipo de dado definido names vetor coluna de strings os nomes associados aos códigos de tipos type inteiro o código de tipo do novo tipo de dado name string o nome associado ao código de tipo Descrição O overloading de funções e operadores faz uso de nomes formais associados aos tipos de dados para formar o nome da função de overloading ver overloading typename pode ser usado para manipular esses nomes formais para tipos de dados hardcoded os nomes formais de tipos de dados codificados de tlist ou mlist são definidos de outra forma ver overloading Chamado sem argumento do lado direito typename retorna informações sobre tipos de dados definidos Chamado com argumento do lado direito typename associa um nome a um código de tipo de dado typenametype suprime o tipo de dado fornecido pelo seu código type de tabelas de tipos de dados conhecidos Number max of defined types is 50 Ver Também type typeof overloading tlist mlist 125 Name user interface para rotinas FORTRAN ou C s1s2slhsusere1e2erhs Descrição Com este comando é possível utilizar um programa externo como um comando do Scilab onde s1s2slhs são as variáveis de saída e e1e2erhs asão as variáveis de entrada Para inserir este comando no Scilab é necessário escrever algumas linhas na subrotina FORTRAN user do Scilab Ver intersci ou a documentação do Scilab para mais Ver Também fort link 126 Name varn variável simbólica de um polinômio symbvarnp pmvarnxvar Parâmetros p polinômio matriz de polinômios symb string x polinômio ou matriz de polinômios var variável simbólica string pm matriz ou matriz de polinômios Descrição symbvarnp retorna em symb a variável simbólica de p ie varnpoly0x is x varnxs retorna uma matriz de polinômios com os mesmos coeficientes que x mas com s como variável simbólica mudança do nome de variável Exemplos spoly0sps21s varnp varnpx Ver Também horner poly 127 Name ver informação de versão sobre Scilab r ver Parâmetros r uma matriz de strings Descrição Informação de versão sobre o Scilab Retorna uma matriz de strings com informações de versão sobre o Scilab Exemplos ver Autor AC 128 Name warning mensagens de aviso warningstring warningoff warningon mode warningquery Descrição Imprime o string string em uma mensagem de aviso on habilita mensagens de aviso off desabilita mensagens de aviso query retorna o estado on ou off Exemplos warningon warningeste é um aviso warningoff warningeste é um aviso warningquery warningon Ver Também error 129 Name what lista de primitivas do Scilab what primitivescommandswhat Descrição Lista de comandos e primitivas de nível baixo Autor AC 130 Name where retorna a árvore de chamamento de instruções corrente linenummacwhere Parâmetros linenum vetor coluna de inteiros mac vetor coluna de strings Descrição Retorna linenum e mac tais que a instrução corrente foi chamada pela linha linenum1 da função mac1 mac1 foi chamada pela linha linenum2 da função mac2 e assim por diante maci é em geral o nome de uma função mas também pode ser exec ou execstr se a instrução reside em um arquivo executável ou em uma instrução execstr Ver Também whereami pause 131 Name whereami exibe a árvore de chamamento de instruções corrente whereami Descrição Exibe a árvore de chamamento para a instrução que contém whereami Pode ser usado dentro de níveis de pause pausa Exemplos deffytestaysina1 yt1y yy1 deffyt1yyy2whereami test1 Ver Também where pause errcatch 132 Name while palavrachave da estrutura while significa enquanto Descrição while Deve ser terminado por end while expressão instruções1else instruções end while expressão do instruções1else instruções end while expressão then instruções1else instruções end Notas A única restrição é que cada palavrachave then ou do deve estar na mesma linha que a palavra chave while As palavraschaves then ou do podem ser substituídas por um retorno de carro ou uma vírgula Para compatibilidade com o Matlab também é possível mas não recomendado por um espaço entre o fim da expressão e o início da primeira instrução A construção opcional else instruções permite fornecer instruções que são executadas quando a expressão expressão tornase falsa Aviso o número de caracateres usados para definir o corpo de qualquer estrutura condicional if while for ou selectcase deve ser limitado a 16k Exemplos e1 a1 k1 while normaae1 eps ee2 kk1 end ek Ver Também for select break return pause 133 Name who listagem de variáveis who who nameswholocal namesmemwholocal nameswhoglobal namesmemwhoglobal whosorted nameswholocalsorted namesmemwholocalsorted nameswhoglobalsorted namesmemwhoglobalsorted Descrição who exibe os nome de variáveis correntes wholocal ou whoget retorna os nomes de variáveis correntes e a memória utilizada em palavras de dupla precisão whoglobal retorna os nomes de variáveis globais e a memória utilizada em palavras de dupla precisão whosorted exibe todas as variáveis em ordem alfabética Ver Também whos whouser 134 Name whouser listagem das variáveis do usuário whouser Descrição whouser exibe os nomes das variáveis do usuário Ver Também whos who 135 Name whos listing of variables in long form whos whos type typ whos name nam Parâmetros typ nome do tipo da variável selecionada ver typeof nam os primeiros caracteres dos nomes selecionados Descrição whos exibe todos os nomes de variáveis correntes bem como seus tipos e memória utilizada whos type typ exibe todas as variáveis correntes com o tipo especificado whos name nam exibe todas as variáveis cujos nomes começam com nam Nota se uma variável é global um aparece em frente ao seu tipo Exemplos lines0 whos whos type boolean whos name Ver Também who typeof 136 Name withatlas Checa se o Scilab foi construído com a biblioteca Atlas rwithatlas Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido construído com a biblioteca Atlas ou f senão 137 Name withgtk Checa se o Scilab foi contstruído com a biblioteca GIMP Toolkit rwithgtk Parameters r um booleano Description Sempre retorna f a biblioteca gtk não é mais suportada pelas versões 5 em diante 138 Name withjavasci Checa se o Scilab foi construído com a interface java rwithjavasci Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido construído com a interface java ou f senão 139 Name withmacrossource Verifica se a fonte de macros está instalada rwithmacrossource Parâmetros r um booleano Descrição Retorna t se a fonte de macros está instalada ou f senão 140 Name withmodule checa se um módulo Scilab foi instalado rwithmodulemodulename Parâmetros r um booleano modulename um string Exemplo core Descrição Retorna t se o módulo Scilab tiver sido instalado Ver Também getmodules Autor AC 141 Name withpvm Checa se o Scilab foi construído com a interface Parallel Virtual Machine rwithpvm Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido construído com a interface Parallel Virtual Machine ou f senão 142 Name withtexmacs checa se o Scilab foi chamado por TeXmacs rwithtexmacs Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido chamado por TeXmacs 143 Name withtk checa se o Scilab foi construído com TCLTK rwithtk Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido construído com a interface TCLTK ou f se não Parte II Equações Diferenciais 145 Name dae Solucionador de equações diferenciais algébricas ydaeinitialt0tres y hddaeinitialt0t rtol atolres jac hd yrddaerootinitialt0tresngsurface y rd hddaerootinitialt0t rtol atolres jac ng surface hd Parâmetros initial um vetor coluna Pode ser igual a x0 or x0xdot0 onde x0 é o valor de estado no tempo inicial t0 e ydot0 é o valor da derivada do estado inicial ou uma estimativa dela ver abaixo t0 número real o tempo inicial t escalar real ou vetor Fornece instantes para os quais você deseja uma solução Note que você pode obter soluções para cada ponto de passo de dae fazendo DAEOPTIONS21 rtol escalar real ou vetor coluna com o mesmo tamanho que x0 A tolerância do erro relativo da solução Se rtol for um vetor as tolerâncias são especificadas para cada componente do estado atol escalar real ou vetor coluna com o mesmo tamanho que x0 A tolerância do erro absoluto da solução Se atol for um vetor as tolerâncias são especificadas para cada componente do estado res uma função externa external Computa o valor de gtyydot Pode ser Uma função do Scilab Neste caso a sua seqüência de chamamento pode ser riresrestxxdot e res deve retornar o resíduo rgtxxdot e o indicador de erro ires ires 0 se res obtiver sucesso ao computar r 1 se o resíduo é indefinido localmente para txxdot 2 se os parâmetros estão fora do intervalo admissível Uma lista Esta forma é utilizada para passar parâmetros à função Deve ser como segue listresp1p2 Onde a seqüência de chamamento da função res é agora rrestyydotp1p2 res ainda retorna o valor residual como uma função de txxdotx1x2 e p1p2 são parâmetros da função Um string Deve se referir ao nome subrotina C ou Fortran Supondo que rname ié o nome dado A seqüência de chamamento em Fortran deve ser dae 146 rnametxxdotresiresrparipar double precision txxdotresrpar integer iresipar A seqüência de chamamento em C deve ser C2Frnamedouble t double x double xdot double res integer ires double rpar integer ipar onde t é o valor de tempo corrente x é o array de estados xdot é o array das derivadas dos estados res é o array de resíduos ires é o indicador de execução rpar é o array de valores de parâmetros em ponto flutuante necessário mas não pode ser definido pela função dae ipar é o array de valores de parâmetros inteiros necessário mas não pode ser definido pela função dae jac uma função externa external Computa o valor de dgdxcjdgdxdot para um dado valor do parâmetro cj Pode ser Uma função do Scilab Sua seqüência de chamamento deve ser rjactxxdotcj e a função jac deve re tornar rdgtxxdotdycjdgtxxdotdxdot onde cj é um escalar real Uma lista Esta forma é utilizada para passar parâmetros à função Deve ser como segue listjacp1p2 Onde a seqüência de chamamento da função jac é agora rjactxxdotp1p2 jac ainda retorna dgdxcjdgdxdot como uma função de txxdotcjp1p2 Um string Deve se referir ao nome de uma subrotina C ou Fortran Supondo que jname é o nome dado A seqüência de chamamento em Fortran deve ser jnamet x xdot r cj ires rpar ipar dae 147 double precision t x xdot r ci rpar integer ires ipar A seqüência de chamamento dem C deve ser C2Fjnamedouble t double x double xdot double r double cj integer ires double rpar integer ipar onde t x xdot ires rpar ipar são definidas semelhantemente como acima r é o array de resultados surface uma função externa external Computa o valor de cada vetor coluna surfacetx como componentes ng Cada componente define uma superfície Uma função do Scilab Sua seqüência de chamamento deve ser rsurfacetx esta função deve retornar um vetor com ng elementos Uma lista Esta forma é utilizada para passar parâmetros à função Deve ser como segue listsurfacep1p2 Onde a seqüência de chamamento da função surface é agora rsurfacetxp1p2 String Deve se referir ao nome de uma rotina C ou Fortran Supondo que sname é o nom dado A seqüência de chamamento em Fortran deve ser rnamenx t x ng r rpar ipar double precision t x r rpar integer nx ngipar A seqüência de chamamento em C deve ser C2Frnamedouble t double x double xdot double r double cj integer ires double rpar integer ipar onde t x rpar ipar são definidas semelhantemente como acima ng é o número de superfícies nx é a dimensão do estado e r é o array de resultados rd um vetor com duas entradas times num times é o valor do tempo no qual a superfície é cruzada num é o número da superfície cruzada hd um vetor de reais que permite armazenar o contexto de dae Pode ser utilizado como argumento de entrada para retomar a integração recomeço rápido dae 148 y matriz de reais Se DAEOPTIONS21 cada coluna é o vetor txtxdott onde t é o índice do tempo para o qual a solução foi computada De outro modo y é o vetor xtxdott Descrição A função dae é uma porta construída sobre as funções dassl e dasrt designada para equações difer enciais implícitas gtxxdot0 xt0x0 e xdott0xdot0 Se xdot0 não for fornecido no argumento initial a função dae tenta computálo resolvendo gtx0xdot00 Se xdot0 for fornecido no argumento initial pode ser tanto uma derivada compatível satis fazendo gtx0xdot00 ou um valor aproximado No último caso DAEOPTIONS7 deve ser ajustado para 1 Exemplos detalhados utilizando funções externas codificadas em C e Fortran são dados em mod ulesdifferentialequationstestsunittestsdassldasrttst Exemplos Exemplo com um código Scilab function rireschemrestyyd r1 004y1 1d4y2y3 yd1 r2 004y1 1d4y2y3 3d7y2y2 yd2 r3 y1 y2 y31 ires 0 endfunction function pdchemjacxyydcj pd004cj 1d4y3 1d4y2 004 1d4y323d7y2cj 1d4y2 1 1 1 endfunction x01 0 0 xd0004 004 0 t1d50024 04114 40 400 4000 40000 4d5 4d6 4d7 4d8 4d9 4d10 ydaex0xd00tchemres retorna os pontos de observação requisitados DAEOPTIONSlist100 pede que a malha de dae seja retornada ydaex0xd004d10chemres sem jacobiano ydaex0xd004d10chemreschemjac com jacobiano exemplo com um código C requerse um compilador C 1 criando os códigos C em TMPDIR equação de Vanderpol forma implícita codeinclude ltmathhgt void res22double tdouble ydouble yddouble resint iresdouble rparint ipar res0 yd0 y1 res1 yd1 100010 y0y0y1 y0 dae 149 void jac22double tdouble ydouble yddouble pddouble cjdouble rparint ipar pd0cj 00 pd1 2000y0y1 10 pd2 10 pd3cj 100010 y0y0 void gr22int neq double t double y int ng double groot double rpar int ipar groot0 y0 mputlcodeTMPDIRt22c 2 compilando e carregando ilibforlinkres22 jac22 gr22t22ccTMPDIRMakefileTMPDIRt22loadersce execTMPDIRt22loadersce 3 executando rtol1d61d6atol1d61d4 t00y020y0d02t2020200ng1 simulação simples t00003300 yydaey0y0dt0tatolrtolres22jac22 clfplotyy1yy2 achando o primeiro ponto onde yy10 yynnhotddaerooty0y0dt0300atolrtolres22jac22nggr22 plotyy11yy21r xstringyy1101yy21stringnn1 recomeço rápido para o próximo ponto t01nn1ppqqsizeyyy01yy23qqy0d1yy34qq yynnhotddaerooty01y0d1t01300atolrtolres22jac22nggr22hotd plotyy11yy21r xstringyy1101yy21stringnn1 Ver Também ode daeoptions dassl impl fort link external 150 Name daeoptions ajusta opções para o solucionador de equações diferenciais algébricas daeoptions Descrição Se no contexto do chamamento da função dae existe a variável DAEOPTIONS a função dae a utiliza para ajustar suas opções A função daeoptions exibe interativamente um comando que deveria ser executado para se ajustar diversas opções do solucionador dae CUIDADO a função dae verifica se esta variável existe e neste caso a utiliza Para utilizar valores padrões você deve limpar esta variável Note que daeoptions não cria esta variável Para criála você deve executar a linha de comando exibida por daeoptions A variável DAEOPTIONS é uma lista list com os seguintes elementos listtstopimodebandmaxstepstepinnonnegisest O valor padrão é list000 Os siginificados destes elementos são listados abaixo tstop um escalar real ou uma matriz fornece o tempo máximo para o qual se permite a avaliação de g Uma matriz vazia significa que não há limites impostos pelo tempo imode Se for 0 dae retorna apenas os valores de pontos do tempo especificado pelo usuário Se for 1 dae retorna seus valores intermediários computados band um vetor de dois componentes que fornece a definição mlmu da matriz de bandas computada por jac ri j ml mu 1j dgidyjcjdgidydotj Se jac retorna uma matriz completa ajustado band maxstep um escalar ou matriz vazia o tamanho máximo do passo Uma matriz vazia indica ausência de limitiação stepin um escalar ou matriz vazia o tamanho mínimo do passo Uma matriz vazia indica não especi ficado nonneg um escalar deve ser ajustado para 0 se a solução se conhece ser não negativa E caso contrário deve ser ajustado para 1 daeoptions 151 isest A scalar deve ser ajustado para 0 se a dada condição inicial é compatível gt0x0xdot00 Deve ser ajustado para 1 se xdot0 é apenas uma estimativa Ver Também dae 152 Name dasrt Solucionador de equações diferenciais algébricas com cruzamento de zeros rnnhddasrtx0t0t atolrtolres jacng surf info hd Parâmetros x0 pode ser tanto y0 ydot0 é estimado por dassl com a primeira estimativa sendo 0 ou a matriz y0 ydot0 gty0ydot0 deve ser igual a zero Se você conhece apenas uma estimativa de ydot0 faça info71 y0 vetor coluna de reais de condições iniciais ydot0 vetor coluna de reais da derivada do tempo de y em t0 pode ser uma estimativa t0 número real é o instante inicial t escalar real ou vetor Fornece instantes para os quais você deseja uma solução Note que você pode obter soluções para cada ponto de passo de dassl fazendo info21 nn um vetor com duas entradas times num times é o valor do tempo no qual a superfície é cruzada num é o número da superfície cruzada atolrtol escalares reais ou vetores colunas com o mesmo tamanho que y atolrtol fornecem respec tivamente as tolerâncias de erros absolutos e relativos da solução Se forem vetores as tolerâncias são especificadas para cada elemento de y res função lista ou string externos Computa o valor de gtyydotPode ser Uma função do Scilab Sua seqüência de chamamento pode ser riresrestyydot e res e deve retornar o resíduo rgtyydot e o indicador de erro ires ires 0 se res obtiver suces so ao computar r 1 se o resíduo é indefinido localmente para tyydot 2 se os parâmetros estão fora do intervalo admissível Uma lista Esta forma permite passar outros parâmetros além de tyydot à função Deve ser como segue listresx1x2 Onde a seqüência de chamamento da função res é agora rrestyydotx1x2 res ainda retorna rgtyydot como função de tyydotx1x2 Warning this form must not be used if there is no extra argument to pass to the function dasrt 153 Um string Deve se referir ao nome subrotina C ou Fortran ligada ao Scilab Em C a seqüência de chamamento void resdouble t double y double yd double r int ires double rpar int ipar Em Fortran deve ser subroutine restyydriresrparipar double precision t yydrrpar integer iresipar Os arrays rpar e ipar devem estar presentes mas não podem ser utilizados jac função lista ou string externos Computa o valor de dgdycjdgdydot para um dado valor do parâmetro cj Uma função do Scilab Sua seqüência de chamamento deve ser rjactyydotcj e a função jac deve re tornar rdgtyydotdycjdgtyydotdydot onde cj é um escalar real Uma lista Deve ser como segue listjacx1x2 Onde a seqüência de chamamento da função jac é agora rjactyydotcjx1x2 jac ainda retorna dgdycjdgdydot como uma função de tyydotcjx1x2 Um string Deve se referir ao nome de uma subrotina C ou Fortran ligada ao Scilab Em C a seqüência de chamamento deve ser void jacdouble t double y double yd double pd double cj double rpar int ipar Em Fortran deve ser subroutine jactyydpdcjrparipar double precision t yydpdcjrpar dasrt 154 integer ipar surf função lista ou string externo Computa o valor do vetor coluna surfty com componentes ng Cada componente define uma superfície Pode ser definido por Uma função Scilab Sua seqüência de chamamento deve ser surfty Uma lista Deve ser como segue listsurfx1x2 onde a seqüência de chamamento surf é agora rsurftyx1x2 Um string Deve se referir ao nome de uma subrotina C ou Fortran ligada ao Scilab Em C a seqüência de chamamento deve ser void surfint ny double t double y int ng double gout Em Fortran deve ser subroutine surfnytynggout double precision t ygout integer nyng info lista que contém 7 elementos o valor padrão é list000 info1 escalar real que fornece o tempo máximo para o qual se permite avaliar g ou uma matriz vazia se não houver limites impostos sobre o tempo info2 indica se dassl retorna seus valores intermediários computados flag1 ou apenas os valores de pontos tempo especificados pelo usuário flag0 info3 vetor de dois componentes que fornece a definição mlmu de matriz de bandas computa da por jac ri j ml mu 1j dgidyjcjdgi dydotj Se jac retorna uma matriz cheia faça info3 info4 escalar real que fornece o tamanho de passo máximo Faça info4 se não houver limitação dasrt 155 info5 escalar real que fornece o passo inicial Faça info5 se não for especificado info6 faça info61 caso se saiba que a soulução não é negativa em outro caso ajuste in fo60 info7 faça info71 se ydot0 é apenas uma estimativa info70 se gt0y0ydot00 hd vetor de reais que permite armazenar o contexto de dassl e retomar integração r matriz de reais Cada coluna é o vetor txtxdott onde t é o índice do tempo para o qual a solução foi computada Descrição Solução da equação diferencial implícita gtyydot0 yt0y0 e ydott0ydot0 Retorna os instantes de cruzamento da superfície e o número da superfície alcançada em nn Exemplos detalhados podem ser encontrados em SCIDIRtestsdassldasrttst Exemplos dydt 2logy8t 5y y1 1 1lttlt6 g1 2logy8t 5y g2 logy 22491 y01t26t01y0d3 atol1d6rtol0ng2 deffdeltairesres1tyydotires0deltaydot2logy8t5y deffrtsgr1tyrts2logy8t5ylogy22491 yynndasrty0y0dt0tatolrtolres1nggr1 Deveria retornar nn24698972 2 Ver Também ode dassl impl fort link external 156 Name dassl Equação diferencial algébrica r hddasslx0t0t atolrtolres jac info hd Parâmetros x0 pode ser tanto y0 ydot0 é estimado por dassl com a primeira estimativa sendo 0 ou a matriz y0 ydot0 gty0ydot0 deve ser igual a zero Se você conhece apenas uma estimativa de ydot0 faça info71 y0 vetor coluna de reais de condições iniciais ydot0 vetor coluna de reais da derivada do tempo de y em t0 pode ser uma estimativa t0 número real é o instante inicial t escalar real ou vetor Fornece instantes para os quais você deseja uma solução Note que você pode obter soluções para cada ponto de passo de dassl fazendo info21 atolrtol escalares reais ou vetores colunas com o mesmo tamanho que y atolrtol fornecem respec tivamente as tolerâncias de erros absolutos e relativos da solução Se forem vetores as tolerâncias são especificadas para cada elemento de y res função lista ou string externos Computa o valor de gtyydot Pode ser Uma função do Scilab Sua seqüência de chamamento pode ser riresrestyydot e res deve retornar o resíduo rgtyydot e o indicador de erro ires ires 0 se res obtiver suces so ao computar r 1 se o resíduo é indefinido localmente para tyydot 2 se os parâmetros estão fora do intervalo admissível Uma lista Esta forma permite passar outros parâmetros além de tyydot à função Deve ser como segue listresx1x2 Onde a seqüência de chamamento da função res é agora rrestyydotx1x2 res ainda retorna rgtyydot como função de tyydotx1x2 Um string Deve se referir ao nome subrotina C ou Fortran ligada ao Scilab dassl 157 Em C a seqüência de chamamento void resdouble t double y double yd double r int ires double rpar int ipar Em Fortran deve ser subroutine restyydriresrparipar double precision t yydrrpar integer iresipar Os arrays rpar e ipar devem estar presentes mas não podem ser utilizados jac função lista ou string externos Computa o valor de dgdycjdgdydot para um dado valor do parâmetro cj Uma função do Scilab Sua seqüência de chamamento deve ser rjactyydotcj e a função jac deve re tornar rdgtyydotdycjdgtyydotdydot onde cj é um escalar real Uma lista Deve ser como segue listjacx1x2 Onde a seqüência de chamamento da função jac é agora rjactyydotcjx1x2 jac ainda retorna dgdycjdgdydot como uma função de tyydotcjx1x2 Um string Deve se referir ao nome de uma subrotina C ou Fortran ligada ao Scilab Em C a seqüência de chamamento deve ser void jacdouble t double y double yd double pd double cj double rpar int ipar Em Fortran deve ser subroutine jactyydpdcjrparipar double precision t yydpdcjrpar integer ipar dassl 158 info lista opcional que contém 7 elementos O valor padrão é list000 info1 escalar real que fornece o tempo máximo para o qual se permite avaliar g ou uma matriz vazia se não houver limites impostos sobre o tempo info2 indica se dassl retorna seus valores intermediários computados flag1 ou apenas os valores de pontos tempo especificados pelo usuário flag0 info3 vetor de dois componentes que fornece a definição mlmu de matriz de bandas computa da por jac ri j ml mu 1j dgidyjcjdgi dydotj Se jac retorna uma matriz cheia faça info3 info4 escalar real que fornece o tamanho de passo máximo Faça info4 se não houver limitação info5 escalar real que fornece o passo inicial Faça info5 se não for especificado info6 faça info61 caso se saiba que a soulução não é negativa em outro caso ajuste in fo60 info7 faça info71 se ydot0 é apenas uma estimativa info70 se gt0y0ydot00 hd vetor de reais que permite armazenar o contexto de dassl e retomar integração r matriz de reais Cada coluna é o vetor txtxdott onde t é o índice do tempo para o qual a solução foi computada Descrição A função dassl integra a equação alegébricadiferencial e retorna a evolução de y em pontos de tempo dados gtyydot0 yt0y0 e ydott0ydot0 Exemplos function rireschemrestyyd r004y11d4y2y3yd1 004y11d4y2y33d7y2y2yd2 y1y2y31 ires0 endfunction function pdchemjacxyydcj pd004cj 1d4y3 1d4y2 004 1d4y323d7y2cj 1d4y2 1 1 1 dassl 159 endfunction y0100 yd00040040 t1d5002404114404004000400004d54d64d74d84d94d10 ydassly0yd00tchemres infolist000 info21 ydassly0yd004d10chemresinfo ydassly0yd004d10chemreschemjacinfo utilizando um argumento extra para parâmetros function rireschemrestyyd abc ray1by2y3yd1 ay1by2y3cy2y2yd2 y1y2y31 ires0 endfunction function pdchemjacxyydcj abc pdacj by3 by2 a by32cy2cj by2 1 1 1 endfunction ydassly0yd00tlistchemres0041d43d7listchemjac0041d43d7 utilizando código c criando o código C rescodevoid chemresdouble t double y double yd double r int ires double rpar int ipar r0 004y010e4y1y2 yd0 r1 004y010e4y1y230e7y1y1yd1 r2 y0y1y21 ires 0 jaccodevoid chemjacdouble t double y double yd double pd double cj double rpar int ipar primeira coluna pd0 004cj pd1 004 pd2 10 segunda coluna pd3 10e4y2 pd4 10e4y2230e7y1cj pd5 10 terceira coluna pd6 10e4y1 pd7 10e4y1 pd8 10 mputlrescodejaccodeTMPDIRmycodec create the C file compilandoo ilibforlinkchemreschemjacmycodeccTMPDIRMakefileTMPDIRloaderscecompilando dassl 160 ligandoo com o Scilab execTMPDIRloadersce linking incremental chamada a dassl ydassly0yd00tchemreschemjac Ver Também ode dasrt impl fort link external 161 Name feval múltipla avaliação zfevalxyf zfevalxf Parâmetros xy dois vetores f função ou string para chamada FORTRAN ou C Descrição Múltipla avaliação de uma função para um ou dois argumentos do tipo vetor zfevalxf retorna o vetor z definido por zifxi zfevalxyf retorna a matriz z tal que zijfxiyj f é uma external função ou rotina que aceita dois ou mais argumentos supostos reais O re sultado retornado por f pode ser real ou complexo No caso de uma chamada FORTRAN a função f deve ser definida na subrotina fevaltablec no diretório SCImod ulesdifferentialequationssrcc Exemplos deffzfxyzx2y2 feval11015f deffzfxyzxiy feval11015f feval11015parab See ffevalf file feval110parab Para link dinâmico ver exemplo ftest em ffevalf você pode usar o comando link os parâmetros dependem da máquina unixmake ftestolinkftestfftest feval11015ftest Ver Também evstr horner execstr external link 162 Name impl equações diferenciais algébricas yimpltypey0ydot0t0t atol rtolresadda jac Parâmetros y0ydot0 vetor de reais ou matriz condições iniciais t0 escalar real tempo inicial t vetor de reais tempos nos quais a solução é computada resadda funções externas função strting ou lista type string adams ou stiff atolrtol escalar real ou vetor de reais com as mesmas dimensões que y jac função externa função string ou lista Descrição Solução da equação diferencial linear implicita Aty dydtgty yt0y0 t0 é o instante inicial y0 é o vetor de condições iniciais O vetor ydot0 da derivada em relação ao tempo y em t0 também deve ser dado A entrada res é uma função externa ie uma função com sintaxe especificada ou o nome da subrotina FORTRAN ou da função C string com seqüência de chamamento especificada ou uma lista Se res for uma função a sintaxe deve ser como segue r restyydot onde t é um escalar real tempo e y e ydot são vetores de reais estado e derivada do estado Esta função deve retornar rgtyAtyydot Se res for um string ele se refere a uma subrotina FORTRAN ou uma função C Ver SCImod ulesdifferentialequationsscigatewayfortranEximplf para um exem plo res também pode ser uma lista ver a ajuda de ode A entrada adda também é uma função externa Se adda for uma função a sintaxe deve ser como segue impl 163 r addatyp e deve retornar rAtyp onde p é uma matriz a ser adicionada a Aty Se adda for um string ele se refere a uma subrotina FORTRAN ou uma função C Ver SCImod ulesdifferentialequationsscigatewayfortranEximplf para um exem plo adda também pode ser uma lista ver a ajuda de ode A entrada jac também é uma função externa Se jac for uma função a sintaxe deve ser como segue j jactyydot e deve retornar o Jacobiano de rgtyAtyydot em relação a y Se jac for um string ele se refere a uma subrotina FORTRAN ou uma função C Ver SCImod ulesdifferentialequationsscigatewayfortranEximplf para um exem plo jac também pode ser uma lista ver a ajuda de ode Exemplos yimpl1000040040004residaplusp utilizando reinicialização rápida x1wiwimpl1000040040002residaplusp inicialização rápida da chamada anterior x1impl10000400400204residapluspwiw maxiabsx1x Ver Também dassl ode external 164 Name int2d integral definida 2d por quadratura e cubatura Ierrint2dXYf params Parâmetros X um array 3 por N contendo as abscissas dos vertices dos N triângulos Y um array 3 por N contendo as ordenadas dos vertices dos N triângulos f função externa função string ou lista definindo o integrando fuv params vetor de reais tol iclose maxtri mevals iflag O valor padrão é 1d10 1 50 4000 1 tol o limite desejado do erro Se iflag0 tol é interpretado como um limite de erro relativo se iflag1 o limite é de erro absoluto iclose um inteiro que determina a seleção dos métodos LQM0 ou LQM Se iclose1 então LQM1 é utilizado Qualquer outro valor de iclose faz com que LQM0 seja usado LQM0 utiliza valores da função apenas em pontos interiores ao triângulo LQM1 geralmente é mais preciso que LQM0 mas envolve a avaliação do integrando em mais pontos incluindo em alguns pontos da fronteira do triângulo Geralmente é melhor utilizar LQM1 a não ser que o integrando possuia singularidades nas bordas do triângulo maxtri o número máximo de triângulos na triangularização final da região mevals o número máximo de avaliações da função permitido Este número terá efeito na limitação da computação se for menor que 94maxtri quando LQM1 é especificado ou 56maxtri quando LQM0 é especificado iflag I o valor da integral err o erro estimado Descrição int2d computa a integral bidimensional de uma função f sobre uma região que consiste de n triângulos Um estimativa de erro total é obtida e comparada a tol que é fornecida como entrada para a subrotina A tolerância de erro é tratada como relativa ou absoluta dependendo do valor de entrada de iflag Um módulo de quadratura local Local Quadrature Module é aplicado para cada triângulo de entrada e estimativas da integral total e do erro total são computadas O módulo de quadratura local é a subrotina LQM0 ou a subrotina LQM1 e a escolha entre elas é determinada pelo valor da variável iclose int2d 165 Se a estimativa de erro total excede a tolerância o triângulo com maior erro absoluto é dividio em dois outro triângulos traçandose uma mediana por seu maior lado O módulo de quadratura local é então aplicado a cada um dos subtriângulos para se obter novas estimativas da integral e do erro Este proces so é repetido até que um dos seguintes 1 a tolerância é satisfeita 2 o número de triângulos gerados excede o parâmetro maxtri 3 o número de avaliações do integrando excede o parâmetro mevals ou 4 a função sente que um erro de arredondamento está começando a contaminar o resultado Exemplos X001110 Y000111 deffzfxyzcosxy Ieint2dXYf computa o integrando sobre o quadrado 0 1x0 1 Ver Também intc intl int3d intg mesh Autores Autores da rotina FORTRAN twodq KahanerDKNBS RechardOWNBS BarnhillRobertUniv de UTAH 166 Name int3d integral definida 3d pelo método da quadratura e cubatura resulterrint3dXYZf nfparams Parâmetros X um array 4 por NUMTET contendo as abscissas dos vértices dos NUMTET tetraedros Y um array 4 por NUMTET contendo as ordenadas dos vértices dos NUMTET tetraedros Z um array 4 por NUMTET contendo as terceiras coordenadas dos vértices dos NUMTET tetraedros f função externa function string ou lista definindo o integrando fxyznf onde xyz é o vetor das coordenadas de um ponto e nf os números das funções nf o número da função a ser integrada o padrão é 1 params vetor de reais minpts maxpts epsabs epsrel O valor padrão é 0 1000 00 1d5 epsabs limite do erro absoluto desejado epsrel limite do erro relativo desejado minpts número mínimo de avaliações da função maxpts número máximo de avaliações da função O número de avaliações da função sobre cada subregião é 43 result o valor da integral ou vetor de valores da integral err estimativas do erro absoluto Descrição A função calcula uma aproximação a um dado vetor de integrais definidas I I I F F F dx3dx2dx1 1 2 numfun onde a região de integração são os NUMTET tetraedros e onde int3d 167 F F X1X2X3 J 12NUMFUN J J uma estratégia globalmente adaptativa é aplicada para se computar aproximações resultk esperandose que satisfaça para cada componente de I à seguinte precisão ABSIK RESULTKMAXEPSABSEPSRELABSIK int3d repetidamente subdivide os tetraedros com maiores erros estimados e estima as integrais e os erros sobre os novos tetraedros até que a exigência de erro seja encontrada ou MAXPTS avaliações da função tenham sido feitas Uma regra de 43 pontos de integração com todos os pontos de avaliação dentro dos tetraedros é apli cada A regra tem grau polinomial 8 Se os valores dos parâmetros de entrada EPSABS ou EPSREL são suficientemente grandes uma re gra de integração é aplicada sobre cada tetraedro e os valores são aproximados para se fornecer as aproximações RESULTK Nenhuma subdivisão posterior dos tetraedros será feita Quando int3d computa estimativas a um vetor de integrais é dado tratamento igual a todos os com ponentes do vetor Isto é IFj e IFk para j diferente de k são estimados com a mesma subdivisão da região de integração Para integrais suficientemente semelhantes podemos economizar tempo aplicando int3d a todos os integrando em uma chamada Para integrais que variam continu amente em função de um parâmetro as estimativas produzidas por int3d também irão variar con tinuamente quando a subdivisão é aplicada a todos os componentes Este geralmente não será o caso quando componentes diferentes são tratados separadamente Por outro lado este recurso deve ser utilizado com cautela quando os componentes diferentes da in tegral requerem claramente subdivisões diferentes Referências Rotina FORTRAN dcutetf Exemplos X0100 Y0010 Z0001 RESULTERRORint3dXYZint3dex computa o integrando expxxyyzz sobre o tetraedro 000100010001 integração sobre um cubo 1ltxlt11ltylt11ltzlt1 fundo topo direita esquerda frente traseira X 0 0 0 0 0 0 0 0 0 0 0 0 11 11 1 1 11 11 11 11 11 1 1 11 11 11 1 1 1 1 1 1 11 1 1 1 1 Y 0 0 0 0 0 0 0 0 0 0 0 0 11 11 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 11 11 11 1 1 Z 0 0 0 0 0 0 0 0 0 0 0 0 11 1 1 1 1 1 1 11 11 11 1 1 11 11 1 1 1 1 int3d 168 11 1 1 1 1 1 1 1 1 1 1 function vfxyznumfunvexpxyzxyzendfunction resulterrint3dXYZf101000001d51d7 function vfxyznumfunv1endfunction resulterrint3dXYZf101000001d51d7 Ver Também intc intl int2d Autores Jarle Berntsen The Computing Centre University of Bergen Thormohlens gt 55 N5008 Bergen Noruega Fone 475544055 Email jarleeikiiuibno Ronald Cools Dept of Computer Science Katholieke Universiteit Leuven Celestijnenlaan 200A B3030 Hev erlee Belgium Fone 3216201015 3562 Email ronaldcskuleuvenacbe Terje O Espelid Department of Informatics University of Bergen Thormohlens gt 55 N5008 Bergen Norway Fone 475544180 Email terjeeikiiuibno 169 Name intc integral de Cauchy yintcabf Parâmetros ab dois números complexos f função externa Descrição Se f é uma função com valores complexos intcabf computa o valor da integral de a a b de fzdz ao longo da reta a b do plano complexo Ver Também intg intl Autor F D 170 Name integrate integração pela quadratura xintegrateexprvx0x1 atol rtol Parâmetros expr string definindo uma expressão Scilab v string variável da integração x0 número real limite inferior de integração x1 vetor de números reais limites superiores de integração atol número real erro absoluto Valor padrão 18 rtol número real erro relativo Valor padrão 1e14 x vetor de números reais o valor da integral para cada x1i Descrição Computa para i1sizex1 Onde é dado pela expressão expr A avaliação procura satisfazer à seguinte precisão absIx maxatolrtolabsI onde I é o valor exato da integral Restrição A expressão dada não deve utilizar nomes de variáveis começando por Exemplos x00x10012pi Xintegratesinxxx0x1 normcosx11X x1100110 Xintegrateif x0 then 1 else sinxxendx0x1 integrate 171 Ver Também intg inttrap intsplin ode 172 Name intg integral definida verrintgabf ea er Parâmetros ab números reais f função externa função lista ou string ea er números reais ea erro absoluto requerido no resultado Valor padrão 1d14 er erro relativo requerido no resultado Valor padrão 1d8 err erro absoluto estimado no resultado Descrição intgabf avalia a integral definida de a a b de ftdt A função ft deve ser contínua Esperase que a avaliação satisfaça à seguinte precisão absIv maxeaerabsI onde I é o valor exato da integral f é uma função externa Se f é uma função sua definição deve ser como segue y ft Se f é uma lista a lista deve ser como segue listfx1x2 onde f é uma função com seqüência de chamamento ftx1x2 Se f é um string ele se refere ao nome de uma função FORTRAN ou procedure C com dada seqüência de chamamento No caso FORTRAN a seqüência de chamamento deve ser double precision function fx onde x tabém é um número de dupla precisão No caso C a seqüência de chamamento é double fdouble x Exemplos caso de função Scilab function yfxyxsin30xsqrt1x2pi2endfunction exact25432596188 Iintg02pif absexactI caso de função Scilab com parâmetros function yf1xwyxsinwxsqrt1x2pi2endfunction intg 173 Iintg02pilistf130 absexactI caso de código FORTRAN compilador FORTRAN requerido escreve o código FORTRAN cd TMPDIR F double precision function ffunx double precision xpi pi314159265358979312d0 ffunxsin300d0xsqrt10d0x20d0pi2 return end mputlFTMPDIRffunf compile o código FORTRAN lilibforlinkffunffunff linking incremental linklffunf integrando a função Iintg02piffun absexactI caso de código C compilador C requerido escreva o código C Cinclude mathh double cfundouble x double ypi314159265358979312 yx20e0pi return xsin300e0xsqrt10e0yy mputlCTMPDIRcfunc compile o código C lilibforlinkcfuncfuncc linking incremental linklcfunc integrando a função Iintg02picfun absexactI Ver Também intc intl inttrap intsplin ode Funções Utilizadas As rotinas associadas podem ser encontradas no diretório SCImodulesdifferentialequationssrcfor tran dqag0f e dqagsf de quadpack 174 Name intl integral de Cauchy yintlabz0rf Parâmetros z0 número complexo ab dois número reais r número real positivo f função externa Descrição Se f é uma função externa com valores complexos intlabz0rf computa a integral de fzdz ao longo da curva no plano complexo definida por z0 rexpit para atb parte do círculo com centro z0 e raio r com fase entre a e b Ver Também intc Autor F D 175 Name ode Solucionador de equações diferenciais ordinárias yodey0t0tf ywiwodetypey0t0t rtol atolf jac wiw yrdwiwoderooty0t0t rtol atolf jacngg wiw yodediscretey0k0kvectf Parâmetros y0 matriz ou vetor de reais condições iniciais t0 escalar real tempo inicial t vetor de reais tempos nos quais a solução é computada f função externa função lista ou string type um dos strings seguintes adams stiff rk rkf fix discrete roots rtolatol constantes reais ou vetores com o mesmo tamanho que y jac função externa função lista ou string wiw vetores de reais ng inteiro g função externa função lista ou string k0 inteiro tempo inicial kvect vetor de inteiros Descrição ode é a função padrão para se resolver sistemas de EDO explícitos definidos por dydtfty yt0y0 É uma interface entre vários solucionadores em particular a ODEPACK O tipo de proble ma resolvido e o método a ser utilizado dependem do primeiro argumento opcional type que pode ser um dos strings seguintes not given O lsoda solucionador do pacote ODEPACK é chamado por padrão Ele escolhe automati camente entre o método preditorcorretor nãorígido de Adams e a Fórmula de Diferenciação Retroativa FDR rígida Ele utiliza o método não rígido inicialmente e monitora os dados para decidir qual método utilizar ode 176 adams Este é para problemas não rígidos O solucionador lsode do pacote ODEPACK é chamado e utiliza o método de Adams stiff Este é para problemas rígidos O solucionador lsode do pacote ODEPACK é chamado e é uti lizado o método FDR rk Método adaptativo de RungeKutta de ordem 4 RK4 rkf O programa de Shampine e Watts baseado no par RungeKutta de Fehlberg de ordem 4 e 5 RKF45 é utilizado Este é utilizado para problemas nãorígidos e mediamente rígidos quando as computações de derivação não são custosas Este método não é recomendado ser utilizado quando o usuário requer uma maior precisão fix Mesmo solucionador que rkf mas a interface do usuário é bem simples ie apenas os parâmetros rtol e atol podem ser passados ao solucionador Este é o método mais simples a se tentar root Solucionador de EDOs com capacidade de encontrar raízes O solucionador lsodar do pacote ODEPACK é utilizado É uma variante do solucionador lsoda onde se acha raízes de uma dada função vetorial Ver ajuda em oderoot para mais detalhes discrete Simulação de tempo discreto Ver ajuda em odediscrete para mais detalhes Nesta ajuda podemos apenas descrever o uso de ode para sistemas padrões explícitos EDOs A chamada mais simples a ode é yodey0t0tf onde y0 é o vetor de condições iniciais t0 é o tempo inicial t é o vetor de tempos onde a solução y é computada e y é a matriz de vetores soluções yyt1yt2 O argumento de entrada f define o lado direito da equação diferencial de primeira ordem dy dtfty É uma função externa isto é uma função com sintaxe especificada ou o nome de uma subrotina Fortran ou uma subfunção C string com seqüência de chamamento especificada ou uma lista Se f for uma função do Scilab a sua sintaxe deve ser ydot fty onde t é um escalar real tempo e y é um vetor de reais estado ydot é um vetor de reais dydt Se f é um string ele se refere ao nome de uma subrotina Fortran ou uma subfunção C ie Se odey0t0tfex for o comando então a subrotina fex será chamada A rotina Fortran deve ter a seguinte seqüência de chamamento fexntyydot com n um inteiro t um escalar de dupla precisão y e ydot vetores de dupla precisão A função C deve ter o seguinte protótipo fexint ndouble tdouble ydouble ydot t é o tempo y o estado e ydot a derivada do estado dydt Esta função externa pode ser construída em um SO de modo indpendente através de ilibforlink e ligada dinamicamente através da função do Scilab link O argumento f também pode ser uma lista com a seguinte estrutura lstlistrealfu1u2un onde realf é uma função do Scilab com a sintaxe ydot ftyu1u2un ode 177 Esta sintaxe permite utilizar parâmetros como argumentos de realf A função f pode retornar uma matriz p x q ao invés de um vetor Com esta notação de matriz nos resolvemos o sistema npq de EDOs dYdtFtY onde Y é uma matriz p x q matrix Então as condições iniciais Y0 também devem ser uma matriz p x q e o resultado de ode é a matriz p x qT1 Yt0Yt1YtT Argumentos de entrada opcionais podem ser fornecidos para o erro da solução rtol e atol são limiares para os erros relativos e absolutos estimados O erro estimado em yi é rtoliabsyiatoli e uma intergração é feita enquanto este erro é pequeno para todos os componentes do estado Se rtol eou atol for uma constante rtoli eou atoli são ajustados para esta constante Os valores padrões para rtol e atol são respectivamente rtol1d5 e atol1d7 para a maior parte dos solucionadores rtol1d3 e atol1d4 para rfk e fix Para problemas rígidos é melhor fornecer o Jacobiano da função do lado direito da equação como o argumento opcional jac É uma função externa istoé ie uma função com sintaxe especificada ou o nome de uma subrotina Fortran ou uma subfunção C string com seqüência de chamamento especificada ou uma lista Se jac for uma função a sintaxe deve ser Jjacty onde t é um escalar real tempo y é um vetor de reais estado A matriz resultante J deve fornecer dfdx ie Jki dfkdxi com fk késimo componente de f Se jac for um sting ele se refere a uma subrotina Fortran ou uma subfunção C com as seguinte seqüência de chamamento No caso Fortran subroutine fexntymlmuJnrpd integer nmlmunrpd double precision tyJ No caso C void fexint ndouble tdouble yint mlint mudouble Jint nrpd jacntymlmuJnrpd Na maior parte dos casos você não tem que se referir a ml mu e nrpd Se jac for uma lista as mesmas convenções que para f se aplicam Os argumentos opcionais w e iw e vetores para armazenamento de informações podem ser retor nados pela rotina de integração ver odeoptionaloutput para detalhes Queando esses vetores são fornecidos no lado direito de ode a integração reinicia com os mesmos parâmetros da parada anteiror Mais opções podem ser fornecidas a solucionadores ODEPACK utilizandose a variável ODEOP TIONS Ver odeoptions Exemplos ode 178 EDO simples de uma dimensão função externa do Scilab dydty2y sintcost y00 function ydotftyydoty2ysintcostendfunction y00t00t001pi yodey0t0tf plotty EDO simples de uma dimensão função externa codificada em C ccodeinclude mathh void myodeint ndouble tdouble ydouble ydot ydot0y0y0y0sintcost mputlccodeTMPDIRmyodec criando o arquivo C ilibforlinkmyodemyodeccTMPDIRMakefileTMPDIRloaderscecompilando execTMPDIRloadersce linking incremental y00t00t001pi yodey0t0tmyode Simulação de dxdt A xt B ut com utsinomegat x010 solução xt desejada em t01 02 05 1 A e a função u são passados para a função do lado direito em uma lista B e omega são passados como variáveis globais function xdotlineartxAuxdotAxButendfunction function utututsinomegatendfunction A1 10 2B11omega5 ode1000102051listlinearAu Integração com notação matricial da equação diferencial de Ricatti XdotAX XA XBX C X0Identity Solução em t12 function XdotrictXXdotAXXAXBXCendfunction A1102 B1001 C1001 t00t001pi XodeeyeA0tric Notação matricial computação de expA A1102 function xdotftxxdotAxendfunction odeeyeA01f odeadamseyeA01f Notação de matriz computação de expA com matriz rígida Jacobian fornecida A10001 function xdotftxxdotAxendfunction function JJacobiantyJAendfunction odestiff0101fJacobian Ver Também odediscrete oderoot dassl impl odedc odeoptions csim ltitr rtitr Autor Alan C Hindmarsh mathematics and statistics division l316 livermore ca 9455019 ode 179 Bibliografia Alan C Hindmarsh lsode and lsodi two new initial value ordinary differential equation solvers acm signum newsletter vol 15 no 4 1980 pp 1011 Funções Utilizadas As rotinas associadas podem ser encontradas no diretório SCImodulesdifferentialequationssrcfor tran lsodef lsodaf lsodarf 180 Name odediscrete solucionador de equações diferenciais ordinárias simulação de tempo discreto yodediscretey0k0kvectf Parâmetros y0 vetor de reais ou matriz condições iniciais t0 escalar real tempo inicial f função externa ie função string ou lista k0 inteiro tempo inicial kvect vetor de inteiros Descrição Com esta sintaxe primeiro argumento igual a discrete ode computa recursivamente yk 1fkyk de um estado inicial yk0 e retorna yk para k em kvect kvect1 deve ser maior do que ou igual a k0 Outros argumentos e opções são os mesmos que para ode veja a página de ajuda de ode Exemplos y1123 deffypafunctionkyypAyBuk Adiag020509 B111u110n5 yodediscretey111nafunction y2Ay1Bu1 Agora y é avaliado em y3y5y7y9 yodediscretey11329afunction Ver Também ode 181 Name odeoptionaloutput descrição de saídas opcionais de solucionadores de EDOs Descrição Esta página descreve os valores mais importantes retornados nos argumento opcionais do lado esquer do da função ode w e iw São válidos apenas para os solucionadores de EDOs lsode lsoda e lsodar Para mais detalhes pode se consultar os comentários dos códigos das subrotinas FORTRAN SCImodulesdifferentialequationssrcfortranlsodf w11 último tamanho do passo em t utilizado sucessivamente w12 o tamanho do passo a ser tentado no próximo passo w13 o valor corrente da variável independente alcançado pelo solucionador ie o ponto de malha interno t corrente Ná saída tcur sempre estará pelo menos tão longe quanto o argumento t mas pode estar mais longe se foi realizada interpolação w14 um fator de escala de tolerância maior que 10 computado quando se detecta requerer muita precisão istate 3 se detectado no início do problema istate 2 em caso contrário Se itol for inalterado mas rtol e atol forem uniformemente escalados por um fator de tolsfw14 para a próxima chamada emtão supõese que o solucionador pode continuar o usuário também pode ignorar tolsf e alterar os parâmetros de tolerância de qualquer outro modo apropriado w15 o valor de t no tempo da última alternação de método se houver Este valor não é significante com o solucionador lsode iw10 o número de avaliações de g para problema até então Este valor é significante apenas para o solucionador lsodar iw11 o número de passos tomados para o problema até então iw12 o número de avaliações de f até então iw13 o número de avaliações do jacobiano e de decomposições lu da matriz para o problema até então iw14 a última ordem do método utilizada sucessivamente iw15 a ordem a ser tentada no próximo passo iw16 o índice do componente de maior magnitude no vetor de erro local ponderado eiewti sobre um erro retorna istate 4 or 5 iw17 o comprimento de w realmente requerido supondo que o comprimento de rwork deve ser fixado para o resto do problema e que a alternância pode ocorrer Isto é definido sobre retornos normais e sobre um retorno de entrada ilegal para armazenamento insuficiente odeoptionaloutput 182 iw18 o comprimento de iw realmente requerido supondo que o comprimento de iw deve ser fixado pelo resto do problema e que a alternância pode ocorrer Isto é definido sobre retornos normais e sobre um retorno de entrada ilegal para armazenamento insuficiente iw19 o indicador do método para o último passo realizado com sucesso 1 significa adams nonstiff 2 significa bdf stiff Este valor não é significante com o solucionador lsode iw20 o indicador do método corrente 1 significa adams nonstiff 2 significa bdf stiff Este é o método a ser tentado no próximo passo Logo difere de iw19 apenas se uma alternância de métodos foi realizada Este valor não é significante com o solucionador lsode 183 Name oderoot solucionador de EDOs com busca de raízes yrdwiwoderooty0t0t rtol atolf jacngg wiw Parâmemtros y0 vetor de reais ou matriz condições iniciais t0 escalar real tempo inicial t vetor de reais tempos nos quais a solução é computada f função externa ie função string ou lista rtolatol constantes reais ou vetores reais com o mesmo tamanho que y jac função externa ie função string ou lista wiw vetores de reais ng inteiros g função externa ie função string ou lista Descrição Com esta sintaxe primeiro argumento igual a root ode computa a solução da EDO dy dtfty até que o estado yt cruze a superfície gty0 g deve fornecer a equação da superfície É uma função externa ie uma função com sintaxe especi ficada ou o nome de uma subrotina FORTRAN ou função C string com seqüência de chamamento especificada ou uma lista Se g é uma função a sintaxe deve ser como segue zgty onde t é um escalar real tempo e y um vetor de reais estado Ela retorna um vetor de tamanho ng que corresponde às ng restrições Se g é um string ele se refere a uma subrotina FORTRAN ou uma função C com a seguinte seqüência de chamamento gntynggout onde ng é o número de restrições e gout é o valor de g saída do programa Se g é uma lista as mesmas convenções para f se aplicam ver ajuda de ode A saída rd é um vetor 1 x k A primeira entrada contém o tempo de parada Outras entradas indicam que componentes de g possuem sinal trocado k maior que 2 indica que mais de uma superfície k1 superfícies foram simultaneamente atravessadas oderoot 184 Outros argumentos e opções são os mesmos que para ode ver a página de ajuda de ode Exemplos Integração da equação diferencial dydty y01 e acha o tempo mínimo t tal que yt2 deffydotftyydoty deffzgtyzy2 y01ng1 yrdoderootsy002fngg deffzgtyzy2233 yrdoderoots102f3g Ver Também dasrt ode 185 Name odedc solucionador de EDOs contínuasdiscretas ytodedcy0ndstdelt0tf Parâmetros y0 vetor coluna de reais condições iniciais y0y0cy0d onde y0d tem nd componentes nd inteiro dimensão de y0d stdel vetor de reais com uma ou duas entradas stdelh delta com delta0 como valor padrão t0 escalar real tempo inicial t vetor linha de reais instantes onde yt é calculado f função externa ie função string ou lista com seqüência de chamamento ypftycydflag Descrição yodedcy0cy0dndhdeltat0tf computa a solução de um sistema misto contínuodiscreto O estado de sistema discreto ydk é embutido em uma função de tempo seccional constante ydt como segue ydtydk para t em tkatrasokhtk1delayk1h com atrasohdelta As equações simuladas são agora dycdtftyctydt0 para t em tktk1 yct0y0c e nos instantes tk a variável discreta yd é atualizada por ydtkfyctkydtk1 Note que utilizando a definição de ydt a última equação fornece ydk f tkyctkydtk11 yc é de tempo contínuo yctkyctk Os parâmetros de chamada de f são fixados ycdftycydflag esta função deve retornar a derivada do vetor yc se flag0 ou a atualização de yd se flag1 odedc 186 ycddotyc deve ser um vetor de mesma dimensão que yc se flag0 e ycdupdateyd deve ser um vetor com a mesma dimensão que yd se flag1 t é um vetor de constantes onde a solução y é computada y é o vetor yyt1yt2 Esta função pode ser chamada com os mesmo parâmetro opcionais da função ode desde que nd e stdel sejam dados na seqüência de chamamen to como segundo e terceiro parâmetros Em particular flags de integração e tolerâncias podem ser ajustadas Parâmetros opcionais podem ser ajustados pela função odeoptions Um exemplo para chamada de rotina externa é encontrado em SCIDIRdefaultfydot2f Rotinas externas podem ser ligadas dinamicamente ver link Exemplos sistema linear com entrada alternante deffxduphistxuflagif flag0 then xduAxBu else xdu1uend x011A1221B12u0nu1stdel10u00t000510 xuodedcx0u0nustdel0tphisxxu12uxu3 nx2 plot2d1onntx1nx161 plot2d2onntunx1nxnu000 função externa FORTRAN ver fydot2f normxuodedcx0u0nustdel0tphis1 feedback resposta amostrado xcdotfctxcu sistema yhctxc xdfdxdy feedback uhdtxd deffxcdftxcxdiflag if iflag0 then xcdfctxcethdtxd else xcdfdxdhctxc end A102341067810B111C111 Ad1210120Bd11Cd11 deffstetstsin3t deffxdotfctxuxdotAxBu deffyhctxyCx deffxpfdxyxpAdx Bdy deffuhdtxuCdx h01t00t0012 x0c000x0d00nd2 xcdodedcx0cx0dndht0tf normxcdodedcx0cx0dndht0tfcd1 cálculo rápido ver fydot2f plot2dtttxcd13 xsetwindow2plot2d2gnnttxcd45 odedc 187 xsetwindow0 Ver Também ode odeoptions csim external 188 Name odeoptions ajusta opções para solucionadores de EDO odeoptions Descrição Esta função exibe interativamente um comando que deveria ser executado para se ajustar diversas opções para solucionadores de EDOs A variável global ODEOPTIONS ajusta as opções CUIDADO a função ode verifica se esta variável existe e neste caso a utiliza Para se utilizar valores padrões devese limpar esta variável Note que odeoptions não cria esta variável Para criála você deve executar a linha de comando exibida por odeoptions A variável ODEOPTIONS é um vetor com os seguintes elementos itasktcrith0hmaxhminjactypmxstepmaxordnmaxordsixprmlmu O valor padrão é 100inf02500125011 O significado de cada elemento é descrito abaixo itask 1 computação normal nos tempos especificados 2 computação nos tempos de malha dados na primeira linha da saída de ode 3 um passo em um ponto interno da malha e retorna 4 computação normal sem overshooting desvalorização excessiva tcrit 5 um passo sem passagem de tcrit e retorna tcrit assume itask igual a 4 ou 5 descrito acima h0 primeiro passo tentado hmax tamanho máximo do passo hmin tamanho mínimo do passo jactype 0 iterações funcionais nenhum jacobiano usado adams ou stiff apenas 1 jacobiano completo fornecido pelo usuário 2 jacobiano completo internamente gerado 3 jacobiano diagonal internamente gerado adams ou stiff apenas 4 jacobiano com bandas fornecido pelo usuário ver ml e mu abaixo 5 jacobiano com bandas internamente gerado ver ml e mu abaixo maxordn máxima ordem nãostiff permitida no máximo 12 maxords máxima ordem stiff permitida no máximo 5 ixpr nível de impressão 0 ou 1 mlmu se jactype é igual a 4 ou 5 ml e mu são as semibandas inferior e superior do jacobiano com bandas a banda são os ijs com iml j ny1 Se jactype é igual a 4 a função jacobiana deve retornar uma matriz J que é mlmu1 x ny onde nydim de y em ydotfty tal que a coluna 1 de J é feita de mu zeros seguidos por df1dy1 df2dy1 df3dy1 1ml entradas nãonulas possivelmente a coluna 2 é feita de mu1 zeros seguidos por df1dx2 df2dx2 etc Ver Também ode 189 Name bvode boundary value problems for ODE using collocation method bvodeS Simplified call to bvode zubvodexpointsNmxlowxupzetaiparltoltolfixpntfsubdfsubgsubdgsubguess zubvodeSxpointsmNxlowxupfsubgsubzeta optionalargs Parameters zu a column vector of size M The solution of the ode evaluated on the mesh given by points It contains zux for each requested points xpoints an array which gives the points for which we want to observe the solution N a scalar with integer valuenumber of differential equations N 20 m a vector of size N with integer elements It is the vector of order of each differential equation mi gives the order of the ith differential equation In the following M will represent the sum of the elements of m xlow a scalar left end of interval xup a scalar right end of interval zeta a vector of size Mzetaj gives jth side condition point boundary point One must have xlowzetaj zetaj1xup All side condition points must be mesh points in all meshes used see description of ipar11 and fixpnt below ipar an array with 11 integer elements nonlin collpnt subint ntol ndimf ndimi iprint iread iguess rstartnfxpnt nonlin ipar1 0 if the problem is linear 1 if the problem is nonlinear collpnt ipar2 Gives the number of collocation points per subinterval where maxmj collpnt 7 if ipar20 then collpnt is set to max maxmj1 5maxmj subint ipar3 Gives the number of subintervals in the initial mesh if ipar3 0 then bvode arbitrarily sets subint 5 ntol ipar4 Gives the number of solution and derivative tolerances We require 0 ntol M ipar4 must be set to the dimension of the tol argument or to 0 In the latter case the actual value will automatically be set to sizetol bvode 190 ndimf ipar5 Gives the dimension of fspace a real work array its value provides a constraint on nmax the maximum number of subintervals The ipar5 value must respect the constraint ipar5nmaxnsizef where nsizef43M5collpntNcollpntNM2Mnrec2M nrec is the number of right end boundary conditions ndimi ipar6 Gives the dimension of ispace an integer work array its value provides a constraint on nmax the maximum number of subintervals The ipar6 value must respect the constraint ipar6nmaxnsizei where nsizei3 collpntNM iprint ipar7 output control make take the following values 1 for full diagnostic printout 0 for selected printout 1 for no printout iread ipar8 0 causes bvode to generate a uniform initial mesh xx Other values are not implemented yet in Scilab 1 if the initial mesh is provided by the user it is defined in fspace as follows the mesh will occupy fspace1 fspacen1 the user needs to supply only the interior mesh points fspacej xj j 2 n 2 if the initial mesh is supplied by the user as with ipar81 and in addition no adaptive mesh selection is to be done iguess ipar9 0 if no initial guess for the solution is provided 1 if an initial guess is provided by the user trought the argument guess 2 if an initial mesh and approximate solution coefficients are provided by the user in fspace the former and new mesh are the same 3 if a former mesh and approximate solution coefficients are provided by the user in fspace and the new mesh is to be taken twice as coarse ieevery second point from the former mesh bvode 191 4 if in addition to a former initial mesh and approximate solution coefficients a new mesh is provided in fspace as well see description of output for further details on iguess 2 3 and 4 ireg ipar10 0 if the problem is regular 1 if the first relax factor is equal to ireg and the nonlinear iteration does not rely on past covergence use for an extra sensitive nonlinear problem only 2 if we are to return immediately upon a two successive nonconvergences or b after obtaining error estimate for the first time nfxpnt ipar11 Gives the number of fixed points in the mesh other than xlow and xup the dimension of fixpnt ipar11 must be set to the dimension of the fixpnt argument or to 0 In the latter case the actual value will automatically be set to sizefixpnt ltol an array of dimension ntolipar4 ltolj l specifies that the jth tolerance in the tol array controls the error in the lth component of It is also required that 1 ltol1 ltol2 ltolntol M tol an array of dimension ntolipar4 tolj is the error tolerance on the ltolj th component of Thus the code attempts to satisfy on each subinterval if is the approximate solution vector an u the exact solution unknown fixpnt an array of dimension nfxpntipar11 it contains the points other than xlow and xup which are to be included in every mesh The code requires that all side condition points other than xlow and xup see description of zeta be included as fixed points in fixpnt fsub an external used to evaluate the column vector f for any x such as xlow x xup and for any zzux see description below The external must have the headings In Fortran the calling sequence must be subroutine fsubxzuf double precision zu fx bvode 192 In C the function prototype must be void fsubdouble x double zu double f And in Scilab function ffsubxzuparameters dfsub an external used to evaluate the Jacobian of fxzu at a point x Where zux is defined as for fsub and the N by M array df should be filled by the partial derivatives of f The external must have the headings In Fortran the calling sequence must be subroutine dfsubxzudf double precision zu dfx In C the function prototype must be void dfsubdouble x double zu double df And in Scilab function dfdfsubxzuparameters gsub an external used to evaluate given z z zetai for 1iM The external must have the headings In Fortran the calling sequence must be subroutine gsubizug double precision zu g integer i In C the function prototype must be bvode 193 void gsubint i double zu double g And in Scilab function ggsubizuparameters Note that in contrast to f in fsub here only one value per call is returned in g dgsub an external used to evaluate the ith row of the Jacobian of gxux Where zu is as for fsub i as for gsub and the Mvector dg should be filled with the partial derivatives of g viz for a particular call one calculates The external must have the headings In Fortran the calling sequence must be subroutine dgsubizudg double precision zu dg In C the function prototype must be void dgsubint i double zu double dg And in Scilab function dgdgsubizuparameters guess An external used to evaluate the initial approximation for zux and dmvalux the vector of the mjth derivatives of ux Note that this subroutine is used only if ipar9 1 and then all M components of zu and N components of dmval should be computed for any x such as xlow x xup The external must have the headings In Fortran the calling sequence must be subroutine guessxzudmval double precision xz dmval In C the function prototype must be bvode 194 void fsubdouble x double zu double dmval And in Scilab function dmvalzufsubxparameters optionalargs It should be either any left part of the ordered sequence of values guess dfsub dgsub fixpnt ndimf ndimi ltol tol ntolnonlin collpnt subint iprint ireg ifail or any sequence of argnameargvalue with argname in guess dfsub dgsub fixpnt ndimf ndimi ltol tol ntol nonlin collpnt subint iprint ireg ifail Where all these arguments excepted ifail are described above ifail can be used to display the bvode call corresonding to the selected optional arguments If guess is given iguess is set to 1 Description These functions solves a multipoint boundary value problem for a mixed order system of odes given by Where The argument zu used by the external functions and returned by bvode is the column vector formed by the components of zux for a given x The method used to approximate the solution u is collocation at gaussian points requiring mi1 continuous derivatives in the ith component i 1N here k is the number of collocation points stages per subinterval and is chosen such that k ge max mi a rungekuttamonomial solution representation is utilized bvode 195 Examples The first two problems below are taken from the paper 1 of the Bibliography The problem 1 describes a uniformy loaded beam of variable stifness simply supported at both end It may be defined as follow Solve the fourth order differential equation Subjected to the boundary conditions The exact solution of this problem is known to be N1 just one differential equation m4a fourth order differential equation Msumm xlow1xup2 the x limits zetaxlowxlowxupxup two constraints on the value of u and its second derivative on each bound The external functions Theses functions are called by the solver with zuuxuxuxux The function which computes the right hand side of the differential equation function ffsubxzuf16x2zu46xzu3x3endfunction The function which computes the derivative of fsub with respect to zu function dfdfsubxzudf006x26xendfunction The function which computes the ith constraint for a given i function ggsubizu select i case 1 then xzeta11 gzu1 u10 case 2 then xzeta21 gzu3 u10 case 3 then xzeta32 gzu1 u20 case 4 then xzeta42 gzu3 u20 end bvode 196 endfunction The function which computes the derivative of gsub with respect to z function dgdgsubiz select i case 1 then xzeta11 dg1000 case 2 then xzeta21 dg0010 case 3 then xzeta32 dg1000 case 4 then xzeta42 dg0010 end endfunction The function which computes the initial guess unused here function zumparguessxzu0mpar0endfunction define the function which computes the exact value of u for a given x for testing purposes function zutrusolx zu0ones41 zu1 02510log231x 05 1x 3xlogx x zu2 02510log23 05 1x2 3xx logx 1 zu3 05 2x3 1x 3x2 zu4 056x4 1xx 6x3 endfunction fixpnt All boundary conditions are located at xlow and xup nonlin collpnt n ntol ndimf ndimi iprint iread iguess rstart nfxpnt ipar0 0 1 2 2000 200 1 0 0 0 0 ltol13set tolerance control on zu1 and zu3 tol1e111e11set tolreance values for these two controls xpointsxlow001xup zubvodexpointsNmxlowxupzetaiparltoltolfixpnt fsubdfsubgsubdgsubguess check the constraints zu131 should be zero plotxpointszu1 the evolution of the solution u zu1for xxpointszu1zu1trusolx end normzuzu1 Same problem using bvodeS and an initial guess function zlhSzstartx zzeros51z51 lhS01 endfunction zubvodexpointsNmxlowxupzetaltolltoltoltolguesszstart The problem 2 describes the small finite deformation of a thin shallow spherical cap of constant thickness subject to a quadratically varying axisymmetric external pressure distribution Here phi bvode 197 is the meridian angle change of the deformed shell and psi is a stress function For epsmu1e3 two different solutions may found depending on the starting point Subject to the boundary conditions for x0 and x1 N2 two differential equations m2 2each differential equation is of second order Msumm xlow0xup1 the x limits zetaxlowxlow xup xup two constraints on each bound The external functions Theses functions are called by the solver with zuu1xu1xu2xu2x The function which computes the right hand side of the differential equation function ffsub2xzuepsdmueps4mugamxt fzu1x2zu2xzu1zu31zu1xgamx1x22eps4mu phi zu3x2zu4xzu11zu12xdmupsi endfunction The function which computes the derivative of fsub with respect to zu function dfdfsub2xzuepsdmueps4mugamxt df1x21zu3xeps4mu 1x 1zu1xeps4mu 0 1zu1xdmu 0 1x2 1x endfunction The function which computes the ith constraint for a given i function ggsub2izu select i case 1 then xzeta10 gzu1 u00 case 2 then xzeta20 g03zu3 xpsi03psi07x0 case 3 then xzeta31 gzu1 u10 case 4 then xzeta41 g1zu403zu3071 xpsi03psi07x0 end endfunction The function which computes the derivative of gsub with respect to z function dgdgsub2iz select i bvode 198 case 1 then xzeta11 dg1000 case 2 then xzeta21 dg00030 case 3 then xzeta32 dg1000 case 4 then xzeta42 dg00031 end endfunction gam11 eps1d3 dmueps eps4mueps4dmu xtsqrt2gam1gam fixpnt All boundary conditions are located at xlow and xup collpnt4 nsizef43M5collpntNcollpntNM2M22M nsizei3 collpntNM nmax200 nonlin collpnt n ntol ndimf ndimi iprint iread iguess rstart nfxpnt ipar1 k 10 4 nmaxnsizef nmaxnsizei 1 0 0 0 0 ltol14set tolerance control on zu1 zu2 zu3 and zu4 tol1e51e51e51e5set tolreance values for these four controls xpointsxlow001xup zubvodexpointsNmxlowxupzetaiparltoltolfixpnt fsub2dfsub2gsub2dgsub2guess2 scf1clfplotxpointszu1 3 the evolution of the solution phi and psi using an initial guess The function which computes the initial guess unused here function zudmvalguess2xgam consgamx1x22 dconsgam13x22 d2cons3gamx dmvalzeros21 if xxt then zu0 0 cons dcons dmval2d2cons else zu2x22xcons2dcons dmval2d2cons end endfunction ipar91iguess zu2bvodexpointsNmxlowxupzetaiparltoltolfixpnt fsub2dfsub2gsub2dgsub2guess2 scf2clfplotxpointszu21 3 the evolution of the solution phi and psi An eigenvalue problem bvode 199 yxlayx BV y0y0 y10 Eigenfunctions and eigenvalues are yxnsinsn1x lansn2 where sn are the zeros of fsnsatansn1pi n012 To get a third boundary condition we choose y01 With yx also cyx is a solution for each constant c We solve the following ode system ylay la0 BV y0y0 y01 y10 zyx yx la function rhsfsubxz rhsz3z10 endfunction function ggsubiz gz1z2 z11 z1 ggi endfunction The following start function is good for the first 8 eigenfunctions function zlhsystartxzla0 z10la0 lhs00 endfunction a0b1 m21 n2 zetaa a b N101 xlinspaceabN We have snn12pi 0 for n to infinity la0inputnth eigenvalue n la0pi2la0pi2 zbvodeSxmnabfsubgsubzetaystartlistystartla0 clf plotxz1 z2 xtitleStartvalue stringla0Eigenvalue stringz31x legendyxyx A boundary value problem with more than one solution DE yxexpyx BV y00 y10 This boundary value problem has more than one solution It is demonstrated how to find two of them with the help of some preinformation of the solutions yx to build the function ystart zyxyx a0b1m2n1 zetaa b N101 bvode 200 tol1e81 1 xlinspaceabN function rhsfsubxzrhsexpz1endfunction function ggsubiz gz1 z1 ggi endfunction function zlhsystartxzM z4x1xM 412xM zM0 lhsexp4x1xM lhs0 endfunction for M1 4 if M1 zbvodeSxmnabfsubgsubzetaystartlistystartMtoltol else z1bvodeSxmnabfsubgsubzetaystartlistystartMtoltol end end Integrating the ode yield eg the two solutions yex and yex1 function yfcyc1tanhsqrtc422endfunction cfsolve2f function yyexxc ylogc21tanhsqrtc14x22 endfunction function yf1c1 y2c12tanh14c121endfunction c1fsolve01f1 function yyex1xc1 ylog1tanh2x14c122c1c1 endfunction dispnormz1yexxnormyexxz1 dispnormz11yex1xnormyex1xz11 clf subplot211 plot2dxz1style5 xtitleTwo different solutionsx subplot212 plot2dxz11style5 xtitle x A multipoint boundary value problem DE yx1 zyxyxyx BV y12 y12 bvode 201 Side condition y01 a1b1c0 The side condition point c must be included in the array fixpnt n1 m3 function rhsfsubxz rhs1 endfunction function ggsubiz gz12 z11 z12 ggi endfunction N10 zetaa c b xlinspaceabN zbvodeSxmnabfsubgsubzetafixpntc function yyexx yx36x2x61 endfunction dispnormyexxz1normyexxz1 See Also link external ode dassl Used Functions This function is based on the Fortran routine colnew developped by U Ascher Department of Computer Science University of British Columbia Vancouver BC V6T 1W5 Canada G Bader institut f Angewandte mathematik university of Heidelberg im Neuenheimer feld 294d6900 Heidelberg 1 Authors This help is based on the original colnewf comments adapted to Scilab by JP Chancelier ENPC on the bvodeS help page due to Rainer von Seggern both merged and revised by S Steer INRIA Bibliography 1 U Ascher J Christiansen and RD Russell collocation software for boundaryvalue ODEs acm trans math software 7 1981 209222 this paper contains EXAMPLES where use of the code is demonstrated 2 G Bader and U Ascher a new basis implementation for a mixed order boundary value ode solver siam j scient stat comput 1987 3 U Ascher J Christiansen and RD Russell a collocation solver for mixed order systems of bound ary value problems math comp 33 1979 659679 bvode 202 4 U Ascher J Christiansen and RD russell colsys a collocation code for boundary value problems lecture notes compsc 76 springer verlag b childs et al eds 1979 164185 5 C Deboor and R Weiss solveblok a package for solving almost block diagonal linear systems acm trans math software 6 1980 8087 Parte III Funções Elementares 204 Name abs valor absoluto magnitude tabsx Parâmetros x matriz ou vetor de reais ou complexos t matriz ou vetor de reais Descrição absx é o valor absoluto dos elementos de x Quando x é de complexos absx é o módulo complexo magnitude dos elementos de x Exemplos abs1i1i1i 205 Name acos arcocosseno em relação aos elementos tacosx Parâmetros x vetor de reais ou complexos t vetor de reais ou complexos Descrição Os componentes do vetor t são os arcoscossenos das entradas correspondentes do vetor x O domínio de definição é 1 1 acos toma valores em Exemplos x1i1i cosacosx 206 Name acosd arcocosseno elemento a elemento com resultado em graus tacosdx Parâmetros x array de reais ou complexos t array de reais ou complexos Descrição Os componentes do vetor t são o arcocosseno em graus das entradas correspondentes do vetor x tacosx180pi Para dados reais em 1 1 os resultados estão em 0 180 Exemplos x1 0 1 sqrt22 sqrt22 sqrt32 sqrt32 acosdx Ver Também acos 207 Name acosh arcocoseno hiperbólico tacoshx Parâmetros x vetor de reais ou complexos t vetor de reais ou complexos Descrição Os componentes do vetor t são os arcoscosenos hiperbólicos das entradas correspondentes do vetor x O domínio de definição é 1infinito A função toma valores em conjuntos Exemplos x01i coshacoshx 208 Name acoshm arcocosseno hiperbólico da matriz matriz arcocosseno hiperbólico tacoshmx Parâmetros xt matriz quadrada de reais ou complexos Descrição acoshm é o arcocosseno hiperbólico da matriz x matriz arcocosseno hiperbólico Usa a fórmula tlogmxxeyesqrtmxeyexeye Para matrizes nãosimétricas o resultado pode ser impreciso Exemplos A1234 coshmacoshmA A11A11i coshmacoshmA Ver Também acosh logm sqrtm 209 Name acosm arcocoseno da matriz matriz arcocosseno tacosmx Parâmetros x matriz quadrada de reais ou complexos t matriz quadrada de reais ou complexos Descrição t é o arcocosseno da matriz x matriz arcocosseno de x É usado o método da diagonalização Para matrizes nãosimétricas o resultado pode ser impreciso Temse tilogmx isqrtmeyexx Exemplos A1234 cosmacosmA Ver Também acos sqrtm logm 210 Name acot computa o arcocotangente elemento a elemento do argumento y acotx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição computa o arcocotangente elemento a elemento do argumento Para argumento reais o resultado é real As seguintes desigualdades se verificam acotz piacotzpi2atanz iacothizpi21csgnzi Exemplos x1 2 2 sqrt2 sqrt2 2sqrt3 2sqrt3 1 acotxpi Ver Também cotg acotd Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 211 Name acotd computa o arcocotangente elemento a elemento do argumento com resultado em graus y acotdx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa o arcocotangente elemento a elemento do argumento com resultado em graus Para argu mento real w o resultado é real Exemplos x1 2 2 sqrt2 sqrt2 2sqrt3 2sqrt3 1 acotdx Ver Também cotd acot Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 212 Name acoth arcocotangente hiperbólico elemento a elemento y acothx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa o arcocotangente hiperbólico do argumento elemento a elemento Exemplos x300130 xabsx1nan plotxacothx Ver Também atanh coth Autor Serge Steer INRIA Funções Usadas Esta rotina é baseada na função atanh 213 Name acsc computa o arcocossecante elemento a elemento do argumento y acscx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição computa o arcocossecante elemento a elemento do argumento Para entradas com valores reais abso lutos maiores que 1 o resultado é real As seguintes desigualdades se verificam acscz acscz asin1z pi2 asecz iacschiz Exemplos xlinspace120200 xx11 nan x plotxacscx Ver Também csc acscd Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 214 Name acscd computa o arcocossecante elemento a elemento do argumento com resutado em graus y acscdx Parâmetros x array de reais y array de reais ou complexos Descrição computa o arcocossecante elemento a elemento do argumento com resutado em graus Para entradas reais com valores absolutos maiores que 1 o resultado é real Exemplos xlinspace120200 xx11 nan x plotxacscdx Ver Também cscd acsc Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 215 Name acsch computa o arcocossecante hiperbólico elemento a elemento do argumento y acschx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa o arcocossecante hiperbólico elemento a elemento do argumento Para argumentos com valores absolutos maiores que 1 o resultado é real As seguintes igualdades se verificam acschz acschz asinh1z csgni 1zasechizipi2 iacsciz Exemplos xlinspace120200 xx11 nan x plotxacschx Ver Também csch Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 216 Name adj2sp converte forma de adjacência para matriz esparsa Parâmetros xadj vetor de inteiros de comprimento n1 adjncy vetor de inteiros de comprimento nz contendo os índices de linha para os elementos correspon dentes em anz anz vetor coluna de comprimento nz contendo os elementos nãonulos de A mn vetor linha com duas entradas mnsizeA opcional A matriz quadrada esparsa de reais ou complexos nz entradas nãonulas Descrição adj2sp converte uma representação em forma de adjacência de uma matriz em sua representação padrão do Scilab função utilitária xadj adjncy anz representação de adjacência de A ie xadjj1xadjj número de entradas nãonulas na linha j adjncy índice de coluna das entradas nãonulas nas linha 1 linha 2 linha n anz valores das entradas nãonulas nas linha 1 linha 2 linha n xadj é um vetor coluna de tamanho n1 e adjncy é um vetor coluna de inteiros de tamanho nznnzA anz é um vetor de reais de tamanho nznnzA Exemplos A sprand1005005 xadjadjncyanz sp2adjA nmsizeA p adj2spxadjadjncyanznm Ap Ver Também sp2adj spcompack 217 Name amell função am de Jacobi snamelluk Parâmetros u escalar real ou vetor de reais k escalar sn escalar real ou vetor de reais Descrição Computa a função elíptica de Jacobi amuk onde k é o parâmetro e u é o argumento Se u é um vetor sn é o vetor dos valores computados elemento a elemento Usado na função sn Ver Também delip sn asn 218 Name and E lógico bandA bandA bandAr bandA1 bandAc bandA2 AB Descrição andA é o E lógico dos elementos da matriz de valores booleanos A andA retorna T true verdadeiro se e só se todas as entradas de A são T yandAr ou de modo equivalente yandA1 é o e em relação às linhas Retorna em cada entrada do vetor linha y o e das linhas de x O e é realizado no índice de linhas yj andAiji1m yandAc ou de modo equivalente yandA2 é o e em relação às colunas Retorna em cada entrada do vetor coluna y o e das colunas de x O e é realizado no índice de colunas yi andAijj1n AB fornece o and elemento a elemento das matrizes de valores booleanos A e B A e B devem ser matrizes com mesmas dimensões ou uma delas deve ser um único booleano Ver Também not or 219 Name asec computa o arcosecante elemento a elemento do argumento y asecx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição computa o arcosecante elemento a elemento do argumento Para valores reais com valores absolutos maiores que 1 o resultado é real As seguintes igualdades se verificam asecz acscz asin1z pi2 asecx iacschiz Exemplos x1 2 2 sqrt2 sqrt2 2sqrt3 2sqrt3 1 asecxpi Ver Também sec asecd Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 220 Name asecd computa o arcosecante elemento a elemento do argumento com resultados em graus y asecdx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição computa o arcosecante elemento a elemento do argumento com resultados em graus Para dados de entrada com valores absolutos maiores que 1 os resultados são reais em 90 90 asecdx is equal to asecx180pi Exemplos x1 2 2 sqrt2 sqrt2 2sqrt3 2sqrt3 1 asecdx Ver Também asec secd Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 221 Name asech computa o arcosecante hiperbólico elemento a elemento do argumento y asechx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa o arcosecante hiperbólico elemento a elemento do argumento Se o argumento é real e tem valor absoluto menor que 1 o resultado é real As seguintes igualdades se verificam asechx acosh1 x icsgni11 xasecxcsgni1 1 xpi2iacschix Exemplos asech1 Ver Também sech Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 222 Name asin arcoseno tasinx Parâmetros x vetor ou matriz de reais ou complexos t vetor ou matriz de reais ou complexos Descrição As entradas de t são os arcossenos das entradas correspondentes de x O domínio de deifinição é 1 1 A função toma valores em conjuntos Exemplos A1234 sinasinA Ver Também sin sinm asinm 223 Name asind arcoseno resultado em graus tasindx Parâmetros x vetormatriz de reais Os elementos devem estar em 1 1 t vetormatriz de reais com as mesmas dimensões que x Descrição As entradas de t são os arcosinversos das entradas correspondentes de x O domínio de definição é 1 1 Os resultados estão em 90 90 Exemplos x1 0 1 sqrt22 sqrt22 sqrt32 sqrt32 asindx Ver Também sin sind asinm 224 Name asinh arcoseno hiperbólico tasinhx Parâmetros x vetor ou matriz de reais ou complexos t vetor ou matriz de reais ou complexos Descrição As entradas de t são os arcossenos hiperbólicos das entradas correspondentes de x O domínio de definição é1infinito A função toma valores em conjuntos Exemplos A1223 sinhasinhA 225 Name asinhm arcoseno hiperbólico da matriz matriz arcoseno hiperbólico tasinhmx Parâmetros xt matriz quadrada de reais ou complexos Descrição asinhm é o arcoseno hiperbólico da matriz x matriz arcoseno hiperbólico de x Usa a fórmula tlogmxsqrtmxxeye Os resultados podem ser imprecisos se a matriz é não simétrica Exemplos A1223 sinhmasinhmA Ver Também asinh logm sqrtm 226 Name asinm arcoseno da matriz matriz arcoseno tasinmx Parâmetros x matriz quadrada de reais ou complexos t matriz quadrada de reais ou complexos Descrição t é o arcoseno da matriz x matrix matriz arcoseno de x É usado o método da diagonalização Para matrizes nãosimétricas o resultado pode ser impreciso Exemplos A1234 sinmasinmA asinmAilogmiAsqrtmeyeAA Ver Também asin sinm 227 Name atan arcotangente 2quadrantes e 4quadrantes phiatanx phiatanyx Parâmetros x escalar real ou complexo ou vetor ou matriz de reais ou complexos phi escalar real ou complexo ou vetor ou matriz de reais ou complexos x y escalares real ou vetores ou matrizes de reais de mesmo tamanho phi escalar real ou vetor ou matriz de reais Descrição A primeira forma computa o arcotangente 2quadrantes que é o inverso de tanphi Para um real x phi está no intervalo pi2 pi2 Para um complexo x atan tem dois pontos de ramificação singulares ii e os ramos escolhidos são as duas semiretas imaginárias i ioo e ioo i A segunda forma computa o arcotangente 4quadrantes atan2 em FORTRAN isto é retorna o ar gumento ângulo do número complexo xiy A imagem de atanyx é pi pi Para argumentos reais ambas as formas produzem valores idênticos se x0 No caso de os argumentos serem vetores ou matrizes a avaliação é feita elemento a elemento de modo que phi é um vetor ou matriz com o mesmo tamanho de phiijatanxij ou phiijtanyijxij Exemplos exemplos com a segunda forma x1i1i phasexatanimagxrealx atan01 ataneps1 ramos ataneps 2i ataneps 2i ataneps 2i ataneps 2i valores nos pontos de ramificação ieee2 atani atani atan 228 Ver Também tan ieee Autores BP LVD autores da função atan para complexos 229 Name atand arcostangentes 2quadrantes e 4quadrantes elemento a elemento do argumento com resul tados em graus phiatandx phiatandyx Parâmetros x escalar vetor ou matriz de reais phi escalar vetor ou matriz de reais x y escalare vetore ou matrizes de reais com tamanhos iguais phi escalar vetor ou matriz de reais Descrição A primeira forma computa o arcotangente 2quadrantes que é o inverso de tandphi Os ele mentos de phi estão no intervalo 90 90 A primeira forma computa o arcotangente 4quadrantes atan2 em Fortran isto é retorna o argu mento ângulo do número complexo xiy A imagem de atandyx é 180180i Ambas as formas são idênticas se x0 Exemplos exemplo com a segunda forma x01sqrt31sqrt3inf0 atandx Ver Também tan tand Autor Serge Steer INRIA 230 Name atanh arcotangente hiperbólico tatanhx Parâmetros x matriz ou vetor de reais ou complexos t matriz ou vetor de reais ou complexos Descrição Os compontente do vetor t são os arcostangentes hiperbólicos das entradas correspondentes em x O domínio de definição é 11 para a função real ver Observação Observação No Scilab como em alguns outros softwares numéricos quando se tenta avaliar uma função matemática elementar fora de seu domínio de definição no caso real uma extensão complexa é usa da com resultado complexo O exemplo mais famoso é a função sqrt tente sqrt1 Es ta aproximação tem algumas desvantagens quando você avalia a função em um ponto singular que pode levar a diferentes resultados quando o ponto é considerado como real ou complexo Para a função atanh isto ocorre para 1 e 1 porque nestes pontos a parte imaginária não converge e então atanh1 Inf i NaN enquanto atanh1 Inf para o caso real como lim x1 de atanhx Então quando você avaliar esta função no vetor 1 2 como 2 está fora do domínio de definição a extensão complexa é usada para todo o vetor e o resultado de atanh1 Inf i NaN enquanto o resultado de atanh1 Inf com 1 05 por exemplo Exemplos exemplo 1 x0ii tanhatanhx exemplo 2 x inf 3 2 1 0 1 2 3 inf ieee2 atanhtanhx exemplo 3 ver Observação ieee2 atanh1 2 atanh1 05 Ver Também tanh ieee 231 Name atanhm Arcotangente hiperbólico da matriz matriz arcotangente hiperbólico tatanhmx Parâmetros x matriz quadrada de reais ou complexos t matriz quadrada de reais ou complexos Descrição atanhmx é o arcotangente hiperbólico da matriz x matriz arcotangente hiperbólico O resul tado pode ser impreciso se x não é simétrica Exemplos A1234 tanhmatanhmA Ver Também atanh tanhm 232 Name atanm arcotangente da matriz quadrada matriz arcotangente tatanmx Parâmetros x matriz de reais ou complexos quadrada t matriz de reais ou complexos quadrada Descrição atanmx é o arcotangente da matriz x matrtiz arcotangente de x O resultado pode ser impreciso se x não é simétrica Exemplos tanmatanm1234 Ver Também atan 233 Name base2dec conversão da base b para inteiros dbase2decsb Parâmetros d matriz de inteiros s matriz de strings correspondentes às representações em base b b inteiro a base Descrição base2decxb retorna a matriz de número correspondentes à representação em base b Exemplos base2decABC0A16 Ver Também bin2dec oct2dec hex2dec dec2bin dec2oct dec2hex 234 Name bin2dec conversão de representação binária para inteira ybin2decstr Parâmetros str um string ou vetormatriz de strings contendo apenas caracteres 1 e 0 y um escalar ou um vetormatriz de inteiros positivos Descrição Dado str um string binário está função retorna y o número decimal cuja representação binária é dada por str y e str possuem o mesmo tamanho Exemplos example 1 1010110 é a representação binária de 86 str1010110 ybin2decstr example 2 1011011 é a representação binária de 91 1010010 é a representação binária de 82 str1011011 1010010 ybin2decstr Ver Também base2dec oct2dec hex2dec dec2bin dec2oct dec2hex 235 Name binomial probabilidades de distribuição binomial prbinomialpn Parâmetros pr vetor linha com n1 componentes p número real em 01 n um inteiro 1 Descrição prbinomialpn retorna o vetor de probabilidade binomial ie prk1 é a probabilidade de k successos em n tentativas independentes de Bernoulli com probabilidade de sucesso p Em outras palavras prk1 probabilityXk com X uma variável aleatória segundo a distribuição Bnp e numericamente n k nk n n prk1 p 1p com k k k nk Exemplos primeiro exemplo n10p03 xbasc plot2d30nbinomialpn segundo exemplo n50p04 meanp sigmasqrtnp1p x 0nmea sigma xbasc plot2dx sigmabinomialpn deffyGaussxy1sqrt2piexpx22 plot2dx Gaussx style2 pela fórmula binomial cuidado se n for grande function prbinomial2pn xpoly0xprcoeff1pxnhornerx0np endfunction p13n5 binomialpnbinomial2pn pela função gama gamman1n cuidado se n for grande p13n5 Cnksgamman1gamma1n1gamman111 xpoly0x prCnkshornerx0n1xn10p binomial 236 prbinomialpn Ver Também cdfbin grand 237 Name bitand AND e aplicado às representações binárias dos argumentos de entrada zbitandxy Parâmetros x escalarvetormatrizhipermatriz de inteiros positivos y escalarvetormatrizhipermatriz de inteiros positivos z escalarvetormatrizhipermatriz de inteiros positivos Descrição Dado x e y dois inteiros positivos esta função retorna z o número decimal cuja forma binária é o AND das representações binárias de x e y x y e z devem ter o mesmo tamanho Se a dimensão de x e y é superior a 1 então zi é igual a bitandxiyi Exemplos exemplo 1 1010110 é a representação binária de 86 1011011 é a representação binária de 91 1010010 é a representação binária para AND aplicado às formas binárias de 86 e 91 então o número decimal correspondente a AND aplicado às formas binárias de 86 and 91 is 82 x86 y91 zbitandxy exemplo 2 x1245y2549 zbitandxy Ver Também bitor bin2dec dec2bin 238 Name bitor OR ou aplicado às representações binárias dos argumentos de entrada zbitorxy Parâmetros x escalarvetormatrizhipermatriz de inteiros positivos y escalarvetormatrizhipermatriz de inteiros positivos z escalarvetormatrizhipermatriz de inteiros positivos Descrição Dado x e y dois inteiros positivos esta função retorna z o número decimal cuja forma binária é o OR das representações binárias de x e y x y e z devem ter o mesmo tamanho Se a dimensão de x é superior a 1 então zi é igual a bitorxiyi Exemplos exemplo 1 110000 é a representação binária de 48 100101 é a representação binária de 37 110101 é a representação binária para OR aplicado às formas binárias de 48 e 37 então o número decimal correspondente a OR aplicado às formas binárias de 48 e 37 é 53 x48 y37 zbitorxy exemplo 2 x1245 y2549 zbitorxy Ver Também bitand bin2dec dec2bin 239 Name bloc2exp retorna a avaliação simbólica de um diagrama de blocos strbloc2expblocd strnamesbloc2expblocd Parâmetros blocd lista str string names string Descrição Dada uma representação em diagrama de blocos de um sistema linear bloc2exp retorna sua avaliação simbólica O primeiro elemento da lista blocd deve ser o string cadeia de caracteres blocd Cada outro elemento desta lista blocd2blocd3 é por si mesmo uma lista de um dos seguintes tipos listtransfernomedosistemalinear listlinknomedaligação númerodecaixadefluxosuperiorportadacaixadefluxosuperior caixadefluxoinferior1númerodeportadacaixainferior1 caixadefluxoinferior2númerodeportadacaixainferior2 Os strings transfer e links são palavraschaves as quais indicam o tipo de elemento no diagrama de blocos transfertransferência link ligação Caso 1 o segundo parâmetro da lista é um string que pode se referir para uma possível avaliação posterior ao nome Scilab de um sistema linear dado em representação de estadoespaço lista sys lin ou em forma de trasnferência matriz de razões de polinômios A cada bloco de transferência é associado um inteiro A cada entrada e saída de um bloco de transferência também é associado seu número um inteiro ver exemplos Caso 2 O segundo tipo de elemento em uma representação de diagrama de blo cos é um link Um link liga uma saída de um bloco representado pelo par númerodecaixadefluxosuperiorportadacaixadefluxosuperior a diferentes entradas de outros blocos Cada tal entrada é representada pelo par caixadefluxoinferiorinúmerodeportadacaixainferiori Os diferentes elementos de um diagrama de blocos podem ser definidos em ordem arbitrária Por exemplo 1 S1S2 com feedback resposta de unidade bloc2exp 240 Há 3 transferências S1 número ns12 S2 número ns23 e um adicionador adder número nadd4 com função de transferência simbólica 11 Há 4 ligações O primeiro de nome U liga a entrada porta 0 de bloco fictício 1 omitido à porta 1 do adicionador Os segundo e terceiro ligam respectivamente a porta de saída 1 do adicionador à porta de entrada 1 do sistema S1 e a porta de saída 1 de S1 à porta de entrada 1 de S2 A quarta ligação de nome Y liga a porta de saída 1 de S2 à saída porta 0 do bloco fictício 1 omitido e à porta de entrada 2 do adicionador Inicialização systlistblocd l1 Sistemas ll1ns1lsystllisttransferS1 Sistema 1 ll1ns2lsystllisttransferS2 Sistema 2 ll1nadderlsystllisttransfer11 adicionador Links Entradas 1 entrada 1 ll1systllistlinkU1nadder1 Internal ll1systllistlink nadder1ns11 ll1systllistlink ns11ns21 Saídas 1 saída 1 ll1systllistlinkYns211nadder2 Chamada de avaliação wbloc2expsyst O resultado é o string ws2s1eyes2s1 Perceba que chamado com dois agumentos de saída strnames blocdsyst retorna em names a lista de nomes simbólicos dos links nomeados Isto é útil para definir nomes de entradas e saídas 2 segundo exemplo Inicialização systlistblocd l1 Sistema planta de blocos 2x2 ll1nslsystllisttransferP11P12P21P22 Controlador ll1nklsystllisttransferk Links ll1systllistlinkw1ns1 ll1systllistlinkzns11 ll1systllistlinkunk1ns2 ll1systllistlinkyns2nk1 Chamada de avaliação wbloc2expsyst Neste caso o resultado é uma fórmula equivalente à usual bloc2exp 241 P11P12invreyeKP22KP21 Ver Também bloc2ss Autores S S F D INRIA 242 Name bloc2ss conversão de diagrama de blocos para espaço de estados slbloc2ssblocd Parâmetros blocd lista sl lista Descrição Dada uma representação em diagrama de blocos de um sistema linear bloc2ss converte esta representação em um sistema linear de espaço de estados O primeiro elemento da lista blocd deve ser o string cadeia de caracteres blocd Cada outro elemento desta lista é por si mesmo uma lista de um dos seguintes tipos listtransfernomedosistemalinear listlinknomedolink númerodecaixadefluxosuperiorportadacaixadefluxosuperior caixadefluxoinferior1númerodeportadacaixainferior1 caixadefluxoinferior2númerodeportadacaixainferior2 Os strings transfer e links são palavraschaves as quais indicam o tipo de elemento no diagrama de blocos transfertransferência link ligação Caso 1 o segundo parâmetro da lista é um string que pode se referir para uma possível avaliação posterior ao nome Scilab de um sistema linear dado em representação de espaço de estados lista syslin ou em forma de trasnferência matriz de razões de polinômios A cada bloco de transferência é associado um inteiro A cada entrada e saida de um bloco de transferência também é associado seu número um inteiro ver exemplos Caso 2 O segundo tipo de elemento em uma representação de diagrama de blo cos é um link Um link liga uma saída de um bloco representado pelo par númerodecaixadefluxosuperiorportadacaixadefluxosuperior a diferentes entradas de outros blocos Cada tal entrada é representada pelo par caixadefluxoinferiorinúmerodeportadacaixainferiori Os diferentes elementos de um diagrama de blocos podem ser definidos em ordem arbitrária Por exmeplo 1 S1S2 com feedback resposta de unidade Há 3 transferências S1 número ns12 S2 número ns23 e um adicionador adder número nadd4 com função de transferência simbólica 11 Há 4 links O primeiro de nome U liga a entrada porta 0 de bloco fictício 1 omitido à porta 1 do adicionador Os segundo e terceiro ligam respectivamente a porta de saída 1 do adicionador à bloc2ss 243 porta de entrada 1 do sistema S1 e a porta de saída 1 de S1 à porta de entrada 1 de S2 O quarto link de nome Y liga a porta de saída 1 de S2 à saída porta 0 do bloco fictício 1 omitido e à porta de entrada 2 do adicionador Inicialização systlistblocd l1 Sistemas ll1ns1lsystllisttransferS1 Sistema 1 ll1ns2lsystllisttransferS2 Sistema 2 ll1nadderlsystllisttransfer11 adicionador Links Entradas 1 entrada 1 ll1systllistlinkU11nadder1 Internal ll1systllistlink nadder1ns11 ll1systllistlink ns11ns21 Saídas 1 saída 1 ll1systllistlinkYns211nadder2 Com spoly0sS11s1S21s o resultado da avaliação de chamada slbloc2sssyst é uma representação em estadoespaço para 1s2s1 2 exemplo da transformação linear fracional TLF e em inglês LFT Inicialização systlistblocd l1 Sistema planta de blocos 2x2 ll1nslsystllisttransferP11P12P21P22 Controlador ll1nklsystllisttransferk Links ll1systllistlinkw1ns1 ll1systllistlinkzns11 ll1systllistlinkunk1ns2 ll1systllistlinkyns2nk1 Com PsyslincABCD P11P11 P12P12 P21P21 P22P22 KsyslincAkBkCkDk bloc2expsyst retorna a avaliação de TLF de P e K bloc2ss 244 Ver Também bloc2exp Autores S S F D INRIA 245 Name cat concatena vários arrays ycatdimsA1A2An Parâmetros dims um escalar real positivo A1A2An escalares vetores matrizes multiarrays ou cell arrays A1 A2 An devem ter o mesmo taman ho excluindo o número de dimensão dims sizeA1isizeA2isizeAni para i diferente de dims e sizeA1dims sizeA2dimssizeAndims podem ser diferentes y um escalar vetor matriz ou multiarray y tem o mesmo tipo de A1A2An Descrição ycatdimsA1A2An y é o resutado da concatenação dos argumentos de entrada A1 A2 An Se dims 1 então a concatenação é feita de acordo com as linhas se dims 2 então a concatenação é feita de acordo com as colunas dos argumentos de entrada Se dims 1então a concatenação é feita de acordo com as linhas A11 2 3 4 5 6 A27 8 9 10 11 12 ycat1A1A2 y1 2 3 4 5 61 7 8 9 10 11 12 Se dims 2então a concatenação é feita de acordo com as colunas dos argumentos de entrada A11 2 34 5 6 A27 8 9 10 11 12 ycat2A1A2 y1 2 3 7 8 9 4 5 6 10 11 12 Exemplos primeiro exemplo concatenação de acordo com as linhas dims1 A11 2 3 A24 5 6 7 8 9 A310 11 12 ycatdimsA1A2A3 segundo exemplo concatenação de acordo com as colunas dims2 A11 2 3 A24 57 89 10 ycatdimsA1A2 terceiro exemplo concatenação de acordo com a terceira dimensão dims3 A1matrix112223 A213 1415 16 A3matrix2136224 ycatdimsA1A2A3 Ver Também permute matrix Autor Farid Belahcene 246 Name ceil arredonda o número para o inteiro maior ou igual ao número yceilx Parâmetros x uma matriz de reais y uma matriz de inteiros Descrição ceilx retorna uma matriz de inteiros feita de arredondamentos para cima dos elementos Exemplos ceil19 2522 ceilinf xrand1020ceilxx Ver Também round floor int 247 Name cell2mat converte um cell array array de células em uma matriz xcell2matc Parâmetros c cell os componentes de c devem ter o mesmo tipo e podem ser escalares ou matrizes x matriz Descrição Retorna uma matriz que é a concatenação de todos os componentes do cell célula c cell2matc todos os componentes de c devem ter o mesmo tipo de dado string doubles inteiros ou booleanos Para cada linha i de c cell2mat concatena todos os componentes da iésima linha do cell c Perceba que se os componentes da entrada do cell c são são strings então cell2matc retorna um vetorcoluna de concatenação de strings Exemplos cmakecell221 2 3 6 7 84 59 1011 1216 1714 13 1518 19 20 cell2matc Ver Também cell 248 Name cellstr converte um vetor ou matriz de strings em um cell de strings ccellstrs Parâmetros s vetor de strings ou matriz de strings Descrição Retorna um cell array de strings Se s ié um vetor linha de strings então cellstrs retorna um cell umporum que contém um componente a concatenação de todas as colunas componentes de s Se s é um vetor coluna de strings então cellstrs converte s em um cell que tem o mesmo tamanho cell de strings sizes1porum Se s é uma matriz de strings então para cada linha i de s cellstrs concatena todos os componentes da iésima linha da matriz s ie si1 si2 si3 e retorna um cell de strings sizes1porum Exemplos cellstrfoo cellstrscilab cellstrabcdefghijklm Ver Também cell string 249 Name char função char ychar x ycharst1st2st3 Parâmetros x um cell de arrays de strings ou um array de códigos ASCII st1st2st3 arrays de strings y vetor coluna de strings Descrição Argumento de uma entrada Dado um cell de arrays de strings x esta função retorna um vetor de strings y no qual as linhas são componentes do cell de strings Dado um array de códigos ASCII x esta função retorna um array de strings y corre spondente aos códigos ASCII Se dims xn1n2n3n4 então o valor retornado tem o mesmo tamanho que o valor de entrada ao invés do segundo dims dimsyn1n3n4 Argumento de mais de uma entrada Dados arrays de strings st1st2st3 esta função retorna um vetor de strings no qual as linhas são os componentes de st1st2st3 No vetor y o comprimento de todos os strings sti é completado por lacunas para terem o mesmo comprimento que o comprimento máximo de sti Exemplos exemplo com uma hipermatriz de códigos ASCII xhypermat4236184 ycharx sizex sizey Exemplo com mais de um argumento st1zeros st2onetwo st3three ycharst1st2st3 sizey todos os strings são completados por lacunas para terem o mesmo comprimento 6 lengthy Ver Também asciimat Autor FB 251 Name conj matriz conjugada yconjx Parâmetros xy matrizes de reais ou complexos Descrição conjx é a matriz conjugada complexa de x Exemplos x1iii2i conjx xconjx x é a matriz transposta conjugada 252 Name cos função coseno ycosx Parâmetros x matriz ou vetor de reais ou complexos Descrição Para uma matriz ou vetor cosx é o coseno de seus elementos Para o coseno da matriz matriz coseno use a função cosmX Exemplos x01i acoscosx Ver Também cosm 253 Name cosd função coseno elemento a elemento argumento dado em graus ycosdx Parâmetros x vetormatriz de reais Descrição Para um vetor ou uma matriz x de ângulos dados em graus cosdx é o coseno de seus elementos Os resultados estão em 1 1 Para elementos de entrada que são iguais a n90 com n inteiro e ímpar o resultado é exatamento zero Exemplos x030 45 60 90 360 cosdx Ver Também cos Autor Serge Steer INRIA 254 Name cosh coseno hiperbólico tcoshx Parâmetros xt matriz ou vetor de reais ou complexos Descrição Os elementos de t são os cosenos hiperbólicos da entradas correspondentes do vetor x Exemplos x01i acoshcoshx Ver Também cos acosh 255 Name coshm coseno hiperbólico da matriz matriz coseno hiperbólico tcoshmx Parâmetros xt matriz quadrada de reais ou complexos Descrição coshm é o coseno hiperbólico da matriz x matriz coseno hiperbólico de x texpmxexpm x2 O resultado pode ser impreciso para matrizes nãosimétricas Exemplos A1224 acoshmcoshmA Ver Também cosh expm 256 Name cosm coseno da matriz matriz coseno tcosmx Parâmetros x matriz quadrada de reais ou complexos Descrição cosmx é o coseno da matriz x matriz coseno de x t05expmixexpm ix Exemplos A1234 cosmA05expmiAexpmiA Ver Também cos expm 257 Name cotd cotangent elemento a elemento do argumento dado em graus ycotdx Parâmetros x array de reais y array de reais com as mesmas dimensões que x Descrição As entradas y são as cotangentes das entradas correspondentes de x supostamente dadas em graus tcosxsinx Para entradas iguais a n180 com n inteiro os resultados são infinitos en quanto que com cotgnpi o resultado é grande pois pi não pode ser representado exata mente para entradas iguais a n90 com n inteiro e ímpar o resultado é exatamente 0 Exemplos x30 45 60 90 cotdx Ver Também cotg Autor Serge Steer INRIA 258 Name cotg cotangente tcotgx Parâmetros xt vetores ou matrizes de reais ou complexos Descrição Os elementos de t são as cotangentes das entradas correspondentes de x tcosxsinx Exemplos x1i cotgxcosxsinx Ver Também tan 259 Name coth cotangente hiperbólica tcothx Descrição Os elementos do vetor t são as cotangentes hiperbólicas dos elementos do vetor x Exemplos x12i texpx tonesxttonesxt cothx Ver Também cotg 260 Name cothm cotangente hiperbólica da matriz matriz cotangente hiperbólica tcothmx Descrição cothmx é a matriz contangente hiperbólica da matriz quadrada x Exemplos A1234 cothmA Ver Também coth 261 Name csc computa a cossecante do argumento elemento a elemento y cscx Parâmetros x array de reais ou complexos y array de reais ou complexos com as mesmas dimensões que x Description Computa a cossecante do argumento elemento a elemento A função cossecante é uma função periódica definida como 1sin Para dados reais os resultados são reais em inf 1 U 1 inf Exemplos xlinspace001pi001200 clfplotxcscxxcscx Ver Também sec cscd Autor Serge Steer INRIA 262 Name cscd computa a cossecante elemento a elemento do argumento em graus x cscdx Parâmetros x array de reais ou complexos x array de reais ou complexos Descrição As emtradas de y são as cossecantes 1sin das entradas de x dadas em graus Os resultados são reais em inf 1 U 1 inf Para entradas iguais a n180 com n inteiro o resultado é infinito ou um erro dependendo do modo ieee Para entradas iguais a n90 com n inteiro e ímpar o resultado é exatamente 1 ou 1 Exemplos cscpi4 cscd90 Ver Também secd csc sind Autor Serge Steer INRIA 263 Name csch computa a cossecante hipertbólica do argumento elemento a elemento y cschx Parâmetros x array de reais ou complexos y array de reais ou complexos com as mesmas dimensões que x Descrição Computa a cossecante hipertbólica do argumento elemento a elemento Para dados reais os resultados são reais Exemplos xlinspace0014200xx11 nan x clfplotxcschx Ver Também csc acsch Autor Serge Steer INRIA 264 Name cumprod produto cumulativo ycumprodx ycumprodxr ou ycumprodx1 ycumprodxc ou ycumprodx2 ycumprodxm Parâmetros x vetor ou matriz de reais ou complexos y vetor ou matriz de reais ou complexos Descrição Para um vetor ou matriz x ycumprodx retorna em y o produto cumulativo de todas as entradas de x tomadas coluna a coluna ycumprodxc ou equivalentemente ycumprodx2 retorna em y o produto cumu lativo dos elementos das colunas de x yicumprodxi ycumprodxr ou equivalentemente ycumprodx2 retorna em y o produto cumu lativo dos elementos das linhas de x yicumprodxi ycumprodxm é o produto cumulativo ao longo da primeira dimensão nãosingleton de x para compatibilidade com Matlab Exemplos A1234 cumprodA cumprodAr cumprodAc randseed0 arand34 mnsizea wzerosa w1a1 for k2mwkwk1akendwcumprodar Ver Também cumsum sum prod 265 Name cumsum soma cumulativa ycumsumx ycumsumxr or ycumsumx1 ycumsumxc or ycumsumx2 Parâmetros x vetor ou matrix de reais ou complexos y vetor ou matrix de reais ou complexos Descrição Para um vetor ou uma matriz x ycumsumx retorna em y a soma cumulativa de todas as entradas de x tomadas coluna a coluna ycumsumxc ou equivalentemente ycumsumx2 retorna em y a soma cumulativa das colunas de x yicumsumxi ycumsumxr ou equivalentemente ycumsumx1 retorna em y a soma cumulativa das linhas de x yicumsumxi ycumsumxm é a soma cumulativa ao longo da primeira dimensão nãosingleton de x para compatibilidade com o Matlab Exemplos A1234 cumsumA cumsumAr cumsumAc arand34i mnsizea wzerosa w1a1 for k2mwkwk1akendwcumsumar Ver Também cumprod sum 266 Name dec2bin representação binária strdec2binxn Parâmetros x escalarvetormatrizhypermatriz de inteiros positivos n um inteiro positivo str um string ou vetor de strings Descrição Dado x um inteiro ou um vetormatriz de inteiros positivo esta função retorna um string ou um vetor coluna de strings que é a representação binária de x Se a dimensão de x é superior a 1 então cada componente do vetor coluna str é a representação binária dos componentes de x ie stri é a representação binária de xi Se o comprimento dos componentes de str é menor que n ie length stri n então adicione aos componentes de str os caracteres 0 à esquerda para se obter o comprimento dos componentes igual a n Exemplos exemplo 1 x86 strdec2binx exemplo 2 a representação binária de 86 é 1010110 seu comprimento é 7menor que n então temos adicionamos a str 8 vezes o caracteres 0 à esquerda x86n15 strdec2binxn exemplo 3 x1245135 zdec2binx Ver Também base2dec bin2dec oct2dec hex2dec dec2oct dec2hex 267 Name dec2hex representação hexadecimal de inteiros hdec2hexd Parâmetros d matriz de inteiros nãonegativos h matriz de strings Descrição dec2hexx retorna a representação hexadecimal de uma matriz de inteiros Exemplos dec2hex2748 1011 3 Ver Também base2dec bin2dec oct2dec hex2dec dec2bin dec2oct 268 Name dec2oct representação octal de inteiros odec2octd Parâmetros d matriz de inteiros nãonegativos o matriz de strings Descrição dec2octx retorna a representação octal de uma matriz de inteiros Exemplos dec2oct2748 1011 3 Ver Também base2dec bin2dec oct2dec hex2dec dec2bin dec2hex 269 Name delip Integral elíptica rdelipxck Parâmetros x vetor real com elementos nãonegativos ck número real entre 1 e 1 r número real ou complexo ou vetor de reais ou complexos com mesmo tamanho que x Descrição A integral elíptica de primeira espécie com parâmetro ck definido como segue Onde x é real e positivo e ck está em 1 1 Se x é menor do que ou igual a 1 o resultado é real Quando chamado com x um vetor real r é avaliado para cada entrada de x Exemplos ck05 delip12ck deffyfty1sqrt1t21ck2t2 intg01f OK desde que a solução seja real Ver Também amell asn sn 270 Name diag inclusão ou extração diagonal ydiagvm k Parâmetros vm vetor ou matriz armazenamento cheio ou esparso k inteiro o valor padrão é 0 y vetor ou matriz Descrição Para um nvetor linha ou coluna vm diagvm retorna uma matriz diagonal com entradas de vm ao longo da diagonal principal diagvmk é uma matriz nabskxnabsk com entradas de vm ao longo da késima diagonal k0 é a diagonal principal k0 são as diagonais superiores e k0 são as diagonais infe riores Para uma matriz vm diagvmk é o vetor coluna feito das entradas da késima diagonal de vm diagvm é a diagonal principal de vm diagdiagx é a matriz diagonal Se vm é uma matriz esparsa diagvmk retorna uma matriz esparsa Para construir um sistema linear diagonal use sysdiag Perceba que eyeAA retorna uma matriz diagonal feita das entradas diagonais de A Isto é válido para qualquer matriz constante de polinômios de razões de polinômios sistema linear em espaço de estados Exemplos diag12 A1234 diagA diagonal principal diagA1 diagsparse110 matriz diagonal esparsa forma de uma matriz triadiagonal de tamanho 2m1 m5diagmm diagones2m11 diagones2m11 Ver Também sysdiag sparse 271 Name diff diferença e derivada discreta ydiffx ydiffx n dim Parâmetros x vetor ou matriz de reais complexos esparsoa ou de polinômios n inteiro ordem da diferenciação dim inteiro ou cadeia de caracteres com valores rc e y escalar ou vetor Descrição ydiffx computa a função de diferença yx2x11 diffxndim é a nésima função de diferença ao longo da dimensão dim diffxn é equivalente a diffxn O valor padrão para n é 1 O valor padrão para dim é dimr é equivalente a dim1 e dimc é equivalente a dim2 Exemplos v183 diffv diffv3 A182 183 184 diffA32 diferenciação aproximada step0001 t0step10 ysint dydiffsintstep diferenciação aproximada da função seno normdycost11inf 272 Name double conversão de inteiro para representação de dupla precisão ydoubleX yint16X yint32X yuint8X yuint16X yuint32X Parâmetros X matriz de números em ponto flutuante ou inteiros y matriz de números em ponto flutuante Descrição Converte os dados armazenados usando inteiros de 1 2 ou 4 bytes em representação de ponto flutuante de dupla precisão Se as entradas de X já são números de ponto flutuante de dupla precisão nada é feito Exemplos xint80 12 140 doublex Ver Também int8 inttype type 273 Name dsearch Busca binária também conhecida como busca dicótoma em francês ind occ info dsearchX val ch Parâmetros X um vetor ou matriz de reais val um vetor linha ou coluna de reais com n componentes em ordem estritamente crescente val1 val2 valn ch opcional um caractere c ou d valor padrão c ind um vetor ou matriz de reais com as mesmas dimensões que X occ um vetor de reais com o mesmo formato que val mas com n1 componentes no caso em que chc info inteiro Descrição Esta função é útil para encontrar em uma tabela table ordenada eou contar o número de compo nentes de um vetor caindo em algumas classes sendo uma classe um intervalo ou um valor Por padrão ou quando chc temos o caso de intervalos isto é para cada Xi busca em qual dos n1 intervalos o componente do vetor cai sendo os intervalos definidos por I1 val1 val2 Ik valk valk1 for 1 k n1 e indi é o número do intervalo de Xi 0 se Xi não está em val1valn occk é o número de componentes de X que estão em Ik info é o número de componentes de X que não estão em val1valn Quando chd temos o caso discreto isto é para cada Xi busca se é igual a um valor valk e indi é igual ao índice do componente de val que corresponde a Xi indi k se Xivalk ou 0 se Xi não está em val dsearch 274 occk é igual ao número de componentes de X iguais a valk info é o número de componentes de X que não estão no conjunto val1valn Exemplos exemplo 1 estatística elementar para U01 m 50000 n 10 X grandm1def val linspace01n1 ind occ dsearchX val xbasc plot2d2val occm0 sem normalização y deve ser próximo de 1n exemplo 2 estatística elementar para BNp N 8 p 05 m 50000 X grandm1binNp val 0N ind occ dsearchX val d Pexp occm Pexa binomialpN xbasc hm 11maxmaxPexamaxPexp plot2d3val val01 Pexa Pexp1 2111 PexactPexp 1 0 N1 hm0 N2 0 6 xtitle Distribuição binomial BstringNstringp probabilidades exatas versus as experimentais exemplo 3 polinômio de Hermite seccionado x 0 02 035 05 065 08 1 y 0 01 01 0 04 01 0 d 1 0 0 1 0 0 1 X linspace0 1 200 ind dsearchX x definindo funções bases hermitianas deffyLltkxytxk1xkxk1 Lagrange esquerdo em Ik deffyLrtkxytxkxk1xk Lagrange direito em Ik deffyHltkxy12txkxkxk1Lltkx2 deffyHrtkxy12txk1xk1xkLrtkx2 deffyKltkxytxkLltkx2 deffyKrtkxytxk1Lrtkx2 plotando a curva Y yindHlXind yind1HrXind dindKlXind dind1KrXind xbasc plot2dXY2 plot2dxy9000 xtitleUm polinômio seccionado de hermite NOTE a verificação pode ser feita adicionandose YY interpXxyd plot2dXYY3000 Ver Também find tabul Autor BP 275 Name eval avaliação de uma matriz de strings H evalZ Descrição Retorna a avaliação da matriz de strings Z Exemplos a1 b2 Zasinb evalZ retorna a matriz 10909 Ver Também evstr execstr 276 Name exp exponencial em relação aos elementos expX Parâmetros X escalar vetor ou matriz de entradas reais ou complexas Descrição expX é a função exponencial elemento a elemento das entradas deX Exemplos x123i logexpx elemento a elemento 2x expxlog2 Ver Também coff log expm 277 Name eye matriz identidade Xeyemn XeyeA Xeye Parâmetros AX matrizes ou listas syslin mn inteiros Descrição Define uma matriz mxn com 1s ao longo de sua diagonal ou uma matriz identidade com as mesmas dimensões de A Cuidado eye10 é interpretado como eyeA com A10 ie 1 NÃO é uma matriz identidade 10 x 10 Se A é um sistema linear representado por uma lista syslin eyeA retorna uma matriz eye com dimensões apropriadas número de saídas x número de entradas eye produz uma matriz identidade com dimensões indefinidas As dimensões serão definidas quan do esta matriz identidade for adicionada a uma matriz com dimensões fixas Exemplos eye23 Arand23eyeA spoly0sAs1ss1eyeA A1s1s2eyeA Assrand223eyeA 1 23 42eye Ver Também ones zeros 278 Name factor fatoração yfactorx Parâmetros x escalar real y vetor de números primos Descrição Dado um real x factorx retorna em um vetor y a decomposição em números primos de x Caso particular factor0 retorna 0 e factor1 retorna 1 Exemplos x620 yfactorx Ver Também primes 279 Name fix arredonda em direção a zero yfixx Parâmetros x uma matriz de reais y uma matriz de inteiros Descrição fixx retorna uma matriz de inteiros feita de arredondamentos em direção a zero ie ysignxfloorabsx É o mesmo que int Ver Também round floor ceil 280 Name flipdim gira os componentes de x ao longo de uma dada dimensão yflipdimxdim Parâmetros x um escalar vetor ou array de reais dim um inteiro positivo y um escalar vetor ou array de reais Descrição Dado x um escalarvetorarray de reais e dim um inteiro positivo esta função gira os componentes de x ao longo da dimensão de número dim de x x e y têm o mesmo tamanho Exemplos exemplo 1 girando os componentes de x ao longo da primeira dimensão x1 2 3 4 5 6 7 8 dim1 yflipdimxdim exemplo 1 girando os componentes de x ao longo da segunda dimensão dim2 yflipdimxdim exemplo e girando os componentes de x ao longo da terceira dimensão xmatrix1483 242 dim3 yflipdimxdim Ver Também FBelahcene 281 Name floor arredondamento para o inteiro menor ou igual ao número yfloorx Parâmetros x matriz de reais y matriz de inteiros Descrição floorx retorna uma matriz de inteiros feita a partir de arredondamentos para baixo Exemplos floor19 2513 floorinf xrand1020floorxx Ver Também round fix ceil 282 Name frexp separa um número em ponto flutuante em potência de base 2 e mantissa fefrexpx Parâmetros x vetor ou matriz de reais f array de valores reais geralmente no intervalo 05 absf 1 e array de inteiros que satisfazem a equação x f2e Descrição Esta função corresponde à função ANSI C frexp Quaisquer zeros em x produzem f0 e e0 Exemplos fefrexp1pi3eps Ver Também log hat ieee log2 283 Name gsort ordenação decrescente s kgsortv s kgsortvflag1 s kgsortvflag1flag2 Parâmetros vs vetor ou matriz de reais inteiros ou strings ou sparse vector flag1 um string r cglr ou lc flag2 um string i para ordem crescente ou d para ordem decrescente k vetor ou matriz de inteiros Descrição gsort é semelhante a sort com propriedades adicionais O terceiro argumento pode ser usado para escolher ordem crescente ou decrescente O segundo argumento podem ser usado para ordens léxicas skgsortag e skgsortagd são o mesmo que skgsorta Eles realizam uma ordenação das entradas da matriz a a sendo vista como vetor de pilhas a coluna a coluna skgsortagi realiza a mesma operação mas em ordem crescente skgsortalr ordena as linhas da matriz a em ordem léxica decrescente s é obtida por uma permutação das linhas da matriz a dada pelo vetor coluna k de tal modo que as linhas de s verificam si sj se ij skgsortalri realiza a mesma operação mas em ordem léxica crescente skgsortalc ordena as colunas da matriz a em ordem léxica decrescente s é obtida por uma permutação das colunas da matriz inta ou a dada pelo vetor linha k ide tal modo que as colunas de s verificam si sj se ij skgsortalci realiza a mesma operação mas em ordem léxica crescente Quando v é complexo os elementos são ordenados pela magnitude ie absv Apenas g como segundo argumento funciona com complexos Se v tem elementos nan ou inf gsort coloca esses elementos no início com o argumento i ou ao fim com o argumento d Exemplos alr122 121 112 111 alr1kgsortalrlri alr1kgsortalrlci vint32alr gsortv gsort 284 gsortvlri gsortvlci vScilab 26 Scilab 27 Scicos 27 Scilab 31 Scicos 31 Scicos 40 Scilab 40 gsortvlri gsortvlci Ver Também find Bibliografia Algoritmo Quicksort 285 Name hex2dec conversão de representação hexadecimal para inteiros dhex2dech Parâmetros d matriz de inteiros h matriz de strings correspondentes às representações hexadecimais Descrição hex2decx retorna a matriz de números correspondentes às representações hexadecimais Exemplos hex2decABC0A Ver Também base2dec bin2dec oct2dec dec2bin dec2oct dec2hex 286 Name imag parte imaginária yimagx Parâmetros x matriz ou vetor de reais ou complexos y matriz ou vetor de reais Descrição imagx é a parte imaginária de x ver i para entrar com números complexos Ver Também real 287 Name imult multiplicação pela parte imaginária i yimultx Parâmetros x escalar real ou complexo vetor ou matriz de reais ou complexos y escalar complexo vetor ou matriz de complexos Descrição imultx é um modo mais eficiente de se multiplicar x por i que y ix sem os problemas que ocorrem quando x inclui números especiais em ponto flutuante como inf e nan Exemplos z1 imultinf z2 i inf Autor BP 288 Name ind2sub conversão de índice linear para matriz de valores subescritos i1i2 ind2subdimsI Mi ind2subdimsI Parâmetros dims vetor com as dimensões da matriz I vetor com os dados índices lineares i1i2 valores subescritos de mesma forma que I Mi matriz cujas colunas contém os valores subescritos Descrição ind2sub é usado para determinar os valores subescritos equivalentes que correspondem a um índice único num array i1i2 ind2subdimsI retorna os arrays i1 i2 contendo os subescritos das linha coluna equivalentes correspondente à matriz de índices I para uma matriz de tamanho dims Miind2subdimsI retorna uma matriz Mi cujas colunas são os arrays i1 i2 Exemplos ind2sub232112 ijkind2sub232112 Ver Também sub2ind extraction insertion Autor Serge Steer INRIA 289 Name int parte inteira yintX Parâmetros X matriz de reais y matriz de inteiros Descrição intX retorna a parte inteira da matriz de reais X É o mesmo que fix Ver Também round floor ceil 290 Name intersect returns the vector of common values of two vectors v kakbintersectab v kakbintersectaborient Parâmetros a vetor de números ou strings b vetor de números ou strings orient flag com possíveis valores 1 ou r 2 ou c v vetor linha de números ou strings ka vetor linha de inteiros kb vetor linha de inteiros Descrição intersectab retorna um vetorlinha ordenado dos valores comuns a dois vetores a e b vkakbintersectab retorna também dois vetores de índices ka e kb tais que vaka e vbkb intersectabr ou intersectab1retorna a matriz formada interseção das linhas únicas de a e b ordenadas em ordem lexicográfica ascendente Neste caso a e b devem ter o mesmo número de colunas vkakbintersectabr retorna também dois vetores de índices ka e kb tais que vaka e vbkb intersectabc ou intersectab2retorna a matriz formada interseção das colu nas únicas de a e b ordenadas em ordem lexicográfica ascendente Neste caso a e b devem ter o mesmo número de linhas vkakbintersectabc retorna também dois vetores de índices ka e kb tais que vaka e vbkb Observação NaN são considerados diferentes deles mesmos então são excluídos da interseção em caso de interseção de vetores Exemplos intersect 291 Around5rand101 Bround5rand71 intersectAB NkakbintersectAB intersectastringAastringB intersectint16Aint16B com matrizes A 0011 1 01111 20111 02222 20111 0011nan B 101 102 123 204 125 nan06 vkakb intersectABc Aka Ver Também unique gsort union 292 Name inttrap integração de dados experimentais por interpolação trapezoidal v inttrapx s Parâmetros x vetor de dados de coordenadas x crescentes O valor padrão é 1sizey s vetor de dados de coordenadas y v valor da integral Descrição Computa Onde f é uma função descrita por um conjuto de valores experimentais sifxi e x0x1 x1xn Entre os pontos da malha a função é interpolada linearmente Exemplos t001pi inttraptsint Ver Também intg intc intl integrate intsplin splin 293 Name isdef verifica existência de variáveis isdefname where Parâmetros name um string where um string opcional com valor padrão all todos os locais Descrição isdefname retorna T se a variável name existe e F em caso contrário Aviso uma função que utiliza isdef pode retornar um resultado que depende do ambiente isdefnamelocal retorna T se a variável name existe no ambiente local da função cor rente e F em caso contrário isdefnamenolocal retorna T se a variável name existe no ambiente de chamada com pleto incluindo o nível global da função corrente e F em caso contrário Exemplos A1 isdefA clear A isdefA function level1 function level2 dispisdefaall dispisdefalocal dispisdefanolocal endfunction level2 endfunction function go a1 level1 endfunction go Ver Também exists isglobal whereis type typeof clear 294 Name isempty verifica se uma variável é uma matriz vazia ou uma lista vazia tisemptyx Parâmetros x vetor matriz ou lista t um booleano Descrição isemptyx retorna true verdadeiro se x é uma matriz vazia ou uma lista vazia Exemplos a1 isemptya2 isemptyfindrand1105 295 Name isequal comparação de objetos tisequalab tisequalab Parâmetros a b variáveis de quaisquer tipos t um booleano Descrição isequal compara seus argumentos Se todos eles forem iguais a função retorna t e em caso contrário retorna f Na comparação de listas estruturas etc a o processo é feito recursivamente e a ordem dos campos importa Dados de ponto flutuante são comparados de acordo com a regra IEEE ie valores NaN não é um número não são iguais Ver isequalbitwise para comparações bit a bit Exemplos a1 2 isequala1 2 isequala1 Ver Também isequalbitwise equal less 296 Name isequalbitwise comparação bit a bit de variáveis tisequalbitwiseab tisequalbitwiseab Parâmetros a b variáveis de quaisquer tipos t um booleano Descrição isequalbitwise compara seus argumentos Se todos eles são iguais a função retorna t e em caso contrário f Na comparação de listas estruturas etc a comparação é feita recursivamente a ordem dos campos importa Dados de ponto flutuante são comparados bit a bit ie valores NaN não é um número são iguais double1 e int321 não são iguais Ver isequal para comparações IEEE Exemplos alist15s1ABCDEFG isequalbitwiseaa Ver Também isequal 297 Name isinf verifica se há entradas infinitas risinfx Parâmetros x um vetor ou matriz de reais ou complexos r um vetor ou matriz de valores booleanos Descrição isinfx retorna um vetor ou matriz de valores booleanos que contém entradas verdadeiras corre spondentes às entradas de x infinitas e entradas falsas correspondentes às entradas de x finitas Exemplos isinf1 001 inf inf Ver Também isnan 298 Name isnan verifica entradas NaN não é um número risnanx Parâmetros x real or complex vector or matrix r boolean vector or matrix Descrição isnanx retorna um vetor ou matriz de valores booleanos que contém entradas verdadeiras corre spondentes às entradas NaN de x e entradas falsas correspondentes às entradas regulares de x Exemplos isnan1 001 nan infinf Ver Também isinf 299 Name isreal verifica se uma variável é armazenada como real ou complexa tisrealx tisrealxeps Parâmetros x vetor ou matriz com entradas ou coeficientes de ponto flutuante t um booleano Descrição isrealx retorna true verdadeiro se x é armazenado como uma variável real e falso se x é armazenado com uma parte imaginária que pode ser zero 0 isrealxeps retorna true se x é armazenado como uma variável real ou se o valor absoluto máximo dos pontos flutuantes imaginários é menor que ou igual a eps Exemplos isreal1 2 isreal10i isreal10i0 isreal1s isrealsprand3301 300 Name kron produto de Kronecker kronAB AB Descrição kronAB ou AB retorna o produto tensorial de Kronecker entre duas matrizes A e B A matriz resultante tem a seguinte forma de blocos A11 B A1n B A B Am1 B Amn B Se A é uma matriz m x n e B é uma matriz p x q então AB é uma matriz mp x nq A e B podem ser matrizes esparsas Exemplos A1234 kronAA AA sparseAsparseA A11i kronAA 301 Name lexsort ordenação lexicográfica de linhas de uma matriz N klexsortM sel unique Parâmetros M matriz de reais N matriz de reais k vetor coluna de inteiros Descrição A função lexsort está obsoleta gora Ela pode ser substituída pelas funções gsort e unique NlexsortM ordena as linhas como um grupo da matriz M em ordem ascendente Se requeri do o argumento de saída k contém a ordem NklexsortM retorna k tal que N é igual a Mk NlexsortMsel unique produz o mesmo resultado que a seguinte seqüência de instruções NklexsortMsel unique NMk O flag indicador unique deve ser fornecido caso desejese reter apenas linhas únicas no resulta do Perceba que lexsortMselunique retém apenas linhas tais que Msel são únicas Exemplos Mround2rand203 lexsortM lexsortMunique NklexsortM1 3unique Ver Também gsort unique 302 Name linspace vetor linearmente espaçado vlinspacex1x2 n Parâmetros x1x2 escalares reais ou complexos n inteiro número de valores O valor padrão é 100 v vetor linha de reais ou complexos Descrição Vetor linearmente espaçado linspacex1 x2 era um vetor linha de n valor padrão 100 pontos linearmente espaçados de modo igual entre x1 e x2 Se x1 ou x2 são complexos então linspacex1x2 retorna um vetorlinha de n complexos cujas partes reais e respectivamente as imaginárias dos n complexos são linearmente espaçadas de modo igual entre a partes reais e re spectivamente as imaginárias de x1 e x2 Exemplos linspace1210 linspace1i22i10 Ver Também logspace 303 Name log logaritmo natural ylogx Parâmetros x vetor ou matriz de constantes Descrição logx é o logaritmo natural elemento a elemento yijlogxij Para logaritmo da matriz matriz logaritmo veja logm Exemplos explog1i1i Ver Também exp logm log10 ieee 304 Name log10 logaritmo na base 10 ylog10x Parâmetros x vetor ou matriz Descrição Logartimo decimal Se x é um vetor log10xlog10x1log10xn Exemplos 10log101i1i Ver Também log logm hat ieee 305 Name log1p computa com precisão o logaritmo natural de seu argumento acrescido de uma unidade ylog1px Parâmetros x escalar real ou vetor ou matriz de reais y escalar real ou vetor ou matriz de reais Descrição logp1x é a função log1x elemento a elemento yijlog1 xij Esta função definida para x 1 deve ser usada se quisermos computar log1x com precisão para x 1 significa muito menor Exemplos formate24 log1001 log1p0001 log1 1e7 log1p1e7 log1 1e20 log1p1e20 formatv retoma o formato padrão Ver Também log Autor BP 306 Name log2 logaritmo na base 2 ylog2x Parâmetros x vetor ou matriz Descrição Logaritmo na base 2 Se x é um vetor log2xlog2x1log2xn Exemplos 2log21i1i Ver Também log hat ieee log10 frexp 307 Name logm logaritmo de matriz quadrada matriz logaritmo ylogmx Parâmetros x matriz quadrada Descrição logmx é o logaritmo da matriz x matriz logaritmo de x O resultado é complexo se x não é positiva ou positiva definida Se x é uma matriz simétrica o cálculo é feito pela forma de Schur Em caso contrário x é assumida como sendo diagonalizável Temse expmlogmxx Exemplos A1234 logmA expmlogmA A1AA logmA1 expmlogmA1 A111i expmlogmA1 Ver Também expm log 308 Name logspace vetor espaçado logaritmicamente logspaced1d2 n Parâmetros d1d2 escalar real ou complexo significado especial para pi n inteiro número de valores O valor padrão é 50 Descrição Retorna um vetor linha de n pontos espaçados logaritmicamente de maneira igual entre 10d1 e 10d2 Se d2pi então os pontos estão entre 10d1 e pi Exemplos logspace1210 Ver Também linspace 309 Name lstsize números de entradas de uma lista tlist ou mlist nlstsizex Parâmetros l uma lista tlist ou mlist n um inteiro número de entradas Descrição lstsizex retorna o número de entradas de uma lista tlist ou mlist Esta função é mais eficiente que a função size e opera de modo semelhante para todos os tipos de listas enquanto a função size fica sobrecarregada para mlists Exemplos lstsizelist1aqsdf xssrand324 nynusizex lstsizex Ver Também length size list tlist mlist 310 Name max máximo m kmaxA m kmaxAc m kmaxAr m kmaxAm m kmaxA1A2An m kmaxlistA1A2An Parâmetros A vetor ou matriz de reais A1An um conjunto de vetores ou matrizes todos de tamanhos iguais ou de escalares Descrição Para A um vetor ou matriz de reais maxA é o maior elemento de A mkmaxA fornece ainda o índice do máximo Um segundo argumento do tipo string r ou c pode ser usado r é usado para obter um vetorlinha m tal que mj contém o méximo da j ésima coluna de A Aj kj fornece o índice de linha que contém o máximo para a coluna j c é usado para a operação dual de linhas de A m é usado para compatibilidade com Matlab mmaxA1A2An onde todos os Aj são matrizes de mesmo tamanho retorna um vetor ou matriz m de tamanho sizemsizeA1 tal que mi max Aji j1n mkmaxA1A2An fornece ainda o vetor ou matriz k Fixado i ki é o número do primeiro Aji a alcançar o máximo mkmaxlistA1An é uma outra sintaxe para mkmaxA1A2An Exemplos mnmax131 mnmax311131113 mnmax3211 mnmaxlist311131113 mnmaxlist131 Ver Também gsort find mini 311 Name maxi máximo m kmaxiA m kmaxiAc m kmaxiAr m kmaxiAm m kmaxiA1A2An m kmaxilistA1A2An Parâmetros A vetor ou matriz de reais A1An um conjunto de vetores ou matrizes todos de tamanhos iguais ou de escalares Descrição Para A um vetor ou matriz de reais maxiA é o maior elemento de A mkmaxiA fornece ainda o índice do máximo Um segundo argumento do tipo string r ou c pode ser usado r é usado para obter um vetorlinha m tal que mj contém o méximo da j ésima coluna de A Aj kj fornece o índice de linha que contém o máximo para a coluna j c é usado para a operação dual de linhas de A m é usado para compatibilidade com Matlab mmaxiA1A2An onde todos os Aj são matrizes de mesmo tamanho retorna um vetor ou matriz m de tamanho sizemsizeA1 tal que mi maxi Aji j1n mkmaxiA1A2An fornece ainda o vetor ou matriz k Fixado i ki é o número do primeiro Aji a alcançar o máximo mkmaxilistA1An é uma outra sintaxe para mkmaxiA1A2An Exemplos mnmaxi131 mnmaxi311131113 mnmaxi3211 mnmaxilist311131113 mnmaxilist131 Ver Também gsort find mini 312 Name meshgrid cria matrizes ou arrays 3D X Y meshgridx X Y meshgridxy X Y Z meshgridxyz Parâmetros x y z vetores X Y Z matrizes no caso de dois argumentos de entrada arrays 3D no caso de 3 argumentos de entrada Descrição Exemplos x 1011 y 1011 XY meshgridxy for i1sizeX1 for j1sizeX2 Zij sinc2piXijYij end end surfXYZ Ver Também ndgrid Autor Farid Belahcene 313 Name min mínimo m kminA m kminAc m kminAr m kminAm m kminA1A2An m kminlistA1A2An Parâmetros A vetor ou matriz de reais A1An um conjunto de vetores ou matrizes todos de tamanhos iguais ou de escalares Descrição Para A um vetor ou matriz de reais minA é o menor elemento de A mkminA fornece ainda o índice do mínimo Um segundo argumento do tipo string r ou c pode ser usado r é usado para obter um vetor linha m tal que mj contém o mínimo da j ésima coluna de A Aj kj fornece o índice de linha que contém o mínimo para a coluna j c é usado para a operação dual de linhas de A m é usado para compatibilidade com Matlab mminA1A2An onde todos os Aj são matrizes de mesmo tamanho retorna um vetor ou matriz m de tamanho sizemsizeA1 tal que mi min Aji j1n mkminA1A2An fornece ainda o vetor ou matriz k Fixado um i ki é o número do primeiro Aji a alcançar o mínimo mkminlistA1An é uma outra sintaxe para mkminA1A2An Exemplos mnmin131 mnmin311131113 mnmin3211 mnminlist311131113 mnminlist131 Ver Também gsort find mini 314 Name mini mínimo m kminiA m kminiAc m kminiAr m kminiAm m kminiA1A2An m kminilistA1A2An Parâmetros A vetor ou matriz de reais A1An um conjunto de vetores ou matrizes todos de tamanhos iguais ou de escalares Descrição Para A um vetor ou matriz de reais miniA é o menor elemento de A mkminiA fornece ainda o índice do mínimo Um segundo argumento do tipo string r ou c pode ser usado r é usado para obter um vetor linha m tal que mj contém o mínimo da j ésima coluna de A Aj kj fornece o índice de linha que contém o mínimo para a coluna j c é usado para a operação dual de linhas de A m é usado para compatibilidade com Matlab mminiA1A2An onde todos os Aj são matrizes de mesmo tamanho retorna um vetor ou matriz m de tamanho sizemsizeA1 tal que mi mini Aji j1n mkminiA1A2An fornece ainda o vetor ou matriz k Fixado um i ki é o número do primeiro Aji a alcançar o mínimo mkminilistA1An é uma outra sintaxe para mkminiA1A2An Exemplos mnmini131 mnmini311131113 mnmini3211 mnminilist311131113 mnminilist131 Ver Também gsort find min 315 Name minus operador de subtração mudança de sinal XY Y Parâmetros X escalar vetor ou matriz de números polinômios ou razões de polinômios Também pode ser uma lista syslin Y escalar vetor ou matriz de números polinômios ou razões de polinômios Também pode ser uma lista syslin Descrição Subtração Para operandos numéricos é a operação de subtração em seu sentido usual Se um dos operandos é uma matriz e o outro um escalar a operção é realizada elemento a elemento Se Y X é retornado Se X Y é retornado A subtração também pode ser definida para outros tipos de dados através de operações softcoded Exemplos 121 2 s2 1s2 catenate Ver Também addf mtlbmode 316 Name modulo Resto aritmético simétrico da divisão de n por m pmodulo Resto aritmético positivo da divisão de n por m imodulonm ipmodulonm Parâmetros nm inteiros ou vetores ou matrizes de inteiros de ordens iguais Descrição modulo computa i n modulo m ie resto da divisão de m n e m inteiros i n m int n m Aqui a resposta pode ser negativa se n ou m são negativos pmodulo computa i n m floor n m a resposta é positiva ou zero Exemplos n121015m2235 modulonm modulo39 pmodulo39 317 Name ndgrid Arrays para avaliação de função multidimensional em grid X Y ndgridxy X Y Z ndgridxyz X Y Z T ndgridxyzt X1 X2 Xm ndgridx1x2xm Parâmetros x y z vetores X Y Z matrizes no caso de 2 argumentos de entrada ou hipermatrizes em outro caso Descrição Esta rotina utilitária é útil para criar arrays para a avaliação da função em grids 2 3 n dimensionais Por exemplo em 2d um grid é definido por dois vetores x e y de comprimento nx e ny e se deseja avaliar uma função dita f em todos os pontos do grid isto é em todos os pontos de coordenadas xiyj com i1nx e j1ny Neste caso esta função pode computar as duas matrizes XY de tamanho nx x ny tais que Xij xi para todo i em 1nx Yij yj e j em 1ny e a avaliação pode ser feita com ZfXY sob a condição de que f foi codificada para a avaliação em argumentos de vetor que é feito em geral usando os operadores elemento a elemento and no lugar de e No caso 3d considerando 3 vetores xyz de comprimentos nx ny e nz XYZ são 3 hipermatrizes de tamanho nx x ny x nz tais que Xijk xi Yijk yj para todo ijk in 1nxx1nyx1nz Zijk zk No caso geral de m argumentos de entrada x1 x2 xm os m argumentos de saída X1 X2 Xm são hipermatrizes de tamanho nx1 x nx2 x x nxm e Xji1i2ijim xjij for all i1i2im in 1nx1x1nx2xx1nxm Exemplos criando um grid 2d simples nx 40 ny 40 x linspace11nx y linspace11ny ndgrid 318 XY ndgridxy computando uma função no grid e plotando deffzfxyz128x2 1x2 y2 1y2 deffzfxyzx2 y3 Z fXY xbasc plot3dxyZ flag2 6 4 xselect criando um grid 3d simples nx 10 ny 6 nz 4 x linspace02nx y linspace01ny z linspace005nz XYZ ndgridxyz tente exibir este grid 3d XF YF ZF for k1nz xfyfzf nf3dXkYkZk XF XF xf YF YF yf ZF ZF zf end for j1ny xfyfzf nf3dmatrixXjnxnz matrixYjnxnz matrixZjnxnz XF XF xf YF YF yf ZF ZF zf end xbasc plot3dXFYFZF flag0 6 3 legXYZ xtitleA 3d grid xselect Ver Também kron Autor B Pincon 319 Name ndims número de dimensões de um array Parâmetros A um array n inteiro o número de dimensões do array Descrição nndimsA retorna o número de dimensões de um array A n é maior que ou igual a 2 Exemplos Arand23 ndimsA Arand232 sizeAndimsA H1s1s1 ndimsH Ver Também size Autor S Steer 320 Name nearfloat get previous or next floatingpoint number xnear nearfloatdir x Parâmetros dir string succ ou pred x escalar real vetor ou matriz de reais xnear escalar real vetor ou matriz de reais Descrição Esta função computa elemento a elemento os vizinhos correspondentes dos elementos de x no con junto de pontos flutuantes subjacente ver numberproperties os sucessores se dir succ e e os predecessores se dir pred Exemplos formate22 nearfloatsucc1 1 1 nearfloatpred1 formatv retoma o formato padrão Ver Também numberproperties frexp Autor BP 321 Name nextpow2 próxima potência de 2 mais alta tnextpow2x Parameters x vetor ou matriz de reais p matriz ou vetor de inteiros Descrição Se x é escalar nextpow2x retorna o primeiro p tal que 2p absx Se x é um vetor ou uma matriz nextpow2x se aplica elemento a elemento Exemplos nextpow2127 nextpow2128 nextpow2010 Ver Também frexp 322 Name norm norma de matrizes ynormx flag Parâmetros x vetor ou matriz de reais ou complexos armazenamento cheio ou esparso flag string tipo da norma valor padrão 2 Descrição For matrices normx ou normx2 é o maior valor singular de x maxsvdx normx1 a norma l1 de x a maior soma coluna a coluna maxisumabsxr normxinfnormxinf a norma infinitesimal de x a maior soma linha a linha maxisumabsxc normxfro norma de Frobenius ie sqrtsumdiagxx Para vetores normvp norma lp sumvip1p normv normv2 norma l2 normvinf maxabsvi Exemplos A123 normA1 normAinf A1234 maxsvdAnormA Asparse1 0 0 33 1 normA Ver Também hnorm dhnorm h2norm abs 323 Name not não lógico A Descrição A fornece a negação dos elementos da matriz de valores booleanos A elemento a elemento Exemplos t t f Ver Também and or find 324 Name numberproperties determina parâmetros de ponto flutuante pr numberpropertiesprop Parâmetros prop string pr escalar real ou booleano Descrição Esta função pode ser usada para receber os númerospropriedades característicos do conjunto de pontos flutuantes aqui dentoado por Fbpeminemax geralmente o conjunto de floats de 64 bits prescritos por IEEE 754 Números de F são da forma sign m be e é o expoente e m a mantissa m d1 b1 d2 b2 dp bp di os dígitos estão em 0 b1 e e em emin emax o número é dito normalizado se d1 0 Os seguintes podem ser recebidos prop radix então pr é a raiz b do conjunto F prop digits então pr é o número de dígitos de p prop huge então pr é o maior float positivo de F prop tiny então pr é o menor float normalizado positivo de F prop denorm então pr é um booleano t se números denormalizados são utilizados prop tiniest então se denorm t pr é o número positivo denormalizado mínimo Em outro caso pr tiny prop eps então pr é a máquina epsilon geralmente b1p2 que é o erro máximo relativo entre um real x tal que x está em tiny huge e flx sua aproximação em ponto flutuante em F prop minexp então pr é emin numberproperties 325 prop maxexp então pr é emax Observações Esta função usa uma rotina de LAPACK dlamch para receber os parâmetros máquinas os nomes radix digits huge etc são aqueles recomendados pelo padrão LIA 1 e são diferentes daqueles cor respondentes em LAPACK CUIDADO às vezes você poderá encontrar a seguinte para a máquina epsilon eps b1p mas nesta função nós usamos a definição tradicional ver prop eps acima e então eps b1p2 se o arredondamento normal acontecer e eps b1 p se não acontecer Exemplos b numberpropertiesradix eps numberpropertieseps Ver Também nearfloat frexp Autor Bruno Pincon 326 Name oct2dec conversão de octais para inteiros doct2deco Parâmetros d matriz de inteiros o matriz de strings correspondentes às representações octais Descrição oct2decx retorna a matriz de número correspondentes à representação octal Exemplos oct2dec1 756115 0 23 Ver Também base2dec bin2dec hex2dec dec2bin dec2oct dec2hex 327 Name ones matriz de entradas todas iguais a 1 yonesm1m2 yonesx yones Parâmetros xy matrizes m1 m2 inteiros Descrição Retorna uma matriz cujas entradas são todas iguais a 1 onesm1m2 retorna uma matriz m1m2 cujas entradas são todas 1 onesm1m2mn retorna uma matriz m1m2mn cujas entradas são todas 1 onesx retorna uma matriz cujas entradas são todas 1 com o mesmo tamanho que x onesx também é válido para x uma lista syslin Perceba que ones3 é onesa com a3 ie NÃO é uma matriz 3x3 ones é equivalente a ones11 Exemplos ones3 ones33 ones232 Ver Também eye zeros 328 Name or ou lógico orA orA orAr orA1 orAc orA2 AB Descrição orA fornece o or dos elementos da matriz de valores booleanos A orA é verdadeira t se e só se pelo menos uma entrada de A é t yorAr ou equivalentemente yorA1 é o or linha a linha Retorna em cada en trada do vetor linha y o or das linhas de x o or é realizado no índice de linhas yj orAiji1m yorAc ou equivalentemente yorA2 é o or colunaacoluna Retorna em cada en trada do vetorcoluna y o or das colunas de x o or é realizado no índice de colunas yi orAijj1n AB fornece o or elemento a elemento das matrizes A e B A e B devem ser matrizes de mesmas dimensões ou uma delas deve ser um único booleano Exemplos ort t f t t ff t t t t ff Ver Também and not find 329 Name pen2ea conversão de feixe em matrizes E e A EApen2eaFs Parâmetros Fs feixe de matrizes sEA EA duas matrizes tais que FssEA Descrição Função utilitária Dado o feixe FssEA retorna as matrizes E e A Exemplos E10A12spoly0s EApen2easEA 330 Name perms retorna todas as permutações dos componentes de um vetor ypermsx Parâmetros x um escalar ou um vetor y um escalar ou uma matriz Descrição Dado um vetor x de comprimento n perms retorna todas as permutações dos n componentes de x ie n permutações O tamanho de y é n x n Exemplos x4 7 10 ypermsx x1 5 2 5 ypermsx 331 Name permute permuta as dimensões de um array ypermutexdims Parâmetros dims um escalar ou um vetor de números reais positivos x um escalar um vetor uma matriz ou um multiarray Descrição ypermutexdims Exemplos exemplo 1 x1 2 34 5 6 ypermutex2 1 exemplo 2 xmatrix112232 ypermutex3 1 2 Ver Também pertrans quote cat Autor Farid Belahcene 332 Name pertrans matriz pertransposta YpertransX Parâmetros X matriz de reais ou complexos Y matriz de reais ou complexos Descrição YpertransX retorna a matriz pertransposta de X ie a matriz simétrica a X em relação à segunda diagonal função utilitária Exemplos A1234 pertransA 333 Name primes função dos primos yprimesx Parâmetros x escalar real y vetor Descrição Dado um real x primesx retorna em um vetor y todos os números primos entre 1 e x Se x2 então primesx retorna uma matriz vazia Exemplos x35 yprimesx Ver Também factor 334 Name prod produto yprodx yprodxr ou yprodx1 yprodxc ou yprodx2 yprodxm Parâmetros x matriz ou vetor de reais ou complexos y matriz ou vetor de reais ou complexos Descrição Para um vetor ou uma matriz x yprodx retorna no escalar y o produtório de todas as entradas de x ex prod1n é n yprodxr ou equivalentemente yprodx1 computa os produtórios dos elementos das linhas de x y é o vetor linha y1jprodxj yprodxc ou equivalentemente yprodx2 computa os produtórios dos elementos das colunas de x y é o vetor coluna yi1prodxi yprodxm é o produtório ao longo da primeira dimensão nãosingleton de x para compat ibilidade com o Matlab prod não é implementado para matrizes esparsas Exemplos A120100 prodA prodAc prodAr Ver Também sum cumprod 335 Name rand gerador de números randômico randm1m2 key randx key rand randkey randseed n randinfo Parâmetros mi inteiros key string com valor uniform ou normal x uma matriz Apenas suas dimensões são levadas em conta Descrição Gerador de matriz randômico Sem argumento key as sintaxes abaixo produzem matrizes randômicas com o gerador randômico corrente o padrão é uniform randm1m2 é uma matriz randômica de dimensão m1 por m2 randm1m2mn é uma matriz randômica de dimensão m1 por m2 por mn randa é uma matriz randômica com mesmo tamanho que a randaé de complexos se a é uma matriz de complexos rand sem argumentos fornece um escalar cujo valor muda a cada vez que é referenciado Se presente o argumento key permite especificar uma outra distribuição randômica randuniform o gerador corrente é acertado como gerador randômico uniforme Números aleatórios são dis tribuidos uniformemente e pertencem ao intervalo 01 randnormal o gerador corrente é acertado como gerador de números randômico gaussiano com média 0 e variância 1 strrandinfo retorna o tipo do gerado randômico padrão uniform ou normal É possível reinicializar o seed do gerador randômico randseed retorna o valor corrente do seed rand 336 randseedn define o seed como n o padrão é n0 numa primeira chamada Observação Use a função mais poderosa grand ao invés Exemplos xrand1010uniform randnormal randinfo yrandxnormal xrand222 Ver Também grand ssrand 337 Name rat aproximação racional de pontoflutuante NDratx tol yratx tol Parâmetros x vetor ou matriz de reais n vetor ou matriz de inteiros d vetor ou matriz de inteiros y vetor ou matriz de reais Descrição ND ratxtol retorna duas matrizes de inteiros tais que ND é próxima a x no sentido de que absND X tolabsx As aproximações racionais são geradas truncandose expansões de frações contínuas tol 1e6normX1 é o padrão y ratxtol retorna o quociente ND Exemplos ndratpi ndratpi1d12 ndpi Ver Também int round 338 Name real parte real yrealx Parâmetros x vetor ou matriz de reais ou complexos y matriz de reais Descrição realx é a parte real de x ver i para entrar com números complexos Ver Também imag 339 Name resizematrix cria uma nova matriz com tamanho diferente resMat resizematrixmatnbRownbColtypeOfMat Parâmetros mat matriz de entrada da qual a matriz redimensionada será criada nbRow número de linhas da matriz redimensionada nbCol número de colunas da matriz redimensionada typeOfMat string nome do tipo da matriz redimensionada resMat matriz redimensionada Descrição Cria uma matriz de tamanho nbRow x nbCol e cujos elementos ij são matij se ij está ao alcance da matriz de entrada De outro modo ij são 0 para matrizes de reais ou de inteiros f para matrizes de booleanos e um string vazio para matrizes de strings O tipo da matriz de saída pode ser modificado especificandose o argumento typeOfMat Neste caso esteja certo de que o tipo da matriz de entrada é compatível com este Por enquanto apenas matrizes de reais inteiros booleanos e strings são suportadas Isto significa que typeOfMat deve ser escolhido dentre constant boolean string ou qualquer tipo inteiro int8 int16 Exemplos matriz de números myMat 5 rand 3 4 myMat resizematrix myMat 3 3 reduzindo tamanho da matriz myMatInteger resizematrix myMat 4 4 int32 criando uma matriz de inteiros myMatBoolean resizematrix myMat 2 2 boolean myMatBoolean resizematrix myMatBoolean 3 5 Matriz de strings myMatString ScilabtheOpen SourceScientificSoftwarePackage myMatString resizematrix myMatString 3 1 Ver Também matrix size typeof Autor JeanBaptiste Silvy 340 Name round arredondamento para inteiro mais próximo yroundx Parâmetros x matriz de reais ou complexos y matriz de inteiros ou complexos com partes reais e imaginárias inteiras Descrição roundx arredonda os elementos de x para os inteiros mais próximos Exemplos round19 2523 round1621i22i roundinf xrand1020roundxx Ver Também int floor ceil 341 Name sec computa a secante elemento a elemento do argumento y secx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa a secante elemento a elemento do argumento A secante é uma função periódica definida como 1cos Para dados reais os resultados são reais em inf 1 U 1 inf Exemplos x0 pi3 2pi3 pi4 3pi4 pi6 5pi6 pi secx xlinspacepipi100 plotxsecx Ver Também cos secd Autor Serge Steer INRIA Função Usada Esta função usa a função cos 342 Name secd computa a secante elemento a elemento do argumento em graus y secdx Parâmetros x array de reais y array de reais Descrição as entradas de y são as secantes 1cos das entradas de x dadas em graus Os resultados são reais e estão em inf 1 U 1 inf para entradas iguais a n180 com n inteiro o resultado é exatamente 1 ou 1 para entradas iguais a n90 com n inteiro e ímpar o resultado é infinito ou um erro dependendo do modo ieee Exemplos secd90 secpi2 Ver Também cosd sec Autor Serge Steer INRIA 343 Name sech computa a secante hipertbólica do argumento elemento a elemento y sechx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa a secante hipertbólica do argumento elemento a elemento A secante hiperbólica é definida como 1cosh Para dados reais os resultados são reais em 0 1 Exemplos xlinspace10101000 plotxsechx Ver Também cosh asech Autor Serge Steer INRIA 344 Name setdiff retorna componentes de um vetor que não pertecem a outro vetor vsetdiffab vkasetdiffab Parâmetros a vetor de números reais ou strings b vetor de números reais ou strings v vetor de números reais ou strings com a mesma orientação de a ka vetor linha de inteiros kai é a localização de vi em a Descrição setdiffab retorna um vetor ordenado que retém as entradas de a que não estão em b vkasetdiffab retorna um vetor ordenado que retém as entradas de a que não estão em b e a localização destas entradas em a Exemplos a 2231112422 b 232122312322 setdiffab vksetdiffstringastringb Ver Também unique gsort union 345 Name sign função de sinal Descrição XsignA retorna a matriz feita dos sinais de Aij Para A feita de complexos signA AabsA Exemplos signrand23 sign1i Ver Também abs 346 Name signm função do sinal da matriz Descrição Para matrizes quadradas e Hemitianas XsignmA é a função do sinal da matriz Exemplos Arand44BAAXsignmBspecBspecX Ver Também sign 347 Name sin função seno tsinx Parâmetros x vetor ou matriz de reais ou complexos Descrição Para um vetor ou matriz sinx é o seno de seus elementos Para o seno da matriz matriz seno use a função sinmX Exemplos asinsin10i Ver Também sinm 348 Name sinc função sinc seno cardinal tsincx Parâmetros x vetor ou matriz de reais ou complexos t vetor ou matriz de reais ou complexos Descrição Se x é um vetor ou uma matriz tsincx é o vetor ou matriz tal que tisinxixi if xi0 e ti1 se xi0 Exemplos xlinspace10103000 plot2dxsincx Ver Também sin cos 349 Name sind função seno argumento em graus tsindx Parâmetros x array de reais ou complexos t array de reais ou complexos com as mesmas dimensões que x Descrição Para um vetor ou uma matriz x sindx é o seno de seus elementos que se supõe estar em graus Os resultados estão em 1 1 Para inteiros n sindn180 é exatamente zero Exemplos x030 45 60 90 360 sindx Ver Também sin Autor Serge Steer INRIA 350 Name sinh seno hiperbólico tsinhx Parâmetros xt vetores ou matrizes de reais ou complexos Descrição Os elementos do vetor t são os senos hiperbólicos dos elementos do vetor x Exemplos asinhsinh01i Ver Também asinh 351 Name sinhm seno hiperbólico da matriz matriz seno hiperbólico tsinhmx Parâmetros xt matriz quadrada de reais ou complexos Descrição sinhmx é o seno hiperbólico da matriz x matriz seno hiperbólico de x texpmxexpm x2 Exemplos A1223 asinhmsinhmA A11isinhmAexpmAexpmA2 Caso para complexos Ver Também sinh 352 Name sinm matriz seno tsinmx Parâmetros x matriz quadrada de reais ou complexos Descrição sinmx é o seno da matriz x matriz seno de x Exemplos A1224 sinmA05iexpmiAexpmiA Ver Também sin asinm 353 Name size tamanho de objetos ysizex sel nrncsizex Parâmetros x matrix incluindo matriz de transferência lista ou sistema linear syslin y 1x2 vetor de inteiros ou número inteiro sel um escalar ou um string nrnc dois inteiros Descrição Aplicado a uma matriz de constantes de polinômios de strings de booleanos ou de razões de polinômios x com apenas um argumento LHS Left Hand Side ou do lado esquerdo size retorna um vetor 1x2 número de linhas número de colunas Chamado com LHS 2 retorna nrnc número de linhas número de colunas sel pode ser usado para especficar a dimensão a ser recebida 1 ou r para receber o número de linhas 2 ou c para receber o número de colunas para receber o produto de linhas e números de colunas Aplicado a uma lista retorna o número de elementos Neste caso apenas a sintaxe ysizex pode ser usada Aplicado a um sistema linear ysizex retorna em y o vetor linha número de saídas número de entradas ie a dimensão da matriz de transferência correspondente A sintaxe nrncsizex também é válida com nrncy1y2 Se x é um sistema lin ear em forma de estadoespaço então nrncnxsizex retorna ainda a dimensão nx da matriz A de x Aplicado a uma hipermatriz ysizex retorna o vetor de dimensões da hipermatriz n1n2nnsizex retorna as dimensões da hipermatriz nisizexi re torna a iésima dimensão e sizex retorna o produto de dimensões Exemplos size 354 nmsizerand32 nmsizeabcd xssrand324nynusizex nynusizess2tfx nynunxsizex Ver Também length syslin 355 Name solve Solucionador simbólico de sistemas lineares xsolveAb Parâmetros Abx matrizes respectivamente vetores de strings Descrição Resolve Ax b quando A é uma matriz triangular superior feita de strings Exemplos A1a02 Triangular superior bxy wsolveAb a1x2y5 evstrw inv110225 Ver Também trianfml 356 Name sort ordenamento decrescente DEPRECATED see gsort s ksortv s ksortvr s ksortvc Parâmetros v vetor esparso vetor ou matriz de reais complexos ou strings s vetor esparso vetor ou matriz de reais complexos ou strings k vetor ou matriz de inteiros Descrição sort will be removed in Scilab 53 see gsort A função sort está obsoleta Ela pode ser substituída por gsort ssortv põe v em ordem decrescente Se v é uma matriz a ordenação é feita coluna a col una v sendo visto como o vetor empilhado v Se v é um string a ordenação é crescente sksortv retorna ainda os índices de entradas de s em v ie vk é o vetor s ssortvr põe as linhas de v em ordem decrescente ie cada coluna de s é obtida de cada coluna de v por reordenação decrescente sksortvr retorna ainda em cada coluna de k os índices tais que vkiisi para cada índice de coluna i ssortvc põe as colunas de v em ordem decrescente ie cada linha de s é obtida de cada linha de v por reordenação decrescente sksortvc retorna ainda em cada linha de k os índices tais que vikisi para cada índice de linha i Matrizes ou vetores de complexos são ordenados de acordo com suas magnitudes Ordenação por colunaslinhas não é implementada para matrizes complexas ysortA é válido quando A é um vetor esparso Ordenação de linhascolunas não é implementado para matrizes esparsas Limitação se v inclui elementos nan a matriz não será ordenada Por favor use gsort neste caso Exemplos spsortrand110 p é uma permutação aleatória de 110 A125342 AsortedqsortAAqAsorted v110 sortv sortv sortvr Não faz nada para vetoreslinha sortvc Ver Também find gsort 358 Name sp2adj converte uma matriz esparsa para forma de adjacência Parâmetros A matriz esparsa de reais ou complexos nz entradas nãonulas xadj vetor de inteiros de comprimento n1 adjncy vetor de inteiros de comprimento nz contendo os índices de linha para os elementos correspon dentes em anz anz vetor coluna de comprimento nz contendo os elementos nãonulos de A Descrição sp2adj converte uma matriz esparsa para usa forma de adjacência função utilitária A matriz esparsa n x m xadj adjncy anz representação em adjacência de A ie xadjj1xadjj número de entradas nãonulas na linha j adjncy índice de coluna das entradas nãonulas nas linha 1 linha 2 linha n anz valores de entradas nãonulas nas linha 1 linha 2 linha n xadj é um vetor coluna de tamanho n1 e adjncy é um vetor coluna de inteiros de tamanho nznnzA anz é um vetor de reais de tamanho nznnzA Exemplos A sprand1005005 xadjadjncyanz sp2adjA nmsizeA p adj2spxadjadjncyanznm Ap Ver Também adj2sp sparse spcompack spget 359 Name speye matriz identidade esparsa Ispspeyenrowsncols IspspeyeA Parâmetros nrows inteiro número de linhas ncols inteiro número de colunas A matriz esparsa sp matriz identidade esparsa Descrição Ispspeyenrowsncols retorna uma matriz identidade esparsa Isp com nrows linhas e ncols colunas matrizes identidades nãoquadradas têm um número máximo de algarismos 1 na diagonal principal IspspeyeA retorna uma matriz identidade esparsa com as mesmas dimensões de A SemnsizeA speyemn e speyeA são equivalentes Em particular speye3 não é equivalente a speye33 Exemplos eye33fullspeye33 Ver Também sparse full eye spzeros spones 360 Name spones matriz esparsa spsponesA Parâmetros A matriz esparsa sp matriz esparsa Descrição spsponesA gera uma matriz com a mesma estrutura de espargimento de A mas com 1 em posições nãonulas Exemplos Asprand101201 spsponesA B A0 bool2sB Ver Também sparse full eye speye spzeros 361 Name sprand matriz esparsa randômica spsprandnrowsncolsfill typ Parâmetros nrows inteiro número de linhas ncols inteiro número de colunas fill coeficiente de preenchimento densidade typ string uniform padrão ou normal sp matriz esparsa Descrição spsprandnrowsncolsfill retorna uma matriz esparsa sp com nrows linhas e ncols colunas e aproximadamente fillnrowsncols entradas nãonulas Se typuniform valores uniformemente distribuídos em 01 são gerados Se typnormal valores normalmente distribuídos são gerados média0 e desvio padrão1 Exemplos Wsprand10010000001 Ver Também sparse full rand speye 362 Name spzeros matriz nula esparsa spspzerosnrowsncols spspzerosA Parâmetros nrows inteiro número de linhas ncols inteiro número de colunas A matriz esparsa sp matriz nula esparsa Descrição spspzerosnrowsncols retorna uma matriz nula esparsa sp com nrows linhas e ncols colunas Equivalente a sparsenrowncols spspzerosA retorna uma matriz nula esparsa com as mesmas dimensões que A Se mnsizeA spzerosmn e spzerosA são equivalentes Em particular spze ros3 não é equivalente a spzeros33 Exemplos sumspzeros10001000 Ver Também sparse full eye speye spones 363 Name sqrt raiz quadrada ysqrtx Parâmetros x escalar real ou complexo ou vetor de reais ou complexos Descrição sqrtx é o vetor de raízes quadradas dos elementos de x O resultado é complexo se x é negativo Exemplos sqrt24 sqrt1 Ver Também hat sqrtm 364 Name sqrtm raiz quadrada da matriz matriz raiz quadrada ysqrtmx Parâmetros x matriz quadrada de reais ou complexos Descrição ysqrtx é a raiz quadrada da matriz x matriz raiz quadrada de x xy2 O resultado pode ser inacurado se x não é simétrica Exemplos x0 12 4 wsqrtmx normwwx x12i wsqrtmxnormwwx1 Ver Também expm sqroot 365 Name squarewave gera uma onda quadrada de período 2pi xsquarewavet percent Parâmetros t vetor de reais discretização do tempo x vetor de reais o valor da onda em cada ponto do tempo no conjunto 11 percent escalar real positivo a porcentagem do período no qual o sinal é positivo O valor padrão é 50 Descrição squarewavet gera o vetor dos valores da onda quadrada de período 2pi em cada data dada no vetor t squarewavet gera uma onda quadrada tal que é a porcentagem do período no qual o sinal é positivo Exemplos t0015pi plot2d1onnt2sint15squarewavetsquarewavet10 Ver Também sin cos 366 Name ssrand gerador de sistema randômico slssrandnoutninnstate slUssrandnoutninnstateflag Parâmetros nout inteiro número de saídas nin inteiro número de entradas nstate inteiro dimensão de espaço de estados flag lista feita de um string ou vários inteiros sl lista lista syslin U matriz quadrada nãosingular nstate x nstate Descrição slssrandnoutninnstate retorna um sistema em espaço de estado randômico estrita mente próprio D0 de tamanho noutnint representado por uma lista syslin e com nstate variáveis de estado slUssrandnoutninnstateflag retorna um sistema linear teste com dadas pro priedades especificadas por flag flag pode ser um dos seguintes flaglistcodimcontsubs flaglistuodimunobssubs flaglistncnodimcnodimncnodimcodimnco flagliststdimcontsubsdimstabsubsdimstab0 flaglistdtdiminstunobdiminstb0dimunobs flaglistonnrngng0nvrk flaglistuinwnwunwuinwuisrk A completa descrição dos Sys é dada no código da função ssrand em SCIDIR macrosutil Por exemplo com flaglistcodimcontsubs um sistema não controlável é retornado e dimcontsubs é a dimensão do subespaço controlável de Sys Os strings couoncnostdtonui significam controlável inobservável nãocontrolávelnãoobservável estabilizável detectável anuladordesaída saídadesconhecida Exemplos flagliststdimcontsubsdimstabsubsdimstab0 ssrand 367 dimcontsubsdimstabsubsdimstab0 par AB Usimilar a 0s 0 A 00i B0 000u 0 A11B1 controlável smatriz estável imatriz neutra umatriz instável SlUssrand238listst255 wss2ssSlinvU desfaz a mudança aleatória de base forma como acima nncuslstilitySlnnc Ver Também syslin 368 Name sub2ind converte matriz de valores subescrtos para índice linear I sub2inddimsi1i2 J sub2inddimsMi Parâmetros dims vetor as dimensões da matriz i1i2 os arrays de valores subescritos de mesma forma que a matriz I Mi matriz cujas colunas contém os valores subescritos I o array de índice linear Descrição sub2ind é usado para determinar o índice único equivalente que corresponde ao dado conjunto de valores subescritos I sub2inddimsi1i2 retorna o índice linear equivalente aos subescritos das linha coluna nos arrays i1 i2 para uma matriz de tamanho dims Neste caso i1 i2 devem ter o mesmo formato e o resultado I tem a mesma forma da matriz I sub2inddimsMi retorna o índice linear equivalente aos subescritos nas colunas da matriz Mi para uma matriz com tamanho dims Neste caso I é um vetor coluna Exemplos i1 2 1 1 2 1 1 j1 2 3 1 2 3 3 k1 2 1 2 1 2 1 sub2ind232ijk sub2ind232ijk Ver Também ind2sub extraction insertion Autor Serge Steer INRIA 369 Name sum soma soma linha soma coluna de entradas de um vetor ou matriz ysumx ysumxr ou ysumx1 ysumxc ou ysumx2 ysumxm Parâmetros x vetor ou matriz de reais complexos esparsoa ou de polinômios y escalar ou vetor Descrição Para um vetor ou matriz x ysumx retorna no escalar y a soma de todas as entradas de x ysumxr ou equivalentemente ysumx1 é a soma linha a linha yj sumxj y é um vetor linha ysumxc ou equivalentemente ysumx2 é a soma coluna a coluna Retorna em cada entrada do vetor coluna y a soma yi sumxi ysumxm é a soma ao longo da primeira dimensão nãosingleton de x para compatibilidade com Matlab Exemplos A1234 traceAsumdiagA sumAcAones21 sumAi AsparseAsumAcAones21 spoly0s Msiss21 sumMsumM2 Ver Também cumsum prod 370 Name sysconv conversão de sistema s1s2sysconvs1s2 Parâmetros s1s2 lista sistemas syslin lineares Descrição Converte s1 e s2 para representação comum a fim de que operações de interconexão de sistemas possam ser aplicadas Função utilitária para peritos A regra de conversão é dada na seguinte tabela c sistema de tempo contínuo d sistema de tempo discreto n sistema amostrado com período de amostragem n sistema com domínio de tempo indefinido Para sistemas mistos s1 e s2 são postos em representação de estadoespaço s1s2 c d n2 c nada incompatível c2es1n2 cs2 d incompatível nada es1n2 ds2 n1 c2es2n1 es2n1 n1n2 incomp es2n1 n1n2 nada cs1 ds1 es1n2 nada Com o seguinte significado n1n2 período de amostragem c2esn o sistema de tempo contínuo s é transformado em um sistema amostrado com período de amostragem n cs conversão para tempo contínuo domínio de tempo é c ds conversão para tempo discreto domínio de tempo é d esn conversão para sistema amostrado com período n sysconv 371 Exemplos s1ssrand112 s2ss2tfs1 s1s2sysconvs1s2 Ver Também syslin ss2tf tf2ss 372 Name sysdiag conexão de sistemas diagonais em blocos rsysdiaga1a2an Descrição Retorna um sistema diagonal em blocos feito de subsistemas postos na diagonal principal ai subsistemas ie ganhos ou sistema linear em forma de espaço de estados ou de transferência Usado em particular para interconexões de sistemas Observação No máximo 17 argumentos Exemplos spoly0s sysdiagrand221s11s11s2s3 sysdiagtf2ss1s1s11s11s2s3 Ver Também brackets insertion feedback 373 Name syslin definição de sistemas lineares slsyslindomABC D x0 slsyslindomND slsyslindomH Parâmetros dom string c d ou ou um escalar ABCD matrizes em representação de espaço de estados D opcional com valor padrão matriz nula para sistemas impróprios D é uma matriz de polinômios x0 vetor estado inicial valor padrão é 0 N D matrizes de polinômios H matriz de razões de polinômios ou representação de espaço de estados linear sl tlist lista syslin representando o sistema linear Descrição syslin define um sistema linear como uma lista e verifica a consistência dos dados dom especifica o domínio de tempo do sistema e pode ter um dos seguintes valores domc para um sistema de tempo contínuo domd para um sistema de tempo discreto n para um sistema amostrado com período de amostragem n em segundos dom se o domínio de tempo é indefinido Representação em espaço de estados slsyslindomABC D x0 Representa o sistema s x Ax Bu y Cx Du x0 x0 A saída de syslin é uma lista da seguinte forma sltlistlssABCDX0dtABCDx0dom Note que D pode ser uma matriz de polinômios sistemas impróprios Representação de matriz de transferência syslin 374 slsyslindomND slsyslindomH A saída de syslin é uma lista da seguinte forma sltlistrnumdendtNDdom ou sltlistrnumdendtH2H3dom Sistemas lineares definidos como syslin podem ser manipulados como matrizes usuais concatenação extração transposição multiplicação etc ambos em estadoespaço ou representação de transferência A maior parte das funções de controle de estadoespaço recebem uma lista syslin como entrada ao invés de quatro matrizes definindo o sistema Exemplos A0100B11C11 S1syslincABC Definição de sistema linear S1A Exibição da matriz A S1X0 S1dt Exibição de X0 e domínio de tempo spoly0s Ds S2syslincABCD H112ss2 S1bissyslincH1 H212ss3s2 S2bissyslincH2 S1S2 S1S2 ss2tfS1S1bis S1bisS2bis S1S2bis sizeS1 Ver Também tlist lsslist rlist ssrand ss2tf tf2ss dscr abcd 375 Name tan tangente ttanx Parâmetros x vetor ou matriz t vetor ou matriz Descrição Os elementos de t são as tangentes dos elementos de x Exemplos x1i1i tanx sinxcosx Ver Também atan tanm 376 Name tand tangente com o argumento em graus ttandx Parâmetros x vetor ou matriz de reais t vetor ou matriz de reais Descrição Os elementos de t são as tangentes dos elementos de x Exemplos modieeeieee2 x030 45 60 90 360 tandx ieeemod Ver Também atand tan 377 Name tanh tangente hiperbólica ttanhx Descrição Os elementos de t são as tangentes hiperbólicas dos elementos de x Exemplos x1i1i tanhx sinhxcoshx Ver Também atanh tan tanhm 378 Name tanhm tangente hiperbólica da matriz matriz tangente hiperbólica ttanhmx Parâmetros xt matrizes quadradas de reais ou complexos Descrição tanhm é a tangente hiperbólica da matriz x matriz tangente hiperbólica de x Exemplos A1234 tanhmA Ver Também tan tanm expm sinm cosm atanhm 379 Name tanm tangente da matriz matriz tangente ttanmx Parâmetros x matriz quadrada de reais ou complexos t matriz quadrada Descrição tanmx é a tangente da matriz x matriz tangente de x Exemplos A1234 tanmA Ver Também tan expm sinm atanm 380 Name toeplitz matriz de Toeplitz Atoeplitzc r Parâmetros acr matrizes de constantes polinômios ou strings Descrição Retorna a matriz de Toeplitz cuja primeira linha é r e a primeira coluna é c c1 deve ser igual a r1 toeplitzc retorna a matriz de Toeplitz simétrica Exemplos Atoeplitz15 Ttoeplitz15127T11 3 5 72 1 3 53 2 1 34 3 2 15 4 3 2 TT1 spoly0s ttoeplitzss1s21s t1s1sss1s1ss1sssss1ss1s1sss1ss tt1 ttoeplitz1234 t11234212332124321 Ver Também matrix 381 Name trfmod exibição de zeros e pólos hmtrfmodh job Descrição Visualiza a estrutura pólozero de uma função de transferência SISO h jobp visualização de polinômios padrão jobf visualização de freqüências naturais e amortecimento Simplificação interativa de h trfmod abre uma janela de diálogo Ver Também poly simp 382 Name trianfml triangularização simbólica f sexptrianfmlf sexp Descrição Triangularização simbólica da matriz f a triangularização é executada por transformações ele mentares de linha sexp é um conjunto de expressões comuns aramazenadas pelo algoritmo Exemplos A12ab WtrianfmlAstringeye22 UW34 a5b6 AevstrA UevstrU UA evstrW12 Ver Também addf mulf solve trisolve 383 Name tril parte triangular inferior de uma matriz trilx k Parâmetros x matriz de reais complexos polinômios ou razões de polinômios k inteiro valor padrão 0 Descrição Parte triangular inferior de uma matriz trilxk é formada pelas entradas abaixo da késima diagonal k0 acima da diagonal superior e k0 diagonais abaixo da diagonal principal Exemplos spoly0s trilsss1 tril1s1s1s1 Ver Também triu ones eye diag 384 Name trisolve solucionador simbólico de sistemas lineares x sexp trisolveAb sexp Parâmetros Ab matrizes de strings Descrição Resolve simbolicamente Ax b A sendo assumida como triangular superior sexp é um vetor de subexpressões comuns em A b x Exemplos Axy0zb01 wtrisolveAb x5y2z4 evstrw invevstrAevstrb Ver Também trianfml solve Autores FD SS 385 Name triu triângulo superior da matriz Descrição Triângulo superior da matriz Ver tril Exemplos spoly0s triusss1 triu1s1s1s1 Ver Também tril ones eye diag 386 Name typeof tipo do objeto ttypeofobject Parâmetros object objeto Scilab t string Descrição ttypeofobject retorna um dos seguintes strings constant se o objeto é uma matriz constante de reais ou complexos polynomial se o objeto é uma matriz de polinômios function se o objeto é uma função código Scilab handle se o objeto é um manipulador alça string se o objeto é uma matriz de strings boolean se o objeto é uma matriz de valores booleanos list se o objeto é uma lista rational se o objeto é a é uma martriz de razões de polinômios matriz de transferência statespace se o objeto é um modelo de espaço de estados ver syslin sparse se o objeto é uma matriz de reais esparsa boolean sparse se o objeto é uma matriz de valores booleanos esparsa hypermat se o objeto é uma hipermatriz array Ndimensional N 3 st se o objeto é um array de estrutura ce se o objeto é um array de células typeof 387 the first string in the first list entry se o objeto é um tlist ou mlist fptr se o objeto é intrínseco ao Scilab código C ou Fortran pointer se o objeto é um ponteiro ver lufact size implicit se o objeto é um polinômio de tamanho implícito para indexação Exemplos typeof1 typeofpoly0x typeof1poly0x typeoft wsprand1001000001 typeofw typeofww deffyfxy2x typeoff LtlistVab18Scilab typeofL Ver Também type strings syslin poly 388 Name union extrai componentes da união de um vetor v ka kb unionab v ka kb unionaborient Parâmetros a vetor ou matriz de números ou strings b vetor ou matriz de números ou strings orient flag com valores possíveis 1 ou r 2 ou c v vetor linha ou matriz de números ou strings ka vetor linha de inteiros kb vetor linha de inteiros Descrição unionab retorna um vetor linha ordenado que retém as entradas únicas de ab unionabr ou unionab1retorna a matriz formada pela união das linhas únicas de a e b em ordem lexicográfica ascendente Neste caso as matrizes a e b devem ter o mesmo número de colunas unionabc ou unionab2retorna a matriz formada pela união das colunas únicas de a e b em ordem lexicográfica ascendente Neste caso as matrizes a e b devem ter o mesmo número de colunas vkakbunionab também retorna vetores de índices ka e kb tais que v é uma combinação ordenada das entradas aka e bkb Exemplos Around5rand101 Bround5rand71 unionAB NkakbunionAB unionastringAbstringB Ver Também unique gsort 389 Name unique extrai componentes únicos de um vetor ou de matrizes N kuniqueM N kuniqueM orient Parâmetros M vetor ou matriz de números ou strings orient flag com valores possíveis 1 ou r 2 ou c N vetor ou matriz de números ou strings k vetor de inteiros Descrição uniqueM retorna um vetor que retém as entradas únicas de M em ordem ascendente uniqueMr ou uniqueM1retorna as linhas únicas de M em ordem lexicográfica ascen dente uniqueMc ou uniqueM2retorna as linhas únicas de M em ordem lexicográfica ascen dente Se requerido o argumento de saída k contém a posição das primeiras entradas únicas encontradas Exemplos Mround2rand201 uniqueM NkuniqueM uniquestringM NkuniquestringM A 0011 0111 2011 0222 2011 0011 TxstringA linhas únicas mkuniqueAr uniqueTr unique 390 colunas únicas mkuniqueTc uniqueAc Ver Também union intersect gsort lexsort 391 Name vectorfind acha em uma matriz linhas ou colunas que coincidem com um vetor ind vectorfindmvjob Parâmetros m uma matriz de qualquer tipo v um vetor de qualquer tipo job um string indicador com valores possíveis r para procura de linhas coincidentes ou c para procura de colunas coincidentes ind vetorlinha contendo os índices das linhas ou colunas coincidentes Descrição Acha em uma matriz as linhas ou colunas que coincidem com um dado vetor Exemplos alr122 121 112 111 121 ind vectorfindalr121r ind vectorfindstringalrstring121r Ver Também find gsort Autores R Nikoukhah S Steer INRIA 392 Name zeros matriz feita de zeros yzeros yzerosx yzerosm1m2 Parâmetros xy matrizes m1 m2 inteiros Descrição Cria uma matriz de zeros é o mesmo que 0ones zerosm1m2 para uma matriz m1m2 zerosm1m2mn cria uma matriz m1m2mn preenhida com zeros zerosA para uma matriz de mesmo tamanho que A zeros3 é zerosa com a3 é uma matriz 3x3 zeros retorna um único zero Se x é uma lista syslin sistema linear em forma de espaço de estados ou transferência zerosx também é válido e retorna uma matriz nula Exemplos zeros3 zeros33 zeros232 Ver Também eye ones spzeros 393 Name logical and operator AB Description AB gives the elementwise logical and of the booleans matrices A and B A and B must be matrices with the same dimensions or one from them must be a single boolean See Also not and or operator 394 Nom csgn Returns the sign of a vector of real of complex values s csgnz Parameters z The vector of values on which we want to compute the sign s If the real part is not equal to zero 1 if the real part of an element if positive 1 if the real part of an element if negative If the real part is equal to zero 1 if the imaginary part of an element if positive 1 if the imaginary part of an element if negative if the element is equal to zero then returns nan Description Returns the sign of a vector of real of complex values Examples A 1 1i 0 1 1i 1i dispcsgnA Authors Y Collette 395 Name isvector check if a variable is a vector tisvectorx Parameters x vector or matrix t a boolean Description isvectorx returns true if x is a vector one of its dimension is different from 1 Examples isvectorones101 isvector1 396 Name logical or operator AB Description AB gives the elementwise logical or of the booleans matrices A and B A and B must be matrices with the same dimensions or one from them must be a single boolean Examples t t f f t t t t f f See Also or and and operator not find Parte IV Funções 398 Nom addprofiling adiciona instruções de profiling análise de performance a uma função addprofilingfunname Parâmetros funname string o nome da função Descrição addprofilingfunname adiciona instruções de profiling a uma função de nome funname Então quando esta função é chamada o número de chamadas e o tempo gasto é armazenado para cada linha da função Exemplos function xfooan x0 for i1n if x10 then xxa else xx1 end end xx21 endfunction addprofilingfoo foo01100 executando a função profilefoo extraindo informação de profile Ver Também profile plotprofile removeprofiling resetprofiling Autor Serge Steer INRIA Funções Utilizadas Esta função utiliza as funções Scilab bytecode e walkbytecode 399 Nom bytecode dada uma função retorna bytecode código de bytes da função em um array Scilab e viceversa x bytecodef f bytecodeX Parâmetros f função Scilab x vetor linha int32 Descrição x bytecodef retorna o bytecode da função f no array Scilab de inteiros x f bytecodex retorna em f a função associada ao bytecode dado no array Scilab de inteiros x AVISO a validade de x não é verificada Observação O bytecode da função Scilab evoluirá drasticamente no futuro então o uso dessa função deve se res tringir à manipulação de instruções de profiling Exemplos function afooasin3endfunction bytecodefoo Ver Também addprofiling bytecodewalk macr2lst macr2tree Autor Serge Steer INRIA 400 Nom bytecodewalk caminha no bytecode código de bytes da função aplicando transformação c1 bytecodewalkcodequeryjob Parâmetros code vetor int32 array de bytecode de entrada query inteiro o opcode código de operação a ser procurado job a operação a ser realizada requerida para c1 vetor int32 array de bytecode de saída Descrição caminha no bytecode da função aplicando transformação Ver Também bytecode Autor Serge Steer INRIA 401 Name deff definição online de função deffs1s2newfunctione1e2text opt Parâmetros e1e2 variáveis de entrada s1s2 variáveis de saída text matriz de strings opt string opcional c a função é compilada para ser eficiente padrão p a função é compilada e preparada para profiling ver profile n a função não é compilada Descrição deff pode ser usada para definir funções de seqüências de instruções escritas em strings de textos Objeto função resultante tem as mesmas propriedades que qualquer outra função definida em um arquivo de texto e carregada através de exec ou exec Aspas em instruções delimitando strings ou indicando transposição de matrizes devem ser dobradas para serem interpretadas corretamente ver quote Isto pode tornar a escrita um tanto estranha Uma alternativa em tais casos é definir funções em arquivos como de uso para carregálas no Scilab através de exec com a opção n e utilizar sci2exp para uma impressão das instruções deff corre spondentes Exemplos deffxmyplusyzxyz deffxmymacroyza3y1 xazy Ver Também comp exec function profile 402 Name exec execução de arquivo script script significa roteiro execpath mode execfun mode ierrexecpatherrcatch mode ierrexecfunerrcatch mode Parâmetros path string o endereço do arquivo script mode escalar inteiro o modo de execução ver abaixo fun uma função do Scilab ierr inteiro 0 ou número de erro Descrição execpath mode executa seqüencialmente as instruções contidas no arquivo fornecido por path com um modo de execução opcional mode Os casos diferentes para mode são 0 o valor padrão 1 nada é impresso 1 eco de cada linha de comando 2 prompt é impresso 3 ecos prompts 4 pára antes de cada prompt A execução retorna após cada retorno de carro 7 paradas prompts ecos útil para demos execfun mode executa a função fun como um script sem argumentos de entrada ou saída nem ambientes de variáveis específicos Esta forma é mais eficiente porque o código script pode se précompilado ver comp Este método para avaliação de scripts permite armazenar scripts como funções em bibliotecas Se um erro é encontrado durante a execução se o flag errcatch estiver presente exec não imprime mensagem de erro aborta execução de instruções e retorna com ierr e igual ao número de erro Se o flag errcatch não estiver presente a manipulação de erros padrão é utilizada Observação Arquivos executáveis exec files podem agora ser usados para definir funções inline utilizando a sintaxe de definição ver function exec 403 Exemplos criando um arquivo script mputla1b2TMPDIRmeuscript executandoo execTMPDIRmeuscript whos name a criando uma função deffyfooxax1ya2 clear a b chamando a função foo1 a é uma variável criada no ambiente da função foo ela é destruída quando foo retorna whos name a x1 criando x para tornála conhecida pelo script foo execfoo a e y são criadas no ambiente corrente whos name a Ver Também exec execstr evstr comp mode chdir pwd 404 Name execstr executa código Scilab em strings execstrinstr ierrexecstrinstrerrcatch msg Parâmetros instr vetor de strings instrução Scilab a ser executada ierr inteiro 0 ou número de erro msg string com valores m ou n O padrão é n Descrição Executa as instruções Scilab fornecidas pelo argumento instr Note que instr não deve fazer uso de marcas de continuação Se o flag errcatch não estiver presente a manipulação de erros ocorre de maneira usual Se o flag errcatch for ajustado e um erro for encontrado enquanto são executadas as instruções definidas em instr execstr não imprime uma mensagem de erro mas aborta a execução das instruções instr no ponto onde o erro ocorreu e retorna com ierr igual ao número de erro Neste caso a exibição da mensagem de erro é controlada pela opção msg m a mensagem é exibida e registrada n nenhuma mensagem de erro é exibida mas a mensagem de erro é registrada ver lasterror Este é o padrão ierr execstrinstrerrcatch pode manipular erros sintáticos Isto é útil para a avaliação de uma instrução obtida por uma pegunta ao usuário Exemplos execstra1 ajusta a1 execstr11 faz nada enquanto evstr11 retorna 2 execstrif t then a1 ba1 else b0 end execstrazzzzzzzerrcatch execstrazzzzzzzerrcatchm execstr 405 erros de sintaxe execstra102errcatch lasterrort execstra1 2 3errcatch lasterrort Ver Também evstr lasterror error try 406 Name fun2string gera definição ASCII de uma função Scilab txtfun2stringfunname Parâmetros fun variável do tipo função name string o nome da função gerada txt vetor coluna de strings o texto fornecendo as instruções Scilab Descrição Dado um pseudocódigo de função Scilab carregada fun2string permite gerar novamente o código O código gerado é identado e embelezado O mecanismo é similar mas mais simples que o de mfile2sci Também pode ser adaptado para traduções de sintaxe Exemplos txtfun2stringasinhfoo writeio2txta Ver Também exec edit macrovar 407 Name function abre definição de função endfunction encerra definição de função Descrição function lhsargumentsfunctionnamerhsarguments statements endfunction Onde functionname é o nome da função rhsarguments é a lista de argumentos de entrada Pode ser uma seqüência separada por vírgula de nomes de variáveis encerrada por parênteses como x1xm O último nome de variável pode ser a palavrachave varargin ver varar gin a seqüência ou nada se a função não possui argumentos de entrada lhsarguments é a lista de argumentos de saída Pode ser uma seqüência separada por vírgula de nomes de variáveis encerrada por colchetes como y1yn O último nome de variável pode ser a palavrachave varargout ver varar gout a seqüência se a função não possui argumentos de saída neste caso a sintaxe também pode ser function functionnamerhsarguments statements conjunto de instruções Scilab declarações Esta sintaxe pode ser usada para definir funções ver functions inline ou em arquivo script ver exec Para compatibilidade com versões Scilab anti gas as funções podem ser definidas em um arquivo script contendo apenas definições de funções podem ser carregadas no Scilab através da função exec A seqüência function lhsargumentsfunctionnamerhsarguments não pode ser separada em várias linhas Esta seqüência pode ser seguida por declarações na mesma linha se uma vírgula ou pontoevírgula for adicionado ao seu fim Definições de funções podem ser aninhadas Exemplos definição inline ver functions function xymyfctab xab yab endfunction xymyfct32 function 408 uma definição de função de uma linha function ysqxyx2endfunction sq3 definição de função aninhada function yfoox asinx function ysqx yx2endfunction ysqa1 endfunction foopi3 definição em um arquivo script ver exec exec SCImoduleselementaryfunctionsmacrosasinhsci Ver Também functions exec exec 409 Name functions procedimentos Scilab e objetos Scilab Descrição Funções são procedimentos Scilab macro função e procedure possuem o mesmo significado Definição de Função Geralmente elas são definidas em arquivos com um edito e carregadas no Scilab através da função exec ou através de uma biblioteca ver lib ou genlib Mas também podem ser definidas online ver deff ou function Uma função é definida por dois componentes uma parte definição de sintaxe como segue function y1ynfoox1xm function y1ynvarargoutfoox1xmvarargin uma seqüência de instruções Scilab A linha de definição de sintaxe fornece a sintaxe de chamamento completa para esta função As variáveis yi são variáveis de saída calculadas em função das variáveis de entrada xi e variáveis existentes no Scilab quando a função é executada Chamada de Função A sintaxe de chamamento de função usual é y1ynfoox1xm Listas de ar gumentos de entrada ou saída mais curtos que as da definição podem ser usadas Em tais casos apenas as primeiras variáveis da esquerda para direita são usadas ou definidas A função argn pode ser utilizada para se o número total real de argumentos de chamada É possível definir funções com número máximo indeterminado de argumentos de entrada ou saída Isto pode ser feito utilizandose as palavraschave varargin e varargout keywords Veja os links para detalhes Também é possível utilizar argumentos nomeados para especificar argumentos de entrada supon ha que a função fun1 seja definida como function y1fun1x1x2x3 então pode ser chamada com uma sintaxe como yfun1x133x31 2 3 Dentro de fun1 x2 será indefinida Também pode ser chamada com sintaxe como yfun1x133yfoo Em tal caso a variável y estará disponível no contexto da função fun1 Note que o número máximo de argumen tos deve ser menor que ou igual ao número de argumentos de entrada fornais utilizados na parte de sintaxe da função É possível buscar por variáveis definidas através da função exists Quando uma função não possui argumento de lado esquerdo e é chamada apenas com argumentos strings a sintaxe de chamamento pode ser simplificada funatotoa string is equivalent to functions 410 fun a toto a string Miscelânea Funções Scilab são objetos com números de tipo 13 ou 11 Elas podem ser manipuladas construídas salvas carregadas passadas como argumentos como outros tipos de variáveis Coleções de funções podem ser reunidas em bibliotecas Funções que começam pelo sinal ex foo são geralmente utilizadas para operações de sobrecarga ver overloading ou são funções para novos tipos de dados Exemplos definição inline ver function function xymyfctab xab yab endfunction xymyfct32 definição inline ver deff deffxymyfctabxab yab definição em um arquivo ASCI ver exec exec SCImoduleselementaryfunctionsmacrosasinhsci Ver Também function deff exec comp lib getd genlib exists varargin varargout 411 Name genlib constrói biblioteca a partir de funções em um diretório genliblibname dirname Force verb Names genliblibname pathdirname verboseverb forceForce namesNames Parâmetros libname string O nome da variável biblioteca a ser recriada dirname string O nome do diretório onde se deve procurar arquivos sci Force booleano o padrão é f Para forçar recompilação de arquivos sci ajusteo para t verb booleano o padrão é f Para obter informações ajusteo para t Names vetor de strings os nomes das funções a serem inclusas na bibilioteca Por padrão todos os ar quivos sci são levados em conta Descrição Para cada arquivo sci em dirname ou apenas para aqueles especificados pelo argumento Names genlib executa um exec e salva as funções no arquivo bin correspondente O arquivo sci só pode conter instruções Scilab Se um arquivo bin for mais novo que o arquivo sci as sicuadi genlib não traduz nem salva o arquivo O comportamento padrão pode ser modificado se force for fornecido e ajustado para t Neste último caso a recompilação é sempre feita para cada arquivo sci Quando todos os arquivos sci tiverem sido processados genlib cria uma biblioteca nomeada libname e a salva arquivo lib em dirname Se a variável Scilab libname não estiver pro tegida ver predef esta variável é atualizada Se verb estiver ajustado para t informações são exibidas durante o processo de construção Seo argumento dirname não for fornecido e se a variável Scilab libname existe e é uma variável dirname é tomado como sendo igual a o endereço de bibilioteca libname modo de atualização Restrições Scilab assume implicitamente que foosci define pelo menos uma função de nome foo Se funções subsidiárias estiverem inlusas elas são tornadas conhecidas ao Scilab apenas depois que função foo tiver sido referencida Ver Também getd exec save lib 412 Name getfunctionpath retorna o endereço do arquivo fonte de uma função de biblioteca pathgetfunctionpathfunname Parâmetros funname string o nome da função path string o nome absoluto do endereço do arquivo fonte da função sci ou Descrição Dadi o nome de uma uma função getfunctionpath o nome absoluto do endereço do arquivo fonte da função se a função estiver definida em uma biblioteca Scilab ver lib ou se nenhum nome cor responde a uma função de biblioteca Exemplos getfunctionpathmedian Ver Também lib string 413 Name getd retorna todas as funções definidas em um diretório getdpath Parameters path string Scilab O endereço do diretório Descrição Carrega todos os arquivos sci contendo funções Scilab definidos no diretório path Exemplos getdSCImodulescacsdmacros Ver Também exec lib pwd chdir 414 Name headcomments exibe comentários do cabeçalho da função Scilab headcommentsname headcommentsnamepaths Parâmetros name string nome da função paths vetor de strings endereços onde se deve procurar o arquivo sci Descrição commentsname exibe comentários do cabeçalho da função como a ajuda do Matlab Os comentários são lidos do arquivo sci associado Se name for uma função em uma biblioteca o endereço do arquivo sci é aquele dado pelo endereço da biblioteca ver lib Se name for uma função que não está na biblioteca um arquivo de nome namesci é procurado nos outros diretórios forneci dos pela variável paths AVISO a maior parte das funções Scilab predefinidas não possui comentários de cabeçalho Exemplos headcomments sinc Ver Também help Autor Serge Steer INRIA 415 Name lib definição de biblioteca xlib liblibdir Parameters libdir string Descrição libdir é um string definindo um diretório que contém arquivos de funções compiladas do Scilab bin Em adição a esses arquivos libdir deve conter um arquivo chamado names que contém os nomes das funções definidas em libdir Com sucesso todas as funções em libdir estarão disponíveis dentro do Scilab Elas são carregadas em demanda quando são chamadas pela primeira vez Arquivos binários podem ser criados de dentro do Scilab com o comando save As bibliotecas padrões do Scilab são definidas utilizandose lib nos subdiretórios SCIDIR macros Uma variável biblioteca geralmente é salva para carregamento posterior tanto online quanto do ar quivo de inicialização específico do usuário ver startup Restrições O Scilab assume tacitamente que cada arquivo xxxxbin define uma variável chamada xxxx Exemplos define some variables function z myplusx y z x yendfunction function z yourplusx y x x yendfunction A110 create the bin files in libdir libdirTMPDIR savelibdir myplusbin myplus savelibdir yourplusbin yourplus savelibdir Abin A create the name file mputlmyplusyourplusATMPDIRnames build the library containing myplus and yourplus xlib liblibdir erase the variables clear myplus yourplus A Automatic loading and execution myplus12 lib 416 A Ver Também library genlib save deff exec whereis 417 Name librarieslist retorna as bibliotecas do Scilab slibrarieslist Parâmetros s uma matriz de strings Descrição Retorna em s todas as bibliotecas na pilha Scilab Exemplos librarieslist Ver Também libraryinfo 418 Name library descrição de tipo de dado bibilioteca Descrição Uma bibilioteca é um tipo de dado com número 14 Contém um nome de endereço e um conjunto de nomes Permite o carregamento automático de variáveis utilizando o seguinte algoritmo Suponha o usuário Scilab referencie a variável de nome foo O Scilab procura primeiro se foo é o nome de uma primitiva ou de uma variável já definida Se naõ for procura por foo seqüencialmente a mais nova em toda a biblioteca definida Suponha que foo pertence ao conjunto de nomes da biblioteca xlib Então o Scilab tenta carregar o arquivo xlibpathnamefoobin xlibpathnamefoobin deve ter sido criado utilizandose a função save Bibliotecas geralmente são utilizadas para coleções de funções mas também podem ser utilizadas para coleções de variáveis Scilab Se uma função estiver definida em mais de uma biblioteca o algoritmo de busca padrão carrega aquela contida na mais nova É possível forçar o uso de uma biblioteca específica utilizando a notação de ponto xlibfoo carrega a variável foo contida em xlib if foo for uma função e xlibfooargs executa as funções Exemplos elemlib é uma biblioteca predefinida elementaryfunctionlib exibindo o conteúdo da biblioteca Arand33 cosmA carregando cosm e executandoo whos name cosm agora cosm é uma variável elementaryfunctionlibsinm carregando sinm da biblioteca elementaryfunctionlibcosmA carregando novamente cosm e executandoo Ver Também lib string load save 419 Name libraryinfo retorna macros e endereço de uma biblioteca Scilab macros libraryinfolibraryname macrospath libraryinfolibraryname Parâmetros macros uma matriz de strings todas as funções principais da biblioteca path um string endereço da biblioteca libraryname string nome da biblioteca Descrição Retorna nomes de funções e o endereço de uma biblioteca Scilab Os nomes de funções são aqueles que correspondem aos nomes de arquivo associados sci ou bin Os outros são funções subsidiárias Exemplos mplibraryinfocorelib Ver Também librarieslist 420 Name listfunctions propriedades de todas as funções no espaço de trabalho flistcompiledprofilablecalled listfunctionsscope Parâmetros scope string local padrão ou global flist array de strings names nomes de todas as variáveis funções especificadas no espaço de trabalho compiled array de booleanos verdadeiro se o elemento correspondente de flist for do tipo 13 profilable array de booleanos verdadeiro se o elemento correspondente de flist for do tipo 13 e adicional mente informações sobre profiling forem encontradas no pseudocódigo da função called array uint32 número de vezes que o elemento correspondente de flist foi chamado nãozero apenas se a função possuir profiling Descrição Esta função verifica todas as variáveis do espaço de trabalho dadas por who e coleta aquelas de tipo 11 ou 13 para as últimas lstmacr2lstfun é chamada de modo a verificar a entrada para magic profiling ao fim da primeira linha de código ie lst5125 Exemplos recompilefunctionasinhp flistcompiledprofilablecalled listfunctions flistprofilable Ver Também function exec deff comp fun2string profile recompilefunction Autor Enrico Segre Bibliografia httpwikiscilaborgScilabfunctionvariables3Arepresentation2Cmanipulation 421 Name macro Procedimento Scilab e objeto Scilab Descrição Macros são procedimentos Scilab macro função e procedimento possuem o mesmo significa do Geralmente eles são definidos em arquivos com um editor e carregados no Scilab com exec ou através de uma biblioteca Também podem ser definidos online ver deff Um arquivo que contém uma macro deve começar como segue function y1ynfoox1xm Os yi são variáveis de saída calculadas como funções de variáveis de entrada e variáveis existentes no Scilab quando o macro é executado Um macro pode ser compilado para uma execução mais rápida Coleções de macros podem ser armazenadas em bibliotecas Macros que começam pelo símbolo ex foo e cujos argumentos são listas são usadas para executar operações específicas por exemplo zrmrxy é equivalente a zxy quando x e z são racionais ie xlistrnd com n e d polinômios Ver Também deff getf comp lib 422 Name macrovar variáveis de uma função varsmacrovarfunction Parâmetros vars list listinoutglobalscalledlocals function nome de uma função Descrição Retorna em uma lista o conjunto de variáveis utilizadas por uma função vars é uma lista feita de cinco vetores colunas de strings in variáveis de entrada vars1 out variáveis de saída vars2 globals variáveis globais vars3 called nomes de funções chamadas vars4 locals variáveis locais vars5 Exemplos deffyfx1x2loc1yax1x2loc varsmacrovarf Ver Também string macr2lst 423 Name plotprofile extrai e exibe execução de profiles dossiês de uma função Scilab plotprofilefun Parâmetros fun função Scilab compilada ou nome de função string ou array de nomes de funções Descrição Para utilizar plotprofile a função Scilab deve ter sido preparada para profiling análise de de sempenho ver exec Quando tal função é executada o sistema conta quantas vezes cada linha foi executada e quanto tempo de cpu foi gasto para cada linha Estes dados são armazenados dentro da estrutura de dados da função A função plotprofile é um comando interativo que exibe os resultados em uma janela gráfica Quando uma linha é clcada a fonte da função é exibida com a linha selecionada realçada NOTA você deve clicar no item Exit na janela de gráficos para sair de plotprofile O código da função é gerado com fun2string e guardado em um arquivo temporário Exemplos definindo função e preparandoa para profiling deffxfoonif n0 then x else x0 for k1n ssvdrandn10n10 xxs1 end endp chamando a função foo30 obtendo profiles de execução plotprofilefoo clique em Exit para sair Ver Também profile showprofile fun2string 424 Name profile extrai profiles dossiês de execução de uma função do Scilab cprofilefun Parâmetro fun função Scilab c uma matriz nx3 contendo os profiles de execução Descrição Para utilizar profile a função Scilab deve ter sido preparada para profiling análise de desempenho ver exec Pata tal função quando tal função é executada o sistema conta quantas vezes cada linha foi executada e quanto tempo de cpu foi gasto para cada execução da linha Estes dados são armazenados na estrutura de dados da função A função profile permite extrair esses dados e retornálos nas duas primeiras colunas de c A terceira coluna de c fornece a medida do esforço do interpretador para a execução da linha correspondente A iésima linha de c corresponde à iésima linha da função inclusa primeiro Note que devido à precisão do clock do processador tipicamente um microssegundo algumas lin has executadas aparecem com tempo de execução 0 mesmo que o tempo de execução de cpu total realmente gasto seja grande Exemplos definindo a função e preparandoa para profiling deffxfoonif n0 then x else x0 for k1n ssvdrandn10n10 xxs1 end endp chamando a função foo10 obtendo profiles de execução profilefoo chamando a função foo20 profilefoo a execução de profiles é acumulada Ver Também exec deff plotprofile showprofile 425 Name recompilefunction recompila uma função Scilab modificando o seu tipo recompilefunctionfunname kind force Parâmetros funname string nome da função a ser recompilada kind string n não compilado tipo 11 c compilado tipo 13 or p compilado tipo 13 preparado para profiling Pardrão c force booleano Se falso a função é recompilada apenas se seu tipo mudar se verdadeiro é recompi lada ainda que mantenha o tipo notavelmente útil para compilar uma função p function para reiniciar as estatísticas de profiling Descrição Esta função compila reversamente uma variável função via fun2string e a recompila para o tipo desejado através de deff Exemplos recompilefunctionasinhp for i1100 asinhrand100100 end showprofileasinh Ver Também function exec deff comp fun2string profile Autor Enrico Segre Bibliografia httpwikiscilaborgScilabfunctionvariables3Arepresentation2Cmanipulation 426 Nom removeprofiling remove instruções de profiling análise de performance de uma função removeprofilingfunname Parâmetros funname string o nome da função Descrição removeprofilingfunname remove instruções de profiling se houver alguma da função de nome funname Exemplos function xfooan x0 for i1n if x10 then xxa else xx1 end end xx21 endfunction addprofilingfoo foo01100 executando a função profilefoo extraindo informação de profile removeprofilingfoo Ver Também profile plotprofile removeprofiling resetprofiling Autor Serge Steer INRIA Funções Utilizadas Esta função utiliza as funções Scilab bytecode e walkbytecode 427 Nom resetprofiling reinicia contadores de profiling de uma função resetprofilingfunname Parâmetros funname string o nome da função Descrição resetprofilingfunname reinicia contadores de profiling se houver da função de nome funname Exemplos function xfooan x0 for i1n if x10 then xxa else xx1 end end xx21 endfunction addprofilingfoo foo01100 executando a função profilefoo extraindo informação de profile resetprofilingfoo profilefoo extraindo informação de profile Ver Também profile plotprofile addprofiling resetprofiling removeprofiling Autor Serge Steer INRIA Funções Utilizadas Esta função utiliza as funções Scilab bytecode e walkbytecode 428 Name showprofile extrai e exibe profiles dossiês de execução de uma função Scilab showprofilefun Parâmetros fun função Scilab Descrição Para utilizar showprofile a função Scilab deve ter sido preparada para profiling análise de per formance ver exec Para tal funçãoQuando tal função é executada o sistema conta quantas número de vezes que cada linha é executada e quanto tempo de cpu é gasto para execução de cada linha Estes dados são armazenados dentro da estrutura de dados da função A função showprofile retorna resultados de profiling ver profile com o texto das linhas da função O texto da função é reconstruído com fun2string Exemplos definindo função e preparandoa para profiling deffxfoonif n0 then x else x0 for k1n ssvdrandn10n10 xxs1 end endp chamada à função foo30 obtendo profiles showprofilefoo Ver Também profile plotprofile fun2string 429 Name varargin variável do número de argumentos de saída em uma lista de argumentos de entrada Descrição Uma função cujo último argumento de entrada é varargin pode ser chamada com mais argumentos de entrada que os indicados pela lista de argumentos de entrada Os argumentos de chamada passados da palavrachave varargin em diante podem ser recuperados em uma lista chamada varargin Suponha que a palavrachave varargin é o nésimo argumento da lista de argumentos de entrada formal então se a função é chamada com n1 argumentos de entrada a lista varargin não é definida Se a função for chamada com n1 argumentos então varargin é uma lista vazia y function exvarargin pode ser chamada com qualquer número de argumentos de entrada Dentro da função ex argumentos de entrada podem ser recuperados em varargini i1lengthvarargin Se não for o último argumento de entrada da função varargin é um argumento de entrada normal sem nenhum significado especial O número de argumentos de entrada real é dado por argn2 Observações Sintaxe de argumento nomeada como fookeyvalue é incompatível com o uso de varargin A razão é que os nomes ie keys associados aos valores value não são armazenados na lista varargin Considere por exemplo function foovarargindispvarargin1varargin2endfunction fooa1b2 O Scilab responde 1 2 foob1a2 O Scilab responde 1 2 O resultado é o mesmo mas os argumentos foram invertidos Exemplos deffexamplavararginlhsrhsargn0 if rhs1 then dispvararginend exampl1 exampl exampl123 llistast exampl1l23 Ver Também function varargout list 430 Name varargout variável do número de argumentos de saída em uma lista de argumentos de saída Descrição Uma função cuja lista de argumentos de saída contém varargout deve ser chamada com mais argumentos de saída que indicado na lista de argumentos de saída A chamada de argumentos passados da palavrachave varargout em diante são extraídos da lista varargout definida na função varargout function ex pode ser chamado com qualquer número de argumentos de saída Dentro da função ex argumentos de saída podem ser armazenados em varargouti X1Xnvarargout function ex também pode ser usado Neste caso as variáveis Xi devem estar atribuídas na função tanto quanto varargouti O número total real de argumentos de saída é dado por argn1 Observação A variável varargout deve ser criada dentro de uma função e atribuída a uma list Se varargout for a única variável de saída formal a lista deve conter pelo menos uma entrada Exemplos function varargoutexampl varargoutlist1234 endfunction xexampl xyexampl xyzexampl function abvarargoutexampl1 afirst bsecond varargoutlist1234 endfunction exampl1 abexampl1 abcexampl1 Ver Também function varargin list 431 Name whereis ome da biblioteca contendo a função librnamewhereisfunctionname Descrição Retorna um string correspondente ao nome da biblioteca onde a função functionname se encon tra O endereço da biblioteca é retornado digitandose librname Ver Também lib 432 Name getf defining a function from a file getffilename opt Parameters filename Scilab string opt optional character string c loaded functions are compiled to be more efficient default n loaded functions are not compiled p loaded functions are compiled and prepared for profiling see profile Description WARNING this function has been deprecated see exec as a replacement of getf getf will be removed in Scilab 53 loads one or several functions see functions defined in the file filename The string optn means that the functions are not compiled preinterpreted when loaded This can be use ful for some debugging purpose see comp By default functions are compiled when loaded ie optc is used In the file a function must begin by a syntax definition line as follows function y1ynfoox1xm The following lines contain a sequence of scilab instructions The syntax definition line gives the full calling syntax of this function The yi are output variables calculated as functions of input variables xi and variables existing in Scilab when the function is executed Shorter input or output argument list may be used Many functions may be written in the same file A function is terminated by an endfunction keyword For compatibility with previous versions a function may also be terminated by the following function keyword or the EOF mark For that reason it is not possible to load function containing nested function definition using the getf function getf is an obsolete way for loading functions into scilab from a file It is replaced by the function exec Note that functions in a file should be terminated by an endfunction keyword The exec function supposes optc To prepare a function for profiling please use the addprofiling function Examples getf 433 getfSCImodulesgraphicsmacrosplotsci getf SCImodulesgraphicsmacrosplotsci See Also functions function genlib getd exec edit comp addprofiling Parte V Arquivos funções de EntradaSaída 435 Name chdir muda o diretório corrente do Scilab cd muda o diretório corrente do Scilab bchdirpath realpathcdpath cd path Parâmetros b um booleano t se a operação chdir estiver ok path um string realpath um string o nome real do endereço após a conversão do nome do endereço ver abaixo Descrição Muda o diretório corrente do Scilab para aquele dado por path Note que a conversão de endereço é realizada e por exemplo SCImodulescoremacros é um padrão válido tanto pra Unix quanto para Windows Se path for vazio muda para diretório home Exemplos chdirTMPDIR pwd cd cd SCI Ver Também pwd 436 Name fileinfo Fornece informações sobre um arquivo xierrfileinfofile Parâmetros file string o endereço do arquivo x um vetor de inteiros de tamanho 13 contendo informações ou uma matriz vazia se o arquivo não existir ierr indicador de erro 0 se não for encontrado nenhum erro Descrição xfileinfofile retorna x1 O tamanho do arquivo x2 O modo do arquivo valor decimal x3 O id do usuário x4 O id do grupo x5 O número do dispositivo x6 A data da última modificação x7 A data da última mudança x8 A data do último acesso x9 O tipo de dispositivo se o dispositivo for inode x10 O tamanho de bloco para a entradasaída do sismtema de arquivos sempre 0 no Windows x11 O número de blocos alocados sempre 0 no Windows x12 O inode x13 O número de hard links fileinfo 437 Referência Esta função é uma interface para a função C stat Permissões são tipicamente especificadas como números octais dec2octx2 para conversão O modo numérico possui de um a quatro dígitos octais 07 derivados através da soma de bits com os valores 4 2 e 1 Quaisquer dígitos omitidos são supostos como zeros à esquerda O primeiro dígito seleciona o ID de usuário 4 e ajusta o ID do grupo 2 e atributos sticky 1 O segundo dígito seleciona permissões para o usuário que possui o arquivo leitura 4 escrita 2 e execução 1 o terceiro dígito seleciona permissões para os outros usuários no grupo do arquivo com os mesmos valores e o quarto seleciona permissões para outros usuários que não estão no grupo do arquivo com os mesmos valores Exemplos w fileinfoSCIetcscilabstart permisso do arquivo dec2octw2 data do arquivo getdatew6 Verificando a permisso de escrita em um arquivo w fileinfoSCIetcscilabstart SIWRITE 128 mascarando a permisso de escrita SIEXEC 64 mascarando a permisso de execuo SIREAD 256 mascarando a permisso de leitura SIFCHR 8192 mascarando a permisso de diretrio if bitand w2 SIWRITE 0 then dispPERIMISSO DE ESCRITA neste arquivo else dispNO H PERIMISSO DE ESCRITA neste arquivo end Ver Também getdate file dispfiles newest isdir Autores S Steer INRIA AC 438 Name getabsolutefilepath fornece o nome de endereço absoluto de um arquivo aberto no Scilab pathname getabsolutefilepathfilename Parâmetros filename string nome do arquivo pathname string o nome de endereço absoluto Descrição Fornece o nome de endereço absoluto de um arquivo já aberto no Scilab getabsolutefilepath procura na lista interna de arquivos abertos correntemente do Scilab filename e retorna seu endereço Se o arquivo não for aberto um erro é retornado Aviso na versão anterior Scilab 50x o diretório corrente era retornado se o arquivo não fosse encontrado Esta função pode ser utilizada para encontrar de onde endereço um script Scilab é executado Exemplos executando este script amopenTMPDIRtestscewt dispgetabsolutefilepathtestsce mclosea Ver Também getshortpathname getlongpathname pwd Autores Allan CORNET 439 Name getrelativefilename dado um nome de diretório absoluto e um nome de arquivo relativo retorna um nome de arquivo relativo relfile getrelativefilenameabsdirabsfile Parâmetros absdir string o diretório absoluto absfile string o nome de arquivo absoluto relfile string o nome de arquivo relativo Descrição dado um nome de diretório absoluto e um nome de arquivo relativo retorna um nome de arquivo relativo Por exemplo se o diretório corrente é Cscilabbin e o nome de arquivo Cscilabmoduleshelp toolsreadmetxt é dado getrelativefilename retornará moduleshelptoolsreadmetxt Exemplos if MSDOS then getrelativefilenameCprogram filescilab40binCprogram filescilab40moduleshelptoolshelpdtd getrelativefilenameCprogram filescilab40binCprogram filescilab40moduleshelptoolshelpdtd getrelativefilenameSCIbinSCImoduleshelptoolshelpdtd getrelativefilenameWSCIbinWSCImoduleshelptoolshelpdtd getrelativefilenamepwdWSCIbinWscilex else getrelativefilenameusrlocalscilab40binusrlocalscilab40moduleshelptoolshelpdtd getrelativefilenameusrlocalscilab40binusrlocalscilab40moduleshelptoolshelpdtd getrelativefilenameSCIbinSCImoduleshelptoolshelpdtd getrelativefilenamepwdSCIbinscilex end Ver Também getshortpathname getlongpathname pwd Autor Pierre MARECHAL 440 Name newest retorna o arquivo mais novo de um conjunto de arquivos knewestpaths knewestpath1path2pathn Parâmetros k o índice do arquivo mais novo paths vetor de strings pathsi é o endereço do iésimo arquivo pathi string o endereço do iésimo arquivo Descrição Dado um conjunto de endereços newest retorna o índice do mais novo Arquivos não existentes são supostos como mais antigos Exemplos newestSCImodulesgraphicsmacrosbodesciSCImodulesgraphicsmacrosbodebin newestSCImodulesgraphicsmacrosbodesciSCImodulesgraphicsmacrosbodebin newestSCImodulesgraphicsmacrosbodescibin Ver Também fileinfo 441 Name sscanf converte entrada formatada fornecida por um string v1vnsscanf stringformat Parameters format especifica a conversão de formato string especifica a entrada a ser lida Descrição Esta função está obsoleta use a função msscanf de preferência que é mais eficiente mais compatível com o procedimento C sscanf A função sscanf intepreta um string de acordo com um formato e retorna os resultados convertidos O parâmetro de formato contém especificações de conversão utilizadas para interpretar a saída O parâmetro de formato pode conter caracteres em branco espaços tabulações novas linhas quebra de página os quais exceto nos dois casos seguintes lê a entrada até o próximo caractere preenchido A menos que haja uma correspondência no string de controle espaços em branco incluindo caractere de nova linha vindo por último não são lidos Qualquer caractere exceto sinal de porcento que deve corresponder ao próximo caractere do fluxo de entrada Uma especificação de conversão que direciona a conversão do próximo campo de entrada Ver scanfconversion para detalhes Ver Também mprintf msscanf mfscanf scanfconversion 442 Name basename strip directory and suffix from filenames files basenamefilesflag flagexpand Parameters files a string matrix giving a set of file names flagflagexpand boolean optional parameters default value t files a string matrix Description basename return the basename of the file entries given in files If flag is true the files are first converted to the target type given by the MSDOS variable Moreover if flagexpand is true leading strings like HOME SCI or are expanded using environment variables Examples filesbasenameSCImodulesfileiomacrospoosci filesbasenameSCImodulesfileiomacrospoosci filesbasenameSCImodulesfileiomacrospooscik See Also listfiles pathconvert fileparts 443 Name copyfile Copy file copyfilesourcedestination statusmessage copyfilesourcedestination Description copyfilesourcedestination copies the file or directory source and subdirectories to the file or directory destination If source is a directory destination can not be a file copyfile replaces existing files without warning status message copyfilesourcedestination copies source to destination returning the status and a message Whatever the operating system if the copy succeeds the status is 1 and the message is empty if the copy fails the status is 0 and the message is not empty The timestamp given to the destination file is identical to that taken from source file Examples copyfileSCIetcscilabstartTMPDIRscilabstart statusmessage copyfileSCIetcscilabstartTMPDIR See Also movefile mdelete Authors Allan CORNET 444 Name createdir Make new directory createdirdirname status createdirdirname Description createdirdirname creates the directory dirname in the current directory if dirname is not in the current directory specify the relative path to the current directory or the full path for dirname status createdirdirname creates the directory dirname in the existing directory parentdir return ing the status a message Here status is T for success and F otherwise createdir is used by mkdir Examples createdirSCIHOMEDirectorytest removedirSCIHOMEDirectorytest See Also mkdir rmdir Authors AC 445 Name deletefile delete a file f deletefilefilename Parameters filename a file name existing or not f t or f Description delete a file if file has been deleted it will return t else f Examples fd mopenTMPDIRfiletodeletetxtwt mclosefd if fileinfoTMPDIRfiletodeletetxt then deletefileTMPDIRfiletodeletetxtend deletefileTMPDIRnotexistingfile Authors AC 446 Name dir get file list dir path Sdirpath Parameters path a string matrix giving a directory pathname eventually ended by a pattern built with Default value is S a tlist of type dir with fields name date and isdir Description dir can be used to get the files which match the patterns given by the path argument Patterns are given to the unix ls or to the windows dir commands in order to get information on files Thus in order to write portable Scilab script valid wildcard patterns for both os are to be given Note that Pathname conversion is performed and for example SCImodulescoremacrossci is a valid pattern for both unix and windows The name field of the returned variable is the column vector of the file names The date field of the returned variable is the column vector of integers containing a last modification date coded in second from 1 Jan 1970 The isdir field of the returned variable is the column vector of boolean true if the corresponding name is a directory The default display of the returned structure is a column formatted list of files It can be changed redefining the function dirp Examples dir dir SCImodulescoremacrosbin xdirSCImodulescoremacrosbin dtgetdatexdate mprintfs 04d02d02d 02d02d02d xnamedt1 2 6 79 See Also listfiles findfiles ls fileinfo date 447 Name dirname get directory from filenames dirs dirnamefilesflag flagexpand Parameters files a string matrix giving a set of file names flagflagexpand boolean optional parameters default value t filesdir string matrices Description dirname return the dirname of the file entries given in files If flag is true the files are first converted to the target type given by the MSDOS variable Moreover if flagexpand is true leading strings like HOME SCI or are expanded using environment variables Note that dirnamefilesf can give erroneous results if pathnames given in files do not follow the convention given by the MSDOS variable Examples filesdirnameSCImodulesfileiomacrospoosci filesdirnameSCImodulesfileiomacrospoosci filesdirnameSCImodulesfileiomacrospooscik See Also basename listfiles pathconvert 448 Name dispfiles display opened files properties dispfilesunits Parameters units a vector of numbers the files logical units By default all opened files Description dispfiles displays properties of currently opened files Examples dispfiles See Also file mopen Authors S Steer 449 Name fileext returns extension for a file path extension fileextfullpath Parameters fullpath a character string the given file path extension a character string the extension part is any or Description extensionfileextfullpath splits the fullpath character string in the extension part in cluding the dot Examples extension fileextSCIetcscilabstart extension fileextSCIetcscilabstartSCIetcscilabquit See Also fileparts Authors Allan CORNET 450 Name fileparts returns the path filename and extension for a file path pathfnameextensionfilepartsfullpath vfilepartsfullpathsel Parameters fullpath a character string the given file path sel a optional character string selector with posible values path fname or extension path a character string the path of the directory pointed to by fullpath fname a character string the filename part is any or extension a character string the extension part is any or value a character string depending on sel value Description pathfnameextensionfilepartsfullpath splits the fullpath character string in its three parts the path of the directory pointed to the filename part the extension part including the dot Examples pathfnameextensionfilepartsSCIetcscilabstart filepartsSCIetcscilabstartextension See Also pathconvert basename fullfile Authors Serge Steer INRIA 451 Name filesep returns directory separator for current platform s filesep Parameters s a string Description returns directory separator on Linux or on Windows Examples filesep Authors AC 452 Name findfiles Finding all files with a given filespec f findfiles ffindfilespath ffindfilespathfilespec Parameters path a path filespec a spec file example sce f returns a string matrix of filenames Description Finding all files with a given filespec Examples ffindfiles ffindfilesSCI ffindfilesSCImodulescoremacrossci See Also listfiles Authors AC 453 Name fprintf Emulator of C language fprintf function fprintffileformatvalue1valuen Parameters format a Scilab string Specifies a character string combining literal characters with conversion specifi cations valuei Specifies the data to be converted according to the format parameter str column vector of character strings file a Scilab string specifying a file name or a logical unit number see file Note that is file0 the message will be display on standard error stream stderr Description Obsolete function use preferabily the mfprintf function which is much more compatible with the C fprintf functionalities The fprintf function converts formats and writes its value parameters under control of the format parameter to the file specified by its file parameter The format parameter is a character string that contains two types of objects Literal characters which are copied to the output stream Conversion specifications each of which causes zero or more items to be fetched from the value parameter list see printfconversion for details If any values remain after the entire format has been processed they are ignored Examples ufileopenresultsunknown open the result file t0012pi for tkt fprintfutime 63f value 63ftksintk write a line end filecloseu close the result file fprintf0My error which is going to be displayed on the stderr See Also mfprintf string print write format disp file printf sprintf printfconversion 454 Name fprintfMat Write a matrix in a file fprintfMatfileM formattext Parameters fil a string the pathname of the file to be written M A matrix of real numbers format a character string a C like format This is an optional parameter the default value is f text a string matrix giving non numerical comments stored at the beginning of the file Description The fprintfMat function writes a matrix in a formated file Each row of the matrix give a line in the file If text is given then the elements of text are inserted columnwise at the beginning of the file one element per line Examples n50 arandnnu fprintfMatTMPDIRMata52f a1fscanfMatTMPDIRMat See Also mclose meof mfprintf mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 455 Name fscanf Converts formatted input read on a file v1vnfscanf fileformat Parameters format Specifies the format conversion file Specifies the input file name or file number Description The fscanf functions read character data on the file specified by the file argument interpret it according to a format and returns the converted results The format parameter contains conversion specifications used to interpret the input The format parameter can contain whitespace characters blanks tabs newline or formfeed that except in the following two cases read the input up to the next nonwhitespace character Unless there is a match in the control string trailing white space including a newline character is not read Any character except percent sign which must match the next character of the input stream A conversion specification that directs the conversion of the next input field see scanfconversion for details See Also printf read scanf sscanf mfscanf scanfconversion 456 Name fscanfMat Reads a Matrix from a text file MfscanfMatfilename MtextfscanfMatfilename Parameters filename a character string giving the name of the file to be scanned M Output variable A matrix of real numbers text Output variable A string matrix Description The fscanfMat function is used to read a scalar matrix from a text file The first nonnumeric lines of the file are returned in text if requested and all the remaining lines must have the same number of columns column separator are assumed to be white spaces or tab characters The number of columns of the matrix will follow the number of columns found in the file and the number of lines is fetched by detecting eof in the input file This function can be used to read back numerical data saved with the fprintfMat Examples fdmopenTMPDIRMatw mfprintffdSome text mfprintffdSome text again arand66 for i16 for j16 mfprintffd52f aijend mfprintffd end mclosefd a1fscanfMatTMPDIRMat See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 457 Name fullfile Build a full filename from parts f fullfilevarargin Parameters varargin all directories and filename used to build the full filename at least one directory and filename f full filename Description f fullfilevarargin builds a full filename taking care of platform on which it is run and handling the cases when the directories begin or end with a directory separator Examples ffullfilehomescilabmacrosutilfullfilesci ffullfileCscilabmacrosutilfullfilesci See Also pathconvert fileparts Authors VC 458 Name fullpath Creates an full path name for the specified relative path name res fullpathrelativepath Parameters res a string relativepath a string Description Creates an full path name for the specified relative path name On linux relativepath needs to exist Examples mkdirTMPDIRniv1 mkdirTMPDIRniv1niv2 mputl TMPDIRniv1testtxt cdTMPDIRniv1niv2 fullpathtesttxt Authors AC 459 Name getdrives Get the drive letters of all mounted filesystems on the computer drives getdrives Parameters drives a matrix of strings Description Get the drive letters of all mounted filesystems on the computer returns the roots of all mounted filesystems on the computer as a matrix of strings For Linux this list consists solely of the root directory Examples getdrives Authors AC 460 Name getlongpathname get long path name Only for Windows longpathgetlongpathnameshortpath longpathbOKgetlongpathnameshortpath Parameters shortpath A character string or matrix of strings the short path longpath A character string or matrix of strings the long path bOK A boolean T or a matrix of boolean if path has been converted else F Description The getlongpathname primitive converts the specified path to its long form It no long path is found this primitive returns the specified name Examples longpathbOKgetlongpathnameSCI longpathsbOKsgetlongpathnameSCISCI See Also getshortpathname Authors Allan CORNET 461 Name getshortpathname get short path name Only for Windows shortpathgetshortgpathnamelongpath shortpathbOKgetshortpathnamelongpath Parameters longpath A character string or matrix of strings the long path shortpath A character string or a matrix of strings the short path bOK A boolean T or a matrix of boolean if path has been converted else F Description The getshortpathname primitive converts the specified path to its short form Examples shortpathbOKgetshortpathnameSCI shortpathsbOKsgetshortpathnameSCISCI See Also getlongpathname Authors Allan CORNET 462 Name io variable returns standard input and standard output file descriptor io1 io2 Description io1 returns standard input file descriptor 5 io2 returns standard ouput file descriptor 6 file descriptor 0 is the standard error Examples mfprintfio2Scilab stdout C mfprintf0Scilab stderr C writeio2Scilab stdout Fortran write0Scilab stderr Fortran unitstypnamesfile See Also write mfprintf file 463 Name isdir checks if argument is a directory path risdirpath Parameters path a character string or a matrix of strings the file pathname r a boolean true if path is a path to a directory Description risdirpath checks if path is a path to a directory Reference This function is based on the C function stat The SCI and shortcuts for Scilab directory and home directory are handled Examples isdirTMPDIR isdir SCIetcscilabstart See Also fileinfo Authors S Steer INRIA 464 Name isfile checks if argument is a file b isfilefilenames Parameters files a character string or a string matrix x an matrix of boolean t is filename exists Description x isfilefilename checks if filename is existing file or not a directory is not a file see isdir Examples cd SCI filenames ls isfilefilenames isfilefilenames isfileSCI etc isdirSCI etc See Also fileinfo isdir Author AC 465 Name listfiles list files files listfilespaths flagflagexpand Parameters paths a string matrix giving a set of pathnames eventually ended by a pattern built with flagflagexpand boolean optional parameters default value t files a string matrix Description listfiles can be used to list the files which match the patterns given by one of the paths entries Patterns are given to the unix ls or to the windows dir commands in order to get information on files Thus in order to write portable Scilab script valid wildcard patterns for both os are to be given Note that Pathname conversion is performed and for example SCIcoremacrossci is a valid pattern for both unix and windows if flag is true the pathnames given by paths are converted according to the MSDOS value See pathconvert Moreover if flagexpand is true leading strings like HOME SCI or are ex panded using environment variables Examples fileslistfilesSCImodulescoremacrossciSCImodulescoremacrosbin See Also findfiles basename pathconvert 466 Name listvarinfile list the contents of a saved data file listvarinfilefilename namstypsdimsvolslistvarinfilefilename Parameters filename character string the pathname of the file to be inspected nams character array names of the variables saved in the file dims list dimensions of the variables saved in the file typs numeric array types of the variables saved in the file vols numeric array size in bytes of the variables saved in the file Description This utility function lists a la whos the variables contained in a Scilab data file produced by save Remark hypermatrices are reported as plain mlists rationals and statespaces are reported as plain tlists graphic handles are not recognized Examples aeye22 bint16onesa crand233 savevalsdatabc listvarinfilevalsdat See Also whos save load saveformat type Authors Serge Steer 31 Jan 2001 reediting by Enrico Segre 467 Name ls show files ls path options filesls path Parameters path a string matrix giving a directory pathname eventually ended by a pattern built with Default value is files a string column vector By default it contains a column formatted output if one of the option is 1 files contains an entry for each files Description ls can be used to list the files which match the patterns given by the path argument Patterns are given to the unix ls or to the windows dir commands in order to get information on files Thus in order to write portable Scilab script valid wildcard patterns for both os are to be given Note that Pathname conversion is performed and for example SCImodulescoremacrossci is a valid pattern for both unix and windows If you want to get a vector of all files matching a pattern use preferabily the listfiles or the dirfunction Please note that starting from the version 50 of Scilab the second input argument has been removed a sequence of strings which can be added under Unix systems the Unix ls command options This option has been removed mainly for security and portability reasons Examples ls ls SCImodulescoremacrossci xlsSCImodulescoremacrossci See Also listfiles findfiles dir fileinfo 468 Name maxfiles sets the limit for the number of files a scilab is allowed to have open simultaneously r maxfilesnewnumbermax Parameters newnumbermax a integer the new value r effective new value Description sets the limit for the number of files a scilab is allowed to have open simultaneously Minimum 20 Maximum 100 Default 20 Examples rmaxfiles50 See Also mopen 469 Name mclearerr reset binary file access errors mclearerrfd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 Description The function clearerr is used to resets the error indicator and EOF indicator to zero See Also merror mclose mopen mput mget mgetstr mputstr meof mseek mtell 470 Name mclose close an opened file errmclosefd mcloseall Parameters fd scalar The fd parameter returned by the function mopen is used as a file descriptor its a positive integer err a scalar Error indicator vector Description mclose must be used to close a file opened by mopen If fd is omitted mclose closes the last opend file mcloseall closes all files opened by fileopen or mopen Be careful with this use of mclose because when it is used inside a Scilab script file it also closes the script and Scilab will not execute commands written after mcloseall See Also meof mfprintf fprintfMat mfscanf fscanfMat mget mgetl mgetstr mopen mprintf mput mputl mputstr mscanf mseek mtell file mdelete 471 Name mdelete Delete files mdeletefilename Parameters filename a character string The pathname of the files to delete Description mdelete may be used to delete a file or a set of files if filename contains metacharaters Note that mdelete does not ask for confirmation when you enter the delete command To avoid accidentally losing files make sure that you have accurately specified the items you want deleted See Also mopen mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell 472 Name meof check if end of file has been reached errmeoffd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 err scalar Error indicator Description The function meof will return a non null value if end of file has been reached in a previous call to mget or mgetstr The function clearerr is used to reset the error flag and EOF flag to zero See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 473 Name merror tests the file access errors indicator err merrorfd errmsg merrorfd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 err scalar returns the error status number errnum of the most recent file IO operation associated with the specified file If the most recent IO operation performed on the specified file was successful the value of msg is empty and merror returns an err value of 0 msg string returns the error string message Description The function merror is used to tests the file access errors indicator returning nonzero if it is set The error indicator can only be reset by the mclearerr function A nonzero err indicates that an error occurred in the most recent file IO operation The value of message is a string that can contain information about the nature of the error If the message is not helpful consult the C runtime library manual for your host operating system for further details Examples fd mopenTMPDIR filetxttxtwt errmsg merrorfd if err 0 then printfProblem end mclosefd See Also mclearerr mclose mopen mput mget mgetstr mputstr meof mseek mtell 474 Name mfprintf converts formats and writes data to a file mfprintffdformata1an Parameters fd scalar file descriptor given by mopen its a positive integer if fd equals 0 redirection in stderr if fd equals 6 redirection in stdout OBSOLETE The value 1 refers to the default file ie the last opened file format a Scilab string describing the format to use to write the remaining operands The format operand follows as close as possible the C printf format operand syntax str a character string string to be scanned a1an Specifies the data to be converted and printed according to the format parameter Description The mfprintf function is a interface for Ccoded version of fprintf functions The mfprintf function writes formatted operands to the file specified by the file desciptor fd The argument operands are formatted under control of the format operand this function may be used to output column vectors of numbers and string vectors without an explicit loop on the elements In that case this function iterates on the rows The shortest vector gives the number of time the format has to be iterated An homogeneous sequence of identical type parameters can be replaced by a matrix Examples fd mopenTMPDIRtexttxtwt mfprintffdhello s d world1 mfprintffdhello s d scilab2 mclosefd if isdefeditor funptreditor0 then editorTMPDIRtexttxt end mfprintf0stderr output mfprintf6stdout output See Also mclose meof fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete printfconversion 475 Name mscanf reads input from the standard input interface to the C scanf function mfscanf reads input from the stream pointer stream interface to the C fscanf function msscanf reads its input from the character string interface to the C sscanf function nv1vnmfscanfniterfdformat Lmfscanfniter fdformat nv1vnmscanfniter format Lmscanfniterformat nv1vmmsscanfniterstrformat Lmsscanfniter strformat Parameters format a Scilab string describing the format to use to write the remaining operands The format operand follows as close as possible the C printf format operand syntax as described in scanfconversion fd The fd parameter returned by the function mopen is used as a file descriptor its a positive inte ger The value 1 refers to the last opened file str a Scilab string or string vector niter an integer the number of times the format as to be used n an integer the number of data read or 1 if EOL has been encountered before any datum has been read vi Each function reads characters interprets them according to a format and stores the results in its output arguments If more than n output arguments are provided the last ones vn1vm are set to empty matrices L if all data are homogeneous they are stored in a unique vector which is returned otherwise subse quences of same data type are stored in matrices and an mlist with type cblock containing all the built matrices is returned Description The mfscanf function reads characters from the stream fd The mscanf function reads characters from Scilab window The msscanf function reads characters from the Scilab string str The niter optional argument specifies how many time the format has to used One iteration produces one line in the output matrix If niter1 the function iterates up to the end of file The niter default value is 1 comments about precision mscanf 476 mfscanf is based on C function fscanf If you use f g e as format your datas will be cast to float and returned in a scilab variable This scilab variable is a double then you can have some precision errors In this case it is better to use lg format Examples Simple use s1 13 a string nabmsscanfsi e Lmsscanfsi e Formats samples msscanf 12 cccc scan characters msscanf0xabcx scan with hexadecimal format msscanf012345abczoo09abcs notation reading float and double msscanf4345988g4345988 scan as float msscanf4345988lg4345988 scan as double scanning multiline data files create a file with data umopenTMPDIRfoow t001pimfprintfu63f 63f tsint mcloseu umopenTMPDIRfoor open the file for reading read the file line by line nabmfscanfue e first line using mutiple LHS syntax lmfscanfue e second one using single LHS syntax use niter to read 5 more lines lmfscanf5ue e use niter1 to read up to the end of file lmfscanf1ue e mcloseu close the file scanning multiline strings vectors use niter to scan a string vector nNamesAgesmsscanf1Alain 19Pierre 15Tom 12s d Dmsscanf1Alain 19Pierre 15Tom 12s d typeofD NamesD1 strings mscanf 477 AgeD2 numerical values See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mput str mscanf mseek mtell mdelete scanfconversion 478 Name mget reads byte or word in a given binary format and convert to double mgeti reads byte or word in a given binary format return an int type xmgetntypefd xmgetintypefd Parameters n a positive scalar The number of items to be read fd a scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 type a string Give the binary format used to write all the entries of x x a vector of floating point or integer type numbers Description The mget function reads data in the input specified by the stream parameter fd and returns a vector of floating point data The mgeti function reads data in the input specified by the stream parameter fd and returns a vector of integer data Data is read at the position at which the file pointer is currently pointing and advances the indicator appropriately The type parameter is a conversion specifier which may be set to any of the following flag characters with default value l Note On Windows default behavior is to skip byte 13 0x0D mopen should be called with the b option eg fd1mopenfile1rb so that all bytes will be read without exception Data type d double f float l long i int s short c character Optional flag mget 479 u unsigned in combination with one of the above types l little endian in combination with one of the above types b big endian in combination with one of the above types Bytes read are automatically swapped if necessary by checking littleendian status This default swapping behavior can be suprressed by adding a flag in the mopen function Formats l d and f are only valid with the mget function Examples file1 test1bin file2 test2bin fd1mopenfile1wb fd2mopenfile2wb mput1996ullfd1 mput1996ullfd2 mclosefd1 mclosefd2 fd1mopenfile1rb if 1996mget1ullfd1 writeio2Bugend fd2mopenfile2rb if 1996mget1ullfd2 writeio2Bugend mclosefd1 mclosefd2 See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mgetl mgetstr mopen mprintf mput mputl mputstr mscanf mseek mtell mdelete 480 Name mgetl read lines from an ascii file txtmgetlfiledesc m Parameters filedesc a character string giving the file name or a logical unit returned by mopen m an integer scalar number of lines to read Default value is 1 txt a column vector of string Description mgetl function allows to read a lines from an ascii file If m is omitted or is 1 all lines till end of file occurs are read If m is given mgetl tries to read exactly m lines This option is useful to sequentialy read part of a file In this case if an end of file EOF occurs before m lines are read the read lines are returned it is possible to check if EOF had occured using the meof function issued mgetl allows to read files coming from Unix Windows or Mac operating systems Examples mgetlSCIetcscilabstart5 mgetl SCImoduleselementaryfunctionsmacroserfsci fdmopenSCIetcscilabstartr mgetlfd10 mclosefd See Also mputl mclose mfscanf mget mput mgetstr mopen read Authors S Steer 481 Name mgetstr read a character string strmgetstrn fd Parameters n a positive scalar The number of character to read fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 str a character string Description mgetstr function allows to read a character string in a binary file If EOF is reached before read com pletion only the properly read values will be returned Examples open file descriptor as text with read mode fdr mopenSCIACKNOWLEDGEMENTSrt get 100 characters of fdr strs1 mgetstr100 fdr get 200 next characters of fdr strs2 mgetstr200 fdr close file descriptor mclosefdr See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mput str mscanf mseek mtell mdelete 482 Name mkdir Make new directory mkdirdirname mkdirparentdirnewdir statusmkdir statusmsgmkdir Description mkdirdirname creates the directory dirname in the current directory if dirname represents a rela tive path Otherwise dirname represents an absolute path and mkdir attempts to create the absolute directory dirname mkdirparentdirdirname creates the directory dirname in the existing directory parentdir where parentdir is an absolute or relative pathname statusmessage mkdirdirname creates the directory dirname in the existing directory parentdir returning the status a message Here status is 1 for success 2 if it already exists 2 if it is a filename and 0 otherwise Examples Absolute pathname mkdirTMPDIRmkdirexample1 status2 mkdirTMPDIRmkdirexample2 status3msg3 mkdirTMPDIRmkdirexample3 Absolute pathname parentdir dirname status4msg4 mkdirTMPDIRmkdirexample4 Relative pathname cd TMPDIR status5msg5 mkdirmkdirexample5 status6msg6 mkdirmkdirexample5mkdirexample6 See Also cd dir rmdir Authors AC 483 Name mopen open a file fderrmopenfile mode swap Parameters file a character string The pathname of the file to open mode a character string that controls whether the file is opened for reading r writing w or appending a and whether the file is opened for updating The mode can also include a b parameter to indicate a binary file swap a scalar If swap is present and swap0 then automatic bytes swap is disabled err a scalar Error indicator see merror fd scalar The fd parameter returned by the function mopen is used as a file descriptor its a positive integer Description mopen may be used to open a file in a way compatible with the C fopen procedure Without swap argument the file is supposed to be coded in little endian IEEE format and data are swaped if nec essary to match the IEEE format of the processor The mode parameter controls the access allowed to the stream The parameter can have one of the following values In this list of values the b character indicates a binary file r Opens the file for reading rb Opens a binary file for reading rt Opens a text file for reading w Creates a new file for writing or opens and truncates a file to zero length wb Creates a new binary file for writing or opens and truncates a file to zero length wt Creates a text binary file for writing or opens and truncates a file to zero length a or ab Appends opens a file for writing at the end of the file or creates a file for writing r or rb Opens a file for update reading and writing mopen 484 w or wb Truncates to zero length or creates a file for update a or ab Appends opens a file for update writing at the end of the file or creates a file for writing When you open a file for update you can perform both input and output operations on the resulting stream However an output operation cannot be directly followed by an input operation without a filepositioning operation mseek function Also an input operation cannot be directly followed by an output operation without an intervening file positioning operation unless the input operation encounters the end of the file When you open a file for append that is when the mode parameter is a or a it is impossible to overwrite information already in the file You can use the fseek function to reposition the file pointer to any position in the file but when output is written to the file the current file pointer is ignored All output is written at the end of the file and the file pointer is repositioned to the end of the output To open files in a way compatible with Fortran like functions use function file open a SCIACKNOWLEDGEMENTS as text and read only fdr mopenSCIACKNOWLEDGEMENTSrt read five lines of fdr mgetlfdr 5 another way to read file here read five words mfscanf5fdrs close file descriptor associated to SCIACKNOWLEDGEMENTS as text and read only mclosefdr open a file as text with write property fdw mopenTMPDIRwritetxtwt write a line in fdw mputlThis is a line of text fwdw mclosefdw read text fdr2 mopenTMPDIRwritetxtrt mgetlfdr2 mclosefdr2 read write a file as binary first we write file fdwb mopenTMPDIRwritereadbinwb put values as binary mput2003lfdwb mput2008ifdwb mput2012sfdwb mput98cfdwb close file descriptor associated to TMPDIRwritereadbin mclosefdwb mopen 485 we read file fdrb mopenTMPDIRwritereadbinrb mgetfdrb l mgetfdrb i mgetfdrb s mgetfdrb c mclosefdrb See Also mclose merror meof mfprintf fprintfMat mfscanf fscanfMat mget mgetl mgetstr mopen mprintf mput mputl mputstr mscanf mseek mtell mdelete 486 Name movefile Move file or directory movefilesourcedestination statusmessage movefilesourcedestination Description movefilesourcedestination moves the file or directory source and subdirectories to the file or directory destination If source is a directory destination can not be a file movefile replaces existing files without warning status message movefilesourcedestination moves source to destination returning the status and a message Whatever the operating system if the move succeeds the status is 1 and the message is empty if the move fails the status is 0 and the message is not empty Examples copyfileSCIetcscilabstartTMPDIRscilabstart statusmessage movefileTMPDIRscilabstartTMPDIRrenamedscilabstart See Also copyfile Authors Allan CORNET 487 Name mput writes byte or word in a given binary format mputx typefd Parameters x a vector of floating point or integer type numbers fd scalar The fd parameter returned by the function Default value is 1 which stands for the last mopen opened file type a string Give the binary format used to write all the entries of x Description The mput function writes data to the output specified by the stream parameter fd Data is written at the position at which the file pointer is currently pointing and advances the indicator appropriately The type parameter is a conversion specifier which may be set to any of the following flag characters with default value l lisuluiusdfcuc for writing respectively a long an int a short an unsigned long an unsigned int an unsigned short a double a float a char and an unsigned char The bytes which are wrote are automatically swapped if necessary by checking littleendian status in order to produce machine independent binary files in littleendian mode This default swapping mode can be suppressed by adding a flag in the mopen function l or b It is also possible to write in littleendian or bigendian mode by adding a l or b character at the end of a type specification For example db will write a double in bigendian mode Examples filen testbin mopenfilenwb mput1996lmput1996imput1996smput98c force littleendian mput1996llmput1996ilmput1996slmput98cl force bigendian mput1996lbmput1996ibmput1996sbmput98cb mclose mopenfilenrb if 1996mget1l then pauseend if 1996mget1i then pauseend if 1996mget1s then pauseend if 98mget1c then pauseend mput 488 force littleendian if 1996mget1ll then pauseend if 1996mget1il then pauseend if 1996mget1sl then pauseend if 98mget1cl then pauseend force bigendian if 1996mget1lb then pauseend if 1996mget1ib then pauseend if 1996mget1sb then pauseend if 98mget1cb then pauseend mclose See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetl mgetstr mopen mprintf mputl mputstr mscanf mseek mtell mdelete 489 Name mputl writes strings in an ascii file r mputltxt filedesc Parameters r returns t or f to check if function has correctly written on the file filedesc A character string giving the name of the file or a logical unit returned by mopen txt a vector of strings Description mputl function allows to write a vector of strings as a sequence of lines in an ascii file Examples fd mopenTMPDIRtextmputltxtwt mputlHello Worldfd mclosefd fd mopenTMPDIRtextmputltxtrt dispmgetlfd mclosefd See Also mget mgetl mclose mfprintf mput mputstr mopen write Authors S Steer Allan CORNET 490 Name mputstr write a character string in a file mputstrstr fd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 str a character string Description mputstr function allows to write a character string in a binary file See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 491 Name mseek set current position in binary file mseekn fd flag Parameters n a positive scalar The offset from origin in number of bytes fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 flag a string specifies the origin Default value set Description The function mseek sets the position of the next input or output operation on the stream fd The new position is at the signed distance given by n bytes from the beginning from the current position or from the end of the file according to the flag value which can be set cur or end mseek allows the file position indicator to be set beyond the end of the existing data in the file If data is later written at this point subsequent reads of data in the gap will return zero until data is actually written into the gap mseek by itself does not extend the size of the file Examples file3test3bin fd1 mopenfile3wb for i110 mputid end mseek0 mput678d mseek0fd1end mput932d mclosefd1 fd1 mopenfile3rb resmget11d res1111 res11678res1932 if res1res writeio2Bugend mseek0fd1set trying to read more than stored data res1mget100dfd1 if res1res writeio2Bugend meoffd1 mclearerrfd1 mclosefd1 See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 492 Name mtell binary file management mtellfd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 Description The function mtell returns the offset of the current byte relative to the beginning of the file associated with the named stream fd See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 493 Name pathconvert pathnames convertion between posix and windows pathspathconvertpaths flagtrail flagexpand type Parameters paths a string matrix giving a set of pathnames flagtrail boolean optional parameters Its default value is TRUE flagexpand boolean optional parameter Its default value depends on the MSDOS variable type a string u or w Description pathconvert can be used to convert a set of pathnames given by a string matrix paths from windows native filename to posixstyle pathnames and back The target style is given by the optional string type which can be u for Unix or w for Windows The default style is set according to the value of MSDOS If MSDOS is TRUE resp FALSE then default type is w resp u Windows pathnames starting with name are converted to pathnames starting with cyg drivename using the cygwin convention flagtrail is an optional boolean parameter When its value is TRUE default value a trailing separator or is added at the end of the path if it was missing If flagtrail is set to FALSE the trailing separator is removed flagexpand is an optional boolean parameter When its value is TRUE leading strings like HOME SCI or are expanded using environment variables Examples pathconvertSCImodulesfileiomacrosfoosciffu pathconvertSCImodulesfileiomacrosfoosciffw pathconvertSCImodulesfileiomacrosfoosciftw pathconvertHOMEmodulesfileiomacrosfooscittw pathconvertctmpftu pathconvertcygdrivectmpffw See Also basename listfiles 494 Name pathsep returns path separator for current platform s pathsep Parameters s a string Description returns path separator on Linux or on Windows Examples pathsep Authors AC 495 Name pwd print Scilab current directory pwd get Scilab current directory pwd xpwd Description pwd returns in ans the Scilab current directory xpwd returns in x the Scilab current directory Examples pwd xpwd See Also chdir cd 496 Name removedir Remove a directory removedirdirname status removedirdirnames Description removedirdirname removes the directory dirname from the current directory If the directory is not empty files and subdirectories are removed If dirname is not in the current directory specify the relative path to the current directory or the full path for dirname status removedirdirname removes the directory dirname and its contents from the current direc tory returning the status Here status is T for success and is F for error removedir is used by rmdir Examples createdirSCIHOMEDirectorytest removedirSCIHOMEDirectorytest See Also mkdir rmdir Authors AC 497 Name rmdir Remove a directory rmdirdirname rmdirdirnames statusmessage rmdirdirnames Description rmdirdirname removes the directory dirname from the current directory If the directory is not emp ty you must use the s argument If dirname is not in the current directory specify the relative path to the current directory or the full path for dirname rmdirdirnames removes the directory dirname and its contents from the current directory status message rmdirdirnames removes the directory dirname and its contents from the current directory returning the status and a message Here status is 1 for success and is 0 for error Examples mkdirSCIDirectory rmdirSCIDirectory See Also cd dir mkdir Authors AC 498 Name saveformat format of files produced by save Description Variables are saved by Scilab with the save function in the following format each variable record is appended consecutively to the file The variable record begins with 6 long integer holding the variable name in encoded format see the Remarks section below After that comes the variable type long integer then depending on it for Floating matrices type 1 rowsize m a long integer columnsize n a long integer realcomplex flag it a long integer in 01 data nmit1 doubles Polynomials type 2 and Size implicit indices type 129 rowsize m a long integer columnsize n a long integer realcomplex flag it long integer in 01 formal variable name 16 bytes indextable mn1 long integers data N1it1 doubles where N is the value of the last entry of the indextable Booleans type 4 rowsize m a long integer columnsize n a long integer data nm long integers Floating sparse matrices type 5 rowsize m a long integer columnsize n a long integer realcomplexflag it a long integer in 01 totalnumberofnonzeroelements nel a long integer numberofnonzeroelementsperrow m long integers columnindexnonzeroelements nel long integers nonzerovalues nelit1 doubles Boolean sparse matrices type 6 rowsize m a long integer columnsize n a long integer unused it a long integer saveformat 499 totalnumberofnonzeroelements nel a long integer numberofnonzeroelementsperrow m long integers columnindexnonzeroelements nel long integers Matlab sparse matrix type 7 rowsize m a long integer columnsize n a long integer realcomplexflag it a long integer in 01 totalnumberofnonzeroelements nel a long integer numberofnonzeroelementspercolumn n long integers rowindexnonzeroelements nel long integers nonzerovalues nelit1 doubles Integer matrices type 8 rowsize m a long integer columnsize n a long integer integertype a long integer 124 or 111214 for signed and unsigned 124 bytes integers data nm bytes for integertype 1 or 11 nm short integers for integertype 2 or 12 nm long integers for integertype 4 or 14 handles type 9 version 4 bytes rowsize m a byte columnsize n a byte data mn serializationrecords A serializationrecord is a flat representation of the C data structure associated with the corre sponding graphic object Each graphic object is defined by a recursive set of properties see the get function The saved serializationrecord of a graphic object is structured as follow typelength n a byte type n bytes the ascii codes of the type name propertyvalues record variable length Strings type 10 rowsize m a long integer columnsize n a long integer indextable nm1 long integers data N long integers the Scilab encoding of the characters see code2str where N is the value of the last entry of the indextable Uncompiled functions type 11 nout long integer saveformat 500 lhsnames 6nout long integers see the Remarks section below nin long integer rhsnames 6nin long integers see the Remarks section below codelength N a long integer code N long integers Compiled functions type 13 nout long integer lhsnames 6nout long integers see the Remarks section below nin long integer rhsnames 6nin long integers see the Remarks section below pseudocodelength N a long integer pseudocode N long integers Libraries type 14 pathlength np a long integer pathname np long integers the path character codes sequence see code2str number of names nn long integer names 6nn long integers see the Remarks section below Lists type 15 tlists type 16 mlists type 17 number of fields n a long integer index n1 long integers variablessequence n variables each one written according to its format Pointers type 128 Not handled Function pointers type 130 functionptr a long integersee funptr functionnamecode 6 long integerssee the Remarks section below Remarks Numbers long interger short integers double are stored using the little endian convention The variable names are stored as a sequence of 6 long integers with a specific encoding see the cvnamef file for details See Also save load listvarinfile type typeof Authors compiled by Enrico Segre 501 Name scanf Converts formatted input on standard input v1vnscanf format Parameters format Specifies the format conversion Description The scanf functions get character data on standard input io1 interpret it according to a format and returns the converted results The format parameter contains conversion specifications used to interpret the input The format parameter can contain whitespace characters blanks tabs newline or formfeed that except in the following two cases read the input up to the next nonwhitespace character Unless there is a match in the control string trailing white space including a newline character is not read Any character except percent sign which must match the next character of the input stream A conversion specification that directs the conversion of the next input field see scanfconversion for details See Also printf read fscanf sscanf scanfconversion 502 Name scanfconversion scanf sscanf fscanf conversion specifications Description Each conversion specification in the format parameter contains the following elements The character percent sign The optional assignment suppression character An optional numeric maximum field width A conversion code The conversion specification has the following syntax widthsizeconvcode The results from the conversion are placed in vi arguments unless you specify assignment suppres sion with asterisk Assignment suppression provides a way to describe an input field that is to be skipped The input field is a string of nonwhitespace characters It extends to the next inappropriate character or until the field width if specified is exhausted The conversion code indicates how to interpret the input field You should not specify the vi param eter for a suppressed field You can use the following conversion codes Accepts a single percent sign input at this point no assignment is done d i Accepts a decimal integer u Accepts an unsigned decimal integer o Accepts an octal integer x Accepts a hexadecimal integer efg Accepts a floatingpoint number The next field is converted accordingly and stored through the corresponding parameter which should be a pointer to a float The input format for floatingpoint numbers is a string of digits with the following optional characteristics It can be a signed value It can be an exponential value containing a decimal point followed by an exponent field which consists of an E or an e followed by an optionally signed integer It can be one of the special values INF NaN scanfconversion 503 s Accepts a string of characters c character value is expected The normal skip over white space is suppressed lg get value as a double See Also scanf scanf fscanf Parte VI Biblioteca de Gráficos 505 Name GlobalProperty Customização de aparência dos objetos curvas superfícies num comando plot ou surf Nenhuma GlobalProperty é um argumento opcional que pode ser utilizado dentro de um comando plot ou surf Permite uma customização global de todas as novas linhas esboçadas respectivamente superfícies Deve ser fornecido como o parPropertyName PropertyValue Vários pares podem ser ajustados ao mesmo tempo PropertyName deve ser um string definido a propriedade a ser ajustada PropertyValue pode ser um real um inteiro ou um string um escalar ou matriz de dependendo do tipo de propriedade usada Por exemplo para especificar um estilo de linha traço longo vermelho cor com marca diamante marca a seqüência deve ser ColoredLineStMarkerdiam Como você pode ver uma escrita completa dos nomes e valores das propriedades não é necessária mas os argumentos especificados em qualquer ordem não podem ser ambíguos Além disso a especificação dos strings não diferencia letras minúsculas de maiúsculas GlobalProperty é predominante em todos os LineSpec anteriormente citados Descrição Aqui está uma lista completa dos PropertyName que você pode especificar utilizando plot ou surf e seus associados disponíveis PropertyValue Se não forem especificadas estas propriedades estão disponíveis para ambos objetos Polyline e Fac3d criados respectivamente por plot e surf e como dito anteriormente eles são aplicados aos novos objetos criados linhas ou superfícies Algumas vezes você pode ter dois PropertyName correspondentes a uma propriedade o primeiro é o nome Matlab equivalente O segundo é o nome padrão utilizado pelo Scilabie Color ou Foreground para uma linha ver abaixo CData or ColorData uma matriz de reais especificando as cores em todos os pontos definidos pela matriz Z TEsta propriedade esta ligada à propriedade datacolor do objeto ver surfaceproperties Note que esta propriedade está disponível para superfícies apenas CDataMapping ou ColorDataMapping um string com valor scaled ou direct Se um datacolor estiver ajustado ca da índice de cor especifica um único valor para cada vértice cdatamapping determina se estes índices estão em escala para serem mapeados linearmente no mapa de cores corrente modoscaled ou aponta diretamente para este mapa de cores modo direct Esta pro priedade é útil quando colorflag é igual a 23 ou 4 Note que esta propriedade só existe em entidades Fac3d Note também que plot3d tem modo direct por padrão e surf tem modo scaled por padrão Clipping um string on ou off definindo o modo de recorte on por padrão É equivalente à propriedade clipstate property Este campo contém a propriedade ver polylineproperties Note que esta propriedade ainda não está disponível para entidades de superfícies Color ou Foreground um string definindo uma cor conhecida ver colorlist ou um vetor 1x3 ou 3x1 RGB defin do um número de cor O número de cor é dado como uma tripla R G B correspondendo respec tivamente a to às intensidades de vermelho verde e azul entre 0 e 1 Esta propriedade está lig ada à propriedade foreground do objeto ver polylineproperties Aviso Color não está disponível para objetos superfícies A propriedade Foregroundexiste para objetos superfícies mas está ligada à propriedade do Matlab EdgeColor ver surfaceproperties EdgeColor or Foreground um string definindo uma cor conhecida ver colorlist ou um vetor 1x3 or 3x1 RGB definindo um número de cor O número de cor é dado pela tripla R G B correspondendo respectivamente a to às intensidades de vermelho verde e azul entre 0 e 1 Esta propriedade está ligada à propriedade foreground da superfície ver surfaceproperties Aviso para poligonais a propriedade Foreground existe com um signficado diferente ver acima e EdgeColor não existe FaceColor um string com valor none flat ou interp especificando o modo como as cores das facetas são renderizadas Quando none é selecionado uma malha da superfície é desenhada se flat modo padrão é selecionado os valores Fac3d colordata determinam uma cor GlobalProperty 506 por faceta utilizando a cor do vértice da faceta Se o valor é interp uma gradação interpolada é feita na faceta utilizando colordata para determinar a cor em cada vértice da faceta LineStyle esta propriedade deve ser um string definindo um estilo de linha Esta propriedade está ligada à propriedade linestyle do objeto ver polylineproperties ou surfaceproperties Especificador Estilo de linha linha sólida padrão linha tracejada linha pontilhada linha tracejadapontilhada none nenhuma linha Marker or MarkStyle um string definindo um tipo de marca Note que se você especificar uma marca sem um es tilo de linha ambas linhas com valor padrão sólido hablitado e marcas são desenhadas Esta propriedade está ligada às propriedades markstyle e markmode do objeto ver polylineproperties ou surfaceproperties Especificador Tipo de marca sinal de mais o círculo asterísco ponto x cruz square or s quadrado diamond or d rombo diamante triângulo para cima v triângulo para baixo triângulo para direita triângulo para esquerda pentagram estrela de cinco pontas pentagrama none sem marca padrão MarkerEdgeColor ou MarkForeground um string definindo uma cor conhecidaver colorlist ou um vetor 1x3 ou 3x1 RGB definindo um número de cor O número de cor é dado pela tripla R G B correspondendo respectivamente às intensidades de vermelho verde e azul entre 0 e 1 esta propriedade está ligada à propriedade markforeground do objeto ver polylineproperties ou surfaceproperties MarkerFaceColor ou MarkBackground um string definindo uma cor conhecida ver colorlist ou um vetor 1x3 ou 3x1 RGB definindo um número de cor O número de cor é dado pela tripla R G B correspondendo respectivamente às intensidades de vermelho verde e azul entre 0 e 1 Esta propriedade esta ligada à propriedade markbackground do objeto ver polylineproperties ou surfaceproperties MarkerSize ou MarkSize um escalar definindo o tamanho do marcador em unidade point Esta propriedade está ligada a propriedade marksize do objeto com marksizeunit habilitado para point ver polylineproperties ou surfaceproperties GlobalProperty 507 Visible um string on ou off definindo o modo de visibilidade on por padrão Esta propriedade está ligada à propriedade visible do objeto ver polylineproperties ou surfaceproperties X data um vetor ou matriz de reais redefinindo os dados fornecidos para todas as linhas ou superfícies esboçadas A respeito das dimensões note que estes novos dados devem corresponder a todos os anteriores especificados por X isto é todas as matrizes devem ter as mesmas dimensões Esta propriedade está ligada à propriedade datax do objeto ver polylineproperties ou surfaceproperties Y data um vetor ou matriz de reais redefinindo os dados fornecidos para todas as linhas ou superfícies esboçadas A respeito das dimensões note que estes novos dados devem corresponder a to dos os anteriores especificados por Y data isto é todas as matrizes devem ter as mesmas dimensões Esta propriedade está ligada à propriedade datay do objeto ver polylineproperties ou surfaceproperties Z data quando usado com plot um vetor ou matriz de reais adicionando dados Z para todas as lin has esboçadas com surf uma matriz de reais redefinindo os dados fornecidos para todas as superfícies A respeito das dimensões note que estes novos dados devem corresponder a todos os anteriores especificados por X e Y data Esta propriedade está ligada à propriedade dataz do objeto ver polylineproperties ou surfaceproperties Exemplos com o comando plot x110 Init plotxsinxcoloredlinestmarkermarkeredgcyanmarkerFaceyellowmarkersize5 clf a ordem das combinações e PropertyNamePropertyValue não importa plotxsinxmarkerpmarkerfaccyanmarkersiz10 clf a combinação de LineSpec com GlobalProperty mostra a predominância de Global Property plotxxxcyacolorgrlinestylemarkersqmarkersize6markforegrounredmarkbackgro02 05 06 clf múltiplos esboços com diferentes LineSpecs e finalmente alguns GlobalProperty clf t0pi202pi plottsintrotcostcyatabssintmomarkstyldiam com o comando surf Z 00001 00013 00053 00299 01809 02465 01100 00168 00008 00000 00005 00089 00259 03673 18670 24736 10866 01602 00067 00000 00004 00214 01739 03147 40919 64101 27589 02779 00131 00020 00088 00871 00364 18559 14995 22171 02729 08368 02016 00130 00308 04313 17334 01148 30731 04444 26145 24410 04877 00301 GlobalProperty 508 00336 04990 23552 21722 08856 00531 26416 24064 04771 00294 00137 01967 08083 02289 33983 31955 24338 12129 02108 00125 00014 00017 03189 27414 71622 71361 31242 06633 00674 00030 00002 00104 01733 10852 26741 26725 11119 01973 00152 00005 00000 00012 00183 01099 02684 02683 01107 00190 00014 00000 clf fgcf ffiguresize 610724 subplot211 surfZfacecolinterpydat101110edgecolmage subplot212 surfZedgecobmarkerdmarkersiz9markerfackxdata5041 Ver Também LineSpec plot surf clf polylineproperties surfaceproperties Autor FLeray 509 Name Graphics Resumo da biblioteca de gráficos Desenhos 2d plot2d esboço 2d plot2d2 esboço 2d funções de degraus plot2d3 esboço 2d barras veticais plot2d4 esboço 2d setas fplot2d esboço 2d de uma curva definida por uma função champ esboço de campo vetorial 2d champ1 campo vetorial 2d com setas coloridas fchamp campo direcional de uma EDO 2d de primeira ordem contour2d curvas de nível de uma superfície em um esboço 2d fcontour2d curvas de nível de uma superfície definida por uma função em um esboço 2d grayplot esboço 2d de uma superfície utilizandose cores fgrayplot esboço 2d de uma superfície definida por uma função utilizando cores Sgrayplot esboço 2d suave de uma superfície utilizando cores Sfgrayplot esboço 2d suave de uma superfície definida por uma função utilizando cores xgrid adiciona um grid em um esboço 2d errbar adiciona barras de erro veriticais a um esboço 2d histplot esboça um histograma Matplot esboço 2d de uma matriz utilizandose cores Graphics 510 Desenhos 3d plot3d esboço 3d de uma superfície plot3d1 esboço 3d em níveis de cinza ou de cores de uma superfície fplot3d esboço 3d de uma superfície definida por uma função fplot3d1 esboço 3d em escala de cinza ou colorido de nível de uma superfície definida por uma função param3d esboço 3d de uma curva parametrizada param3d1 esboço 3d de curvas parametrizadas contour curvas de nível em uma superfície 3d fcontour curvas de nível sobre uma superfície 3d definida por uma função hist3d representação 3d de um histograma genfac3d computa facetas de uma superfície 3d eval3dp computa facetas 3d de uma superfície parametrizada geom3d projeção 3d para 2d após um esboço 3d Desenho de linhas e poligonais xpoly desenha uma poligonal ou um polígono xpolys desenha um conjunto de poligonais ou polígonos xrpoly desenha um polígono regular xsegs desenha segmentos desconexos xfpoly preenche um polígono xfpolys preenche um conjunto de polígonos Desenho de retângulos xrect desenha um retângulo Graphics 511 xfrect preenche um retângulo xrects desenha ou preenche um conjunto de retângulos Desenho de arcos xarc esboça parte de uma elipse xarcs desenha partes de um conjunto de elipses xfarc preenche parte de uma elipse xfarcs preenche partes de um conjunto de elipses Desenho de setas xarrows desenha um conjunto de setas Strings xstring imprime strings xstringl computa uma caixa que cerca strings xstringb escreve strings em uma caixa xtitle adidciona títulos a janelas de gráficos titlepage adiciona título no meio de uma janela de gráficos xinfo escreve um string de informação na subjanela de mensagens Molduras e eixos graduate graduação de eixos plotframe esboça uma moldura com escalas e grides Esta função está obsoleta Transformações de coordenadas isoview ajusta escalas para esboço isométrico não muda o tamanho da janela square ajusta escalas para esboço isométrico muda o tamanho da janela Graphics 512 scaling transformação afim de um conjunto de pontos rotate rotação de um conjunto de pontos xsetech ajusta a subjanela de uma janela de gráficos para esboço subplot divide uma janela de gráficos em uma matriz de subjanelas xgetech retorna a escala de gráficos corrente xchange conversão de coordenadas reais para coordenadas pixeis Cores colormap mapa de cores getcolor abre um diálogo que exibe as cores no mapa de cores corrente addcolor adiciona cores novas ao mapa de cores corrente graycolormap mapa de cores linear cinza hotcolormap mapa de cores de vermelho para amarelo Contexto gráfico xset ajusta valores para o contexto gráfico Função obsoleta xget retorna valores correntes do contexto gráfico xlfont carrega uma fonte em um contexto gráfico ou pergunta a fonte carregada getsymbol Diálogo para a seleção de um símbolo e seu tamanho Gravação e carregamento xsave salva gráficos em um arquivo xload carrega gráficos salvos xs2fig envia gráficos para um arquivo em sintaxe Xfig Graphics 513 xs2gif envia gráficos a um arquivo em sintaxe GIF xs2ppm envia gráficos para um arquivo em sintaxe PPM Primitivas gráficas xbasc limpa uma janela de gráficos xclear limpa janela de gráficos driver seleciona um driver gráfico xinit inicialização de um driver de gráficos xend termina uma sessão de gráficos xbasr desenha novamente uma janela de gráficos replot redesenha a janela de gráficos corrente com novas fronteiras xpause suspende o Scilab xselect restaura a janela de gráficos corrente xdel deleta uma janela de gráficos winsid retorna a lista de janelas de gráficos xname muda o nome da janela de gráficos corrente Posição do mouse xclick espera por um clique do mouse locate seleção pelo mouse de um conjunto de pontos xgetmouse retorna os eventos de mouse e posição corrente Editor interativo editcurv editor interativo de curvas gráficas Graphics 514 grmenu editor gráfico interativo simples sd2sci estrutura grmenu para conversor de instrução Scilab Funções gráficas e controle automático bode diagrama de Bode gainplot esboço de magnitude nyquist diagrama de Nyquist mcircle esboço de um Mcírculo chart carta de Nichols black diagrama de Black evans lugar geométrico das raízes Evans sgrid esboça linhas de grid de um splano plzr esboço de pólozero zgrid esboço de um zgrid 515 Name LineSpec Customização rápida de linhas que aparecem em um esboço Nenhuma LineSpec é um argumento opcional que pode ser utilizado dentro de um comando plot para customizar os aspectos de cada linha nova Deve ser fornecido um string concatenado contendo as informações sobre cor estilo de linha e marcas É muito útil para especificar de forma rápida estas propriedades de linha básicas Para especificar uma linha vermelha de traço longo com marcas de rombo o string pode ser rdiam Como você pode ver não é necessário escrita completa de cada de cada valor de propriedade mas o string que é uma concatenação em qualquer ordem destas três propriedades não pode conter ambigüidade Além disso a especificação de strings não diferencia letras maiúsculas de minúsculas Descrição Aqui está uma lista completa dos tipos LineSpec que você pode especificar utilizando plot LineStyle um string definindo o estilo de linha Esta propriedade está ligada à propriedade linestyle do objeto ver polylineproperties especificador estilo de linha linha sólida padrão linha tracejada linha pontilhada linha tracejadapontilhada Color um string definindo a cor da linha Esta propriedade está ligada à propriedade foreground do objeto ver polylineproperties especificador cor r vermelho g verde b azul c ciano m magenta y amarelo k preto w branco Uma tabela de cores padrão é utilizada para colorir curvas esboçadas se você não especificar as cores nem com LineSpec nem com GlobalProperty Quando linhas múltiplas são desenhadas o comando plot automaticamente atribui em ciclos as cores a seguir R G B 0 0 1 0 05 0 1 0 0 0 075 075 075 0 075 075 075 0 025 025 025 LineSpec 516 Marker type um string definindo o tipo do marcador Note que se você especificar um marcador ou marca sem um estilo de linha apenas o marcador é desenhado Esta propriedade está ligada à propriedade do objeto markstyle e markmode do objeto ver polylineproperties especificador tipo de marcador sinal de mais o círculo asterísco ponto x cruz square ou s quadrado diamond ou d rombo ou diamante triângulo para cima v triângulo para baixo triângulo para a direita triângulo para a esquerda pentagram estrela de cinco pontas pentagrama none nenhum marcador padrão Exemplos x10110 inicialização plotxsinxr esboçando um linha de traços e pontos com um truângulo apontando para a direita centrado em cada ponto clf se você especificar um marcador sem um estilo de linha apenas a marca é desenhada plotxsinxd esboçando um linha de traços e pontos com um truângulo apontando para a direita centrado em cada ponto x110 Init a ordem das combinações não importa plotxxxcya múltiplos esboçoes com diferentes LineSpecs clf t0pi202pi plottsintrotcostcyatabssintmo Ver Também GlobalProperty plot clf Autor FLeray 517 Name Matplot esboço 2d de uma matriz utilizandose cores Matplotastrfrectnax Matplotaoptargs Parâmetros a matriz de reais de tamanho n1n2 optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes rect ajusta as fronteiras do esboço Se esta chave é fornecida nem frameflag ou strf é fornecido então o caractere y de strf é suposto como 7 Ver valores abaixo nax ajusta a definição dos grides Se esta chave é fornecida nem axesflag ou strf é forneci do então o caractere z cd strf é suposto como 1 Ver valores abaixo frameflag especifica como a moldura do esboço é computado O valor é um inteiro entre 0 e 8 Corre sponde ao caractere y de strf Ver abaixo axesflag especifica que tipo de eixos são desenhados ao redor do esboço O valor é um inteiro entre 0 e 5 Corresponde ao caractere z de strf Ver abaixo strf é um string de comprimento 3 xyz default o padrão é 081 x controls the display of captions x0 sem legendas x1 legendas são exibidas Elas são dadas pelo argumento opcional leg y controla a computação dos intervalos de coordenadas reais a partir dos valores mínimos re queridos Intervalos reais podem ser maiores que os requerimentos mínimos y0 sem computação o esboço utiliza a escala anterior ou padrão y1 a partir do argumento rect y2 a partir dos valores mínimomáximo dos dados x e y Matplot 518 y3 constrói uma escala isométrica a partir do argumento rect y4 constrói um esboço em escala isométrica a partir dos valores mínimomáximo dos dados x e y y5 aumentados para obtenção de bons eixos a partir do argumento rect y6 aumentados para obtenção de bons eixos a partir dos valores mínimomáximo dos dados x e y y7 como y 1 mas os anteriores são redesenhados para se utilizar a nova escala y8 como y 2 mas os anteriores são redesenhados para se utilizar a nova escala z controla a exibição de informação na moldura ao redor do esboço Se eixos são requeridos o número de tiques pode ser especificado pelo argumento opcional nax z0 nada é desenhado ao redor do esboço z1 eixos são desenhados o eixo y é exibido à esquerda z2 o esboço é cercado por uma caixa sem tiques z3 eixos são desenhados o eixo y é exibido à direita z4 eixos são desenhados centrados no meio da caixa de moldura z5 eixos são desenhados cruzandose no ponto 00 Se o ponto 00 não estiver den tro da moldura os eixos não aparecerão no gráfico rect este argumento é utilizado quando o segundo caractere y do argumento strf é 1 3 ou 5 É um vetor linha de tamanho quatro e fornece a dimensão da moldura rectxminyminxmaxymax nax este argumento opcional é utilizado quando o terceiro caractere z do argumento strf é 1 É um vetor linha de quatro entradas nxNxnyNy onde nx ny é o número de subgraduações no eixo x y axis e Nx Ny é o número de graduações no eixo x y Descrição As entradas da matriz inta são utilizadas como entradas do mapa de cor no mapa de cores corrente A cor associada a aij é utilizada para desenhar um pequeno quadrado de lado 1 com centro localizado em xjyn1i1 Entre com o comando Matplot para visualizar uma demonstração Matplot 519 Exemplos Matplot1 2 34 5 6 clf desenhando o mapa de cores corrente Matplot1xgetlastpattern Ver Também colormap plot2d Matplot1 Matplotproperties Autor JPhC 520 Name Matplot1 Esboço 2d de matrizes utilizando cores Matplot1arect Parâmetros a matriz de reais de tamanho n1n2 rect xminyminxmaxymax Descrição As entradas da matriz inta são utilizadas como entradas de mapa de cores no mapa de cores cor rente rect especifica um retângulo na escala corrente e a matriz é desenhada dentro deste retângulo Cada entrada da matriz será renderizada como um pequeno retângulo preenchido com sua cor asso ciada Exemplos primeiro exemplo clf axgcaobtendo o manipulador dos eixos correntes axdatabounds001010set the databounds axboxon desenha uma caixa a5ones1111 a2102104 a57572 primeira matriz no retângulo 1133 Matplot1a1133 aones1010 a 3trila 2a segunda matriz no retângulo 5678 Matplot1a5678 segundo exemplo animação n100 clf fgcfobtendo o manipulador da figura corrente fpixmaponmodo de buffer duplo axgcaobtendo o manipulador dos eixos corrente axdatabounds001010ajustando the databounds axboxon desenhando uma caixa showpixmap for knn aonesnn a 3trilak 2a a a a k1 3k100200 if kn then deletegceend Matplot1ak12k179 showpixmap enviando o buffer duplo para a tela end Matplot1 521 Ver Também colormap plot2d Matplot grayplot Matplotproperties Autor JPhC 522 Name Matplotproperties Descrição das propriedades da entidade Matplot Descrição A entidade Matplot é uma folha na hierarquia de entidades gráficas Representa esboços 2d de superfícies utilizando cores e imagens ver Matplot e Matplot1 parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Matplot deve ser do tipo Axes children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores Mat plot handles correntemente não possuem galhos visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o esboço é visível o valor da propriedade é on Se off o esboço não é desenhado na tela data este campo define uma matriz de cores mxn color utilizando o mapa de cores corrente A cor associada a colorij é utilizanda para se esboçar um pequeno quadrado de lado 1 com centro localizado em xjymi1 clipstate este campo contém o valor da propriedade clipstate para o Matplot o valor de clipstate pode ser off significa que o Matplot não é recortado clipgrf significa que o Matplot é recortado fora da caixa dos eixos on significa que o Matplot é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquer do largura altura define as porções do retângulo a ser exibido contudo o valor da propriedade clipstate será alterado userdata este campo pode armazenar qualquer variável Scilab na estrutura de dados do Matplot e recu perála Exemplos Matplot1xgetlastpattern egce obtendo a entidade corrente edataedata11 ordem inversa Ver Também set get delete grayplot Matplot Matplot1 graphicsentities grayplotproperties Matplotproperties 523 Autor FLeray 524 Name Sfgrayplot esboço 2d suave de uma superfície definida por uma função utilizando cores Sfgrayplotxyfoptargs Sfgrayplotxyf strf rect nax zminmax colminmax mesh colout Parâmetros xy vetores linhas de reais de tamanhos n1 e n2 f função do Scilab zfxy optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes strf rect nax zminmax colminmax mesh colout ver plot2d para os três primeiros e fec para os quatro últimos strfrectnax ver plot2d zminmax colminmax mesh colout ver fec Descrição Sfgrayplot é o mesmo que fgrayplot mas o esboço é suavizado A função fec é utilizada para suavização A superfície é esboçada assumindose que é linear em um conjunto de triângulos construídos a partir do grid aqui com n15 n23 A função colorbar pode ser utilizada para se visualizar a escala de cores mas você deve saber ou computar os valores mínimo e máximo Ao invés de Sfgrayplot você pode usar Sgrayplot este pode ser um pouco mais rápido Entre com o comando Sfgrayplot para visualizar uma demonstração Exemplos exemplo 1 esboço de 4 superfícies function zsurf1xy zxy endfunction function zsurf2xy zx2y2 endfunction function zsurf3xy zx3y2 endfunction function zsurf4xy zx2y2 endfunction xbasc xsetcolormapjetcolormap64hotcolormap64 x linspace1160 y linspace1160 Sfgrayplot 525 drawlater subplot221 colorbar11164 Sfgrayplotxysurf1strf041colminmax164 xtitlefxy xy subplot222 colorbar1165128 Sfgrayplotxysurf2strf041colminmax65128 xtitlefxy x2y2 subplot223 colorbar1265128 Sfgrayplotxysurf3strf041colminmax65128 xtitlefxy x3y2 subplot224 colorbar02164 Sfgrayplotxysurf4strf041colminmax164 xtitlefxy x2y2 drawnow xselect exemplo 2 esboço de surf3 e adição de algumas linhas de contorno function zsurf3xy zx3y2 endfunction xbasc x linspace1160 y linspace1160 xsetcolormaphotcolormap128 drawlater colorbar12 Sfgrayplotxysurf3strf041 fcontour2dxysurf301 0025 04style1 1 1strf000 xtitlefxy x3y2 drawnow xselect exemplo 3 esboço de surf3 e uso dos argumentos opcionais zminmax e colout para restringir o esboço em 05lt z lt 1 function zsurf3xy zx3y2 endfunction xbasc x linspace1160 y linspace1160 xsetcolormapjetcolormap128 drawlater zminmax 05 1 colors32 96 colorbarzminmax1zminmax2colors Sfgrayplotx y surf3 strf041 zminmaxzminmax colout0 0 colminmaxcolors fcontour2dxysurf305 1style1 1 1strf000 xtitlefxy x3y2 com partes abaixo de z 05 e acima de z 1 removidas drawnow xselect Ver Também fec fgrayplot grayplot Sgrayplot Autor JPhC 526 Name Sgrayplot esboço 2d suave de uma superfície utilizando cores Sgrayplotxyzoptargs Sgrayplotxyz strf rect nax zminmax colminmax mesh colout Parâmetros xy vetores linhas de reais de tamanhos n1 e n2 z matriz de reais de tamanho n1n2 zij é o valor da superfície no ponto xiyj optargs representa uma seqüência de declarações key1value1key2value2 onde key1 key2 podem ser um dos seguintes strf rect nax zminmax colminmax mesh colout strf é um string de comprimento 3 xyz por padrão strf 081 x controla a exibição de legendas x0 sem legendas x1 legendas são exibidas Elas são dadas pelo argumento opcional leg y controla a computação dos intervalos de coordenadas reais a partir dos valores mínimos re queridos Intervalos reais podem ser maiores que os requerimentos mínimos y0 sem computação o esboço utiliza a escala anterior ou padrão y1 a partir do argumento rect y2 a partir dos valores mínimomáximo dos dados x e y y3 construídos para uma escala isométrica a partir do argumento rect y4 construídos para uma escala isométrica a partir dos valores mínimomáximo dos dados x e y y5 aumentados para obtenção de bons eixos a partir do argumento rect y6 aumentados para obtenção de bons eixos a partir dos valores mínimomáximo dos dados x e y y7 como y 1 mas os anteriores são redesenhados para se utilizar a nova escala Sgrayplot 527 y8 lcomo y 2 mas os anteriores são redesenhados para se utilizar a nova escala z controla a exibição de informação na moldura ao redor do esboço Se eixos são requeridos o número de tiques pode ser especificado pelo argumento opcional nax z0 nada é desenhado ao redor do esboço z1 eixos são desenhados o eixo y é exibido à esquerda z2 o esboço é cercado por uma caixa sem tiques z3 eixos são desenhados o eixo y é exibido à direita z4 eixos são desenhados centrados no meio da caixa de moldura z5 eixos são desenhados cruzandose no ponto 00 Se o ponto 00 não estiver den tro da moldura os eixos não aparecerão no gráfico rect este argumento é utilizado quando o segundo caractere y do argumento strf é 1 3 ou 5 É um vetor linha de tamanho quatro e fornece a dimensão da moldura rectxminyminxmaxymax nax este argumento opcional é utilizado quando o terceiro caractere z do argumento strf ié 1 É um vetor linha de quatro entradas nxNxnyNy onde nx ny é o número de subgraduações no eixo x y axis e Nx Ny é o número de graduações no eixo x y zminmax colminmax mesh colout ver fec Descrição Sgrayplot é o mesmo que grayplot mas o esboço é suavizado A função fec é utilizada para suavização A superfície é esboçada assumindose que é linear em um conjunto de triângulos construídos a partir do grid aqui com n15 n23 A função colorbar pode ser utilizada para se visualizar a escala de cores O parâmetro zminmax é útil para propósitos de animação veja um exemplo depois e o parâmetro colminmax permite que o usuário escolha uma parte do mapa de cores corrente ver a página de ajuda de fec Entre com o comando Sgrayplot para visualizar uma demonstração Sgrayplot 528 Exemplos exemplo 1 x1010 y1010m rand2121 clf xsetcolormaphotcolormap64 Sgrayplotxym strf011 rect20202020 exemplo 2 tpi01pi msintcost clf xsetcolormapjetcolormap64 colorbar11 Sgrayplotttm strf041 exemplo 3 exibindo animação de costsinxsiny n 30 nt 100 x linspace02pin y linspace0pin2 z sinxsiny t linspace04pint xselect clf fgcf fcolormapjetcolormap64 fpixmapon colorbar11 Sgrayplotxycost1z strf042 zminmax11 cgceecchildren xtitleOlhos de Kaa for i 1nt edata3matrixcostiz11 showpixmap end fpixmapoff Ver Também fec fgrayplot grayplot Sfgrayplot colorbar Autor JPhC 529 Name addcolor adiciona cores novas ao mapa de cores corrente newaddcolorc Parâmetros new identificadores das cores definidas em c em uma nova tabela de cores c matriz com 3 colunas definição de cores RGB vermelho verde e azul Descrição addcolor adiciona novas cores fornecidas no argumento c ao mapa de cores corrente c deve ser uma matriz com três colunas R G B R é o componente vermelho G é o componente verde B é o componente azul cada entrada em c deve ser um número nãonegativo menor do que ou igual a 1 Os identificadores das novas cores são retornados em new Se uma cor definida em c já está presente no mapa de cores ela não será adicionada Examplos plot3d h gcf hcolormap jetcolormap16 addcolorname2rgbgrey255 Ver Também colormap name2rgb 530 Name alufunctions Funções de desenho de pixel Descrição src is the source ie the value of the pixel which we want to draw dst is the destination ie value of the pixel which is already drawn 0 clear ie 0 limpo 1 and ie src AND dst E 2 and reverse ie src AND NOT dst E NÃO e reverso 3 copy ie src cópia 4 and inverted ie NOT src AND dst NÃO E e invertido 5 noop ie dst 6 xor ie src XOR dst UM OU OUTRO 7 or ie src OR dst OU 8 nor ie NOT src AND NOT dst NÃO E NÃO nem um nem outro 9 equiv ie NOT src XOR dst NÃO UM OU O OUTRO equivalência 10 invert ie NOT dst NÃO 11 or reverse ie src OR NOT dst OU NÃO ou reverso 12 copy inverted ie NOT src cópia invertida 13 or inverted ie NOT src OR dst NÃO OU invertido 14 nand ie NOT src OR NOT dst NÃO OU NÃO pelo menos um não 15 set ie 1 ajustado 531 Name arcproperties Descrição das propriedades da entidade Arc arco Descrição A entidade Arc é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para elipses e partes de elipses preenchidas ou não parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Arc deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores arc não possuem galhos correntemente thickness este campo contém a propriedade de linha thickness espessura Deve ser um inteiro positivo linestyle o valor da propriedade linestyle deve ser um inteiro em 1 6 1 significa linha sólida e os demais valores significam tipos diferentes de tracejados linemode esta propriedade permite que se exiba ou não a linha representando o arco O valor pode ser on ou off fillmode se o valor da propriedade fillmode é on o arco é preenchido com a cor background de plano de fundo foreground este campo contém o valor padrão da propriedade foreground primeiro plano para desenhar ou preencher o arco Deve ser um índice de cor relativo ao mapa de cores corrente background este campo contém a cor usada para preencher o arco Deve ser um índice de cor relativo ao mapa de cores corrente data esta propriedade retorna as coordenadas do ponto superior esquerdo a largura e a altura do retângulo envolvente bem como os ângulos de froenteira do setor É a matriz xleftyup zupwidthheighta1a2 onde a1 e a2 são os ângulos de fronteira dados em graus Aviso nas versões do Scilab até a 412 a1 e a2 são dados em degree64 visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Se on o arco é desenhado se off o arco não é exibido na tela arcdrawingmethod Este campo controla o tipo de discretização utilizado para renderizar o arco Seu valor deve ser nurbs ou lines Se nurbs for selecionado o arco é renderizado utilizandose superfícies e curvas nurbs Isto resulta na exibição de uma superfície perfeita não importa qual o ponto de vista seja Se lines é selecionado então o arco é aproximado com um número constante de linhas Isto reduz o tempo de desenho mas pontas agudas podem aparecer em uma ampliação O uso do valor lines é desencorajado e só deve ser utilizado se for notada alguma perda na velocidade dos quadros ao se utilizar o valor nurbs arcproperties 532 clipstate este campo contém o valor da propriedade clipstate para o arco O valor de clipstate pode ser off significa que o arco não é recortado clipgrf significa que o arco é recortado fora da caixa dos eixos on significa que o arco é recortado fora do arco dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox property Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura e altura define as porções do arco a serem exibidas contudo o valor da pro priedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade arco e recuperála Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds2222 xarc151533036064 arcgethdl obtendo o manipulador da entidade corrente aqui é a entidade Arc arcfillmodeon arcforeground5 arcdata3 62 27064 xfarc5146036064 arcvisibleoff Ver Também set get delete xarc xarcs xfarc xfarcs graphicsentities Autor Djalel ABDEMOUCHE JeanBaptiste SILVY 533 Name autumncolormap Mapa de cores com tons do outono vermelho laranja amarelo cmapautumncolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição autumncolormap computa um mapa de cores com n cores com tons do outono Exemplos f scf plot3d1 fcolormap autumncolormap32 Ver Também colormap bonecolormap coolcolormap coppercolormap graycolormap hotcolormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 534 Name axesproperties descrição das propriedades de entidades Axes de eixos Descrição A entidade Axes é o segundo nível da hierarquia das entidades de gráfico Esta entidade define os parâmetros que permitem a mudança de coordenadas e o esboço dos eixos tanto quanto os valores padrões dos parâmetros para criação de entidades galhos Propriedades dos eixos parent este campo contém o manipulador da figura raiz children Fvetor FA contendo os manipuladores de todos os objetos gráficos galhos dos eixos Estes objetos gráficos são do tipo Com pound Rectangle Polyline Segs Arc Grayplot ver Compoundproperties rectangleproperties champproperties axisproperties polylineproperties segsproperties grayplotproperties surfaceproperties param3dproperties fecproperties textproperties legendproperties visible este campo contém o valor da propriedade visible visível para os eixos O valor pode ser on ligado ou off desligado Por padrão os eixos são visíveis on caso todos os galhos visíveis sejam exibidos na tela Se off os eixos e seus galhos não são esboçados axesvisible um vetor de strings 1x3 string vector Esta propriedade especifica se o eixo deve ser desen hado ou não Seu valor pode ser on ou off para um ajuste global Para agir em um único eixo a sintaxe é axesvisibleN onde N é 12 ou 3 correspondentes aos eixos xy ou zO dado de escala e se requerido os grides são desenhados se o valor for on Note que ao criar uma simples entidade de eixo usando os comandos gca atalho para getcurrentaxes ou gcf atalho para getcurrentfigure a visibil idade dos eixos é ajustada para off axesreverse um vetor de strings 1x3 correspondentes aos três eixos XYZ Para cada eixo a pro priedade especifica a direção dos valores crescentes Se off a direção padrão é usada Se on a direção é invertida Também é possível utilizar apenas um string on ou off para ajustar simultaneamente os três dados grid o valor do campo é um vetor xgridygridzgrid onde xgrid controla o esboço para o eixo x e ygrid zgrid respectivamente para os eixos y e z O valor padrão é 1 os grides não são desenhados caso contrário os grides são desenhados utilizan do a cor dada indexada pelo valor do grid gridposition Este string determina a posição do grido comparada às outras entidades gráficas Seu valor pode ser foreground para desenhar o grid à frente das outras entidades ou back ground para desenhar o grid atrás xlocation especifica a localização do eixo y Os valores possíveis são bottom Neste caso o eixo y é desenhado na parte direita do retângulo de eixos axesproperties 535 top Neste caso o eixo y é desenhado na parte esquerda do retângulo de eixos middle Neste caso o eixo y é desenhado na posição mais próxima da coordenada 0 do eixo x ylocation especifica a localização do eixo y Os valores possíveis são left Neste caso o eixo y é desenhado na parte direita do retângulo de eixos right Neste caso o eixo y é desenhado na parte esquerda do retângulo de eixos middle Neste caso o eixo y é desenhado na posição mais próxima da coordenada 0 do eixo x title um objeto anexado à entidade de eixos que retorna um manipulador gráfico de uma estrutura label rótulo ver labelproperties Este campo define um título com opções sobre este label xlabel um objeto anexado à entidade de eixos que retorna um manipulador gráfico de uma estrutura label ver labelproperties Este campo define um label sobre o eixo x com opções sobre este label ylabel um objeto anexado à entidade de eixos que retorna um manipulador gráfico de uma estrutura label ver labelproperties Este campo define um label sobre o eixo y com opções sobre este label zlabel um objeto anexado à entidade de eixos que retorna um manipulador gráfico de uma estrutura label ver labelproperties Este campo define um label sobre o eixo z com opções sobre este label autoticks um vetor de strings 1x3 fornecendo o status autoticks para cada eixo Esta propriedade especifica se cada eixo é graduado utilizandose um algoritmo computacional ou não graduações feitas pelo usuário Os valores podem ser on ou off para ajuste glob al Para agir em um único eixo a sintaxe é autoticksN onde N é 12 ou 3 corre spondentes aos eixos xy ou z Note que a edição de tiques textos eou localizações via xticks yticks ou zticks ajusta automaticamente autoticks para off para os eixos correspondentes xtickslocations um vetor de reais contendo a localização das graduações sobre o eixo x Esta propriedade pode ser editada especificandose um novo vetor de reais de mesmo tamanho Para especificar graduações maiores ou menores podese agir no tlist xticks definindo também um vetor de strings xtickslabels ytickslocations um vetor de reais contendo a localização das graduações sobre o eixo y Esta propriedade pode ser editada especificandose um novo vetor de reais de mesmo tamanho Para especificar graduações maiores ou menores podese agir no tlist yticks definindo também um vetor de strings ytickslabels ztickslocations um vetor de reais contendo a localização das graduações sobre o eixo z Esta propriedade pode ser editada especificandose um novo vetor de reais de mesmo tamanho Para especificar graduações maiores ou menores podese agir no tlist zticks definindo também um vetor de strings ztickslabels axesproperties 536 xtickslabels um vetor de strings contendo rótulos para as graduações no eixo x Esta propriedade pode ser editada especificandose um novo vetor de mesmo tamanho Para especificar graduações menores ou maiores pode se agir no tlist xticks definindo também um vetor de reais xtickslocations ytickslabels um vetor de strings contendo rótulos para as graduações no eixo y Esta propriedade pode ser editada especificandose um novo vetor de mesmo tamanho Para especificar graduações menores ou maiores pode se agir no tlist yticks definindo também um vetor de reais ytickslocations ztickslabels um vetor de strings contendo rótulos para as graduações no eixo z Esta propriedade pode ser editada especificandose um novo vetor de mesmo tamanho Para especificar graduações menores ou maiores pode se agir no tlist zticks definindo também um vetor de reais ztickslocations box esta propriedade especifica se os eixos devem ser encerrados por uma caixa Seu valor pode ser off hiddenaxes backhalf ou on Se o valor for off a caixa não é desenhada Se a propriedade for hiddenaxes apenas a moldura de trás é de senhada Se o valor for backhalf os eixos X Y e Z são desenhados também Se a propriedade for on a caixa toda é desenhada filled Esta propriedade especifica se o plano de fundo dos eixos devem ser desenhados ou não Seu valor pode ser off ou on Se o valor for off o plano de fundo não é desenhado e a caixa de eixos é transparente Se a propriedade for on o plano de fundo é desenhado utilizandose a cor especificada pela propriedade background subticks esta propriedade determina o número de subtiques a serem desenhados entre dois tiques prin cipais O valor de campo é o vetor nxny onde nx é o número de subtiques para o eixo x e ny é o correspondente para o eixo y fontstyle especifica a fonte a ser utilizada para exibir os rótulos É um inteiro positivo que faz referência a uma das fontes carregadas Seu valor deve estar entre 0 referenciando a primeira fonte e o número de fontes carregadas menos um referenciando a última fonte carregada Para mais informações ver graphicsfonts fontsize um inteiro especificando o tamanho da fonte usada para para os rótulos dos tiques Se a propriedade fractionalfont for off apenas a parte inteira do valor é utilizada Para mais informações ver graphicsfonts fontcolor esta propriedade determina a cor dos rótulos dos tiques fractionalfont esta propriedade especifica se os rótulos dos tiques serão exibidos com tamanhos de fonte fracionários Seu valor pode ser on ou off Se on o valor em ponto flutuante de fontsize é usado para exibição e a fonte não possui outro nome Se off apenas a parte inteira é utilizada e a fonte não é suavizada isoview esta propriedade é utilizada para se obter escalas isométricas para os eixos x y e z por ex emplo para fazer com que a exibição da curva sinx versus cosx seja um círculo não uma elipse Os valores podem ser on ou off Se o valor for on os databounds axesproperties 537 dos eixos mudam automaticamente de acordo com os valores da propriedade de figura cor respondente figuresize cubescaling esta propriedade é utilizada no modo 3d mode para se obter uma nova escala para os eixos x y e z De fato permite que os dados se encaixem em um cubo 1x1x1 o objetivo é uma melhor visualização de gráficos 3d caso as escalas dos eixos se diferenciem muito umas das outras Os valores podem ser on ou off que é o valor padrão Na maior parte dos casos ajuda a gerar uma visualização 3d semelhante a do Matlab view este campo é relacionado ao universo gráfico Toma 3d como valor correspondente a visualizações em três dimensões Em outros casos pode ser 2d para esboço inicial 2d valor padrão Este flag também depende dos esboços com os quais o usuário entra um comando plot3d por exemplo vai alternar o flag view de 2d para 3d rotationangles este campo é o vetor alphatheta Estes dois valores fornecem as coordenadas esféricas de obsevação em graus logflags string de três caracteres que ajusta a escala linear ou logarítmica o longo dos eixos Cada caractere especifica a escala para os eixos x y e z respectivamente Os valores podem ser n para escala linear ou l para escala logarítmica tightlimits se está propriedade for on os eixos se adaptam para se encaixarem dentro dos valores máximos e mínimos de databounds Se o campo for off os eixos podem aumentar os limites de modo a produzir rótulos de tiques convenientes databounds este campo contém os valores de limite para as coordenadas xy e z É a ma triz xminyminzminxmaxymaxzmax ou xminyminxmaxymax Note que para ter estritamente os limites de dados especificados tightlimits deve ser ajus tado para on ver acima zoombox este campo contém a caixa de zoom corrente se forem fornecidas quaisquer coordenadas É uma matriz vazia sem zoom ou vetor xminyminxmaxymaxzminzmax define um retângulo dado por dois vértices opostos margins um vetor marginleftmarginrightmargintopmarginbottom es pecificando a porção das margens para estes eixos Este vetor é composto de números em 0 1 com valores padrões 0125 0125 0125 0125 estes números são razões relativas aos valores correspondentes da propriedade de figura figuresize axesbounds um vetor xleftyupwidthheight especificando a porção da figura usada por estes eixos onde xleft yup width e height são números em 0 1 fornecendo respectivamente a posição do canto superior esquerdo e a dimensão dos eixos testes números são razões relativas aos valores correspondentes da propriedade de figura figuresize hiddenaxiscolor esta propriedade define a cor do eixo escondido É um índice relativo ao mapa de cores corrente userdata este campo pode armazenar qualquer variável Scilab na estrutura de dados de eixos e recu perála axesproperties 538 Propriedades para funções de altonível As funções plot plot2dx grayplot e matplot utilizam as propriedades seguintes para decidir como misturar esboços consecutivos se isto não for declarado pelo argumento de chama da frameflag calling argument O resultado da mistura é decidido através destas duas pro priedades autoclear se esta propriedade for on uma chamada a um gráfico de altonível reinicializa os eixos correntes e apaga todos os seus galhos antes de realizar o esboço Se for off os esboços serão adicionados aos eixos correntes de acordo com a propriedade autoscale autoscale uma propriedade para atualizar os limites de dados dos eixos Se o valor for on um novo esboço adaptará as propriedades de eixos correntes para se adequar aos esboços anteriores e correntes Se o valor for off o novo esboço será esboçado nos limites de dados correntes Valores padrões dos galhos hiddencolor esta propriedade controla as cores das partes escondidas Toma como valor um índice relativo ao mapa de cores corrente Em outro caso se for um valor negativo as partes escondidas tomam a mesma cor que a superfície linemode este campo contém o valor padrão da propriedade linemode para objetos Segs Rectangle Legend Axis Plot3d Fac3d e Polyline Seus valores podem ser on padrão ou off linestyle este campo contém o valor padrão da propriedade linestyle para objetos Segs Arcs Rectangle e Polyline linestyle seleciona o tipo de linha que será utilizado nos desenhos de linhas Seu valor deve ser um inteiro no intervalo 0 6 0 e 1 significam linhas sólidas os outros selecionam linhas tracejadas ver getlinestyle thickness este campo contém o valor padrão da propriedade thickness para todos os objetos que utilizam linhas Seu valor deve ser um inteiro positivo markmode este campo contém o valor padrão da propriedade markmode para os objetos Segs Rect angle Legend Axis Plot3d Fac3d e Polyline Seu valor pode ser on ou off padrão markstyle este campo contém o valor padrão da propriedade markstyle para objetos Segs Rect angle Legend Axis Plot3d Fac3d e Polyline markstyle seleciona o tipo de marca a ser exibida Seu valor deve ser um inteiro no intervalo 0 9 que significa ponto sinal de mais cruz estrela diamante preenchido diamante triângulo para cima triângulo para baixo trevo ou círculo marksizeunit este campo contém o valor padrão da propriedade marksizeunit para objetos Segs Rectangle Legend Axis Plot3d Fac3d e Polyline Se marksizeunit é ajustado para point então o valor de marksize é diretamente fornecido em pontos Quando marksizeunit é ajustado para tabulated marksize é computado de acor do com o array de tamanho de fonte logo seu valor deve ser um inteiro no intervalo 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que plot2d e funções puras do Scilab utilizam o modo tabulated como padrão ao utilizarse a função plot o modo point é automaticamente habilitado marksize este campo contém o valor padrão da propriedade marksize para objetos Segs Rectangle Legend Axis Plot3d Fac3d e Polyline marksize seleciona o tamanho de fonte da marca axesproperties 539 ser exibida Deve ser um valor inteiro entre 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt ver getmark markforeground este campo contém o valor padrão da propriedade markforeground criados sob os eixos Objetos Polyline Rectangle Legend Surface Segment e Axis utilizam esta propriedade para especificar uma cor de primeiro plano borda para suas marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente Note que o valor padrão é 1 preto padrão e mesmo que você mude o colormap este valor 1 sempre apontará para a cor preta padrão markbackground este campo contém o valor padrão da propriedade markbackground para todos os obje tos criados sob os eixos objetos Polyline Rectangle Legend Surface Segment e Axis uti lizam esta propriedade para especificar uma cor de plano de fundo face para suas marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente Note que o valor padrão é 2 branco padrão e mesmo que você mude o colormap este valor 2 sempre apontará para a cor branca padrão foreground este campo contém o valor padrão da propriedade foreground para eixos e para todos os objetos criados sob os eixos O valor deve ser um índice de cor relativo ao mapa de cores cor rente Note que o valor padrão é 1 preto padrão e mesmo que você mude o colormap este valor 1 sempre apontará para a cor preta padrão background este campo controla o valor padrão da propriedade background para os eixos e para objetos criados sob os eixos O valor deve ser um índice de cor relativo ao mapa de cores corrente Note que o valor padrão é 2 branco padrão e mesmo que você mude o colormap este valor 2 sempre apontará para a cor branca padrão arcdrawingmode este campo controla o valor padrão da propriedade default arcdrawingmode para todos os objetos Arc criados sob este objeto Axes Seu valor pode ser nurbs ou lines clipstate este campo contém o valor padrão da propriedade clipstate para todos os objetos Seu valor pode ser off isto indica todos os objetos criados depois que não estão recortados valor padrão clipgrf isto indica todos os objetos criados depois que estão recortados fora das fronteiras dos eixos on isto indica todos os objetos criados depois que estão recortados fora do retângulo através da propriedade clipbox clipbox este campo contém o valor padrão da propriedade clipbox para todos os objetos Deve ser uma matriz vazia se clipstate for off Em outro caso o recorte é dado por xywh ponto superior esquerdo largura altura Nota sobre valores padrões Todas essas propriedades e campos listados herdam de valores padrões armazenados em um modelo de eixos Estes valores podem ser visualizados e modificados Para isto utilize o comando getdefaultaxes command ele retorna o manipulador gráfico do modelo de eixos Note que nenhuma janela de gráficos é criada por este co mando Note que os próximos eixos criados herdarão deste modelo ver exemplo sobre modelo de eixos abaixo axesproperties 540 Exemplos lines0 desabilitando o paginamento vertical agetcurrentaxesobtendo o manipulador dos novos eixos criados aaxesvisibleon tornando os eixos visíveis afontsize3 ajustando o tamanho da fonte dos rótulos dos tiques axlocationtop ajustando a posição do eixo x adatabounds1002110021 ajustando os valores limites para as coordenadas xy e z asubtics50 alabelsfontcolor5 agrid22 aboxoff exemplo com eixos 3d clf limpando a janela de gráficos x01012piplot2dx3sinx72 agca obtendo o manipulador dos eixos correntes agrid1 1 1 make xgrid arotationangles70 250 girando eixos com ângulos dados agrid1 6 1 criando ygrid aview2d retornando a vista 2d aboxbackhalf alabelsfontcolor5 achildrenchildrenthickness4 achildrenchildrenpolylinestyle3 aview3d return te the 3d view achildrenchildrenthickness1 achildrenchildrenforeground2 agrid1 6 3 criando zgrid aparentbackground4 abackground7 plot2dcosx13sinx3 plot2dcosx73sinx3 achildren2childrenpolylinestyle2 achildren1childrenpolylinestyle4 achildren1childrenforeground5 achildren2childrenforeground14 aparentfiguresize 1200800 aboxon alabelsfontsize4 aparentbackground8 aparentfiguresize 400200 arotationangles0 260 deleteachildren2 delete deletando objeto corrente a gca alabelsfontsize1 aautoclear on x00125piplot2d10cosxsinx adatabounds1 115 ajustando limites positivos para o eixo x alogflags lnn ajustando o eixo X para escala logarítmica alogflags nnn voltando para escala linear agca axesproperties 541 arotationangles45 45 adatabounds203220 3 2 xrect4 05 8 1 aautoclear off aisoviewon modo de isovisualização xrect2 025 4 05 achildren1fillmodeon aaxesvisibleoff achildren1data2 025 1 4 05 achildren2data4 05 1 8 1 x2pi078 xv2sinx9sinxyv2cosx9cosx xsegs10xvyv18 sachildren1 sarrowsize1 ssegscolor5 adatabounds os valores limites para as coordenadas xy e z aview2d adatabounds101 101 ajustando os valores limites para vistas bidimensionais exemplo com eixos modelos dagda obtendo manipulador dos eixo modelos para ver e editar campos título padrão datitletextMy DefaultTitle datitleforeground 12 datitlefontsize 4 rótulos x padrões daxlabeltextx daxlabelfontstyle 8 daxlabelfontsize 2 daxlabelforeground 5 daxlocation middle rótulos y padrões daylabeltexty daylabelfontstyle 3 daylabelfontsize 5 daylabelforeground 3 daylocation right dathickness 2 daforeground 7 o esboço x0012pi plot2dxsinxsin2xsin3xstyle123rect022pi2 sda de volta aos eixos modelos padrões Ver Também lines set get gca gda gcf sda sdf scf graphicsentities Autor Djalel ABDEMOUCHE 542 Name axisproperties Descrição das propriedades da entidade Axis eixo Descrição A entidade Axis é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para escala de eixos e aparência Propriedades parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Axis deve ser do tipo Axes ou Compound visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o eixo é visível a propriedade é on Se off o eixo não é exibido na tela ticsdirection especifica a direção dos tiques desenhados sob os eixos horizontal e vertical Os possíveis valores para esta propriedade são top Neste caso os tiques são desenhados na parte de cima do eixo horizontal bottom Neste caso os tiques são desenhados na parte de baixo do eixo horizontal left Neste caso os tiques são desenhados à esquerda do eixo vertical right Neste caso os tiques são desenhados à direita do eixo vertical Os valores padrões são top para o eixo horizontal e right para o eixo vertical xticscoord este campo contém as coordenadas x do eixo É um vetor linha que contém valores crescentes da esquerda para a direita que fornecem as posições dos tiques para um eixo horizontal Em outro caso a entidade é um eixo vertical esta propriedade contém a escala que define a origem x do eixo yticscoord este campo contém as coordenadas y do eixo É um vetor linha que contém valores crescentes do fundo para o topo que fornecem as posições dos tiques para um eixo vertical Em outro caso a entidade é um eixo horizontal esta propriedade contém a escala que define a origem y do eixo ticscolor o valor desta propriedade é o índice da cor utilizada para desenhar as linhas dos eixos e tiques ticssegment este campo contém um flag que controla a exibição do segmento base do eixo O valor padrão é on senão sem exibição a propriedade toma off como valor ticsstyle esta propriedade descreve como os tiques são dados É um flag string que pode ter um desses valores v É o valor padrão Neste caso as posições dos tiques são dadas pelo vetor linha xticscoord para o eixo horizontal yticscoord para o vertical r INeste caso as posições dos tiques são dadas pelo vetor minmaxn onde n é o número de intervalos axisproperties 543 i Neste caso o vetor fornecendo as posições dos tiques tem tamanho 4 k1k2an os valores crescem entre k110a e k210a n é o número de inter valos subtics este campo ajusta o número de tiques a serem desenhados entre dois tiques principais ticslabels este campo é uma matriz de strings que contém strings a serem impressos ao longo dos eixos nas posições dos tiques labelsfontcolor esta propriedade determina a cor dos rótulos dos tiques labelsfontsize um inteiro especificando o tamanho da fonte utilizada para imprimir os rótulos dos tiques Se a propriedade fractionalfont for off Apenas a parte inteira do valor é utilizada Para mais informações veja graphicsfonts fractionalfont esta propriedade especifica se os rótulos dos tiques serão exibidos utilizandose um taman ho de fonte fracionário Seu valor deve ser on ou off Se on o valor em ponto flutuante de fontsize é utilizado para a exibição e retirase o serrilhamento da fonte Se off apenas a parte inteira é utilzada e a fonte não é suavizada clipstate este campo contém o valor da propriedade clipstate para o eixo O valor de clipstate pode ser off significa que o eixo não é recortado clipgrf significa que o eixo é recortado fora da caixa dos eixos on significa que o eixo é recortado fora do arco dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções do eixo a ser exibido contudo o valor da pro priedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade axis e recuperála Exemplos agetcurrentaxesobtendo manipulador dos novos eixos criados adatabounds111010 drawaxisx27y4diru a1achildren1 a1xticscoord1 4 5 8 10 a1ticscolor2 a1labelsfontsize3 a1ticsdirectionbottom a1ticslabels Fevereiro Maio Junho Agosto Outubro drawaxisx12110y5dirutextcolor13 axisproperties 544 a2gethdl a2subtics0 a2ticssegmentoff a2yticscoord4 drawaxisx1y017dirrfontsize10textcolor5ticscolor6subint10 a3gethdl a3ticslabels B string07 a3ticsdirectionleft Ver Também set get delete drawaxis graphicsentities Autor Djalel ABDEMOUCHE 545 Name bar Histograma de barras bary barxy barhxy width color style Parâmetros h manipulador de eixos padrão hgca y escalar real vetor de tamanho N ou uma matriz NxM x escalar real ou um vetor de tamanho N padrão se y é um vetor então x is é um vetor e o comprimento de x é igual ao comprimento de y Se y é uma matriz então x é um vetor e o comprimento de x é igual ao número de linhas de y width opcional escalar real define a largura uma porcentagem do espaço disponível para a barra padrão 08 ie 80 color opcional um string padrão blue especificando a cor da barra style string grouped ou stacked padrão grouped Descrição bary se y é um vetor então a função bar desenha uma poligonal que tem polylinestyle tipo 6 Se y for um vetor desenha o vetor y versus o vetor 1sizey Se y for uma matriz NM bar desenha M poligonais tipo 6 cada poligonal corresponde a uma coluna de y versus o vetor x1sizey1 barxy se y for um vetor então a função bar desenha uma poligonal que tem polylinestyle tipo 6 onde comprimento de x comprimento de y Se y é uma matriz NxM então a função bar desenha M poligonais que possuem tipo 6 Cada poligonal corresponde a uma col una de y versus o vetor x barh define os eixos correntes onde o desenho é feito barwidth define a largura das barras em porcentagem geralmente 0width1 barstyle define como as barras serão desenhadas Se y é uma matriz NxM então temos M poligonais de tipo 6 então há dois modos de se desenhar as M barras A opção style grouped permite centrar as M poligonais versus cada componente de x e a opção style stacked permite empilhálas barcolor define a cor da barra Funções de barra utilizam o mesmo mapa de cores que na função Se há várias chamadas a bar a função barhomogenize permite homogeneizar a largura e estilo de todas as barras ie poligonais do tipo 6 inclusas nos eixos correntes bar 546 Exemplos primeiro exemplo desenhando uma barra ie uma poligonal com polylinestyle 6 com width05 e coloryellow e stylegrouped x1lengthy scf0 y1 3 5 bary05yellow segundo exemplo desenhando 3 barras ie três poligonais com polylinestyle 6 stylegrouped scf1 x1 2 5 y1 5 63 2 74 3 8 barxy terceiro exemplo stylestacked scf2 x1 2 5 y1 4 72 5 83 6 9 barxystacked quarto exemplo width02colorgreen stylegrouped scf3 x1 2 5 y1 4 72 5 83 6 9 barxy02green Ver Também barh barhomogenize plot polylineproperties Autor Farid Belahcene 547 Name barh Exibição horizontal de um histograma de barras barhy barhxy barhhxy width color style Parâmetros h manipulador de eixos padrão hgca y escalar real vetor de tamanho N ou uma matriz NxM x escalar real ou um vetor de tamanho N padrão se y é um vetor então x é um vetor e o compri mento de x é igual ao comprimento de y Se y é uma matriz então x é um vetor e o comprimento de x é igual ao número de linhas de y width opcional escalar real define a largura uma porcentagem do espaço disponível para a barra padrão 08 ie 80 color opcional um string padrão blue especificando a cor interior da barra barra style string grouped ou stacked padrão grouped Descrição barhy se y é um vetor então a função bar desenha uma poligonal que tem polylinestyle tipo 6 Se y for um vetor desenha o vetor y versus o vetor 1sizey Se y for uma matriz NM bar desenha M poligonais tipo 6 cada poligonal corresponde a uma coluna de y versus o vetor x1sizey1 barhxy se y for um vetor então a função desenha uma poligonal que tem polylinestyle tipo 6 onde comprimento de x comprimento de y Se y é uma matriz NxM então a função desenha M poligonais que possuem tipo 6 Cada poligonal corresponde a uma coluna de y versus o vetor x barhh define os eixos correntes onde o desenho é realizado barhwidth define a largura das barras em porcentagem geralmente 0width1 barhstyle define como as barras serão desenhadas Se y é uma matriz NxM então temos M poligonais de tipo 6 então há dois modos de se desenhar as M barras A opção style grouped permite centrar as M poligonais versus cada componente de x e a opção style stacked permite empilhálas barhcolor define a cor da barra Funções de barra utilizam o mesmo mapa de cores que na função plot Se há várias chamadas a barh a função barhomogenize permite homogeneizar a largura e estilo de todas as barras ie poligonais do tipo 6 inclusas nos eixos correntes barh 548 Exemplos primeiro exemplo desenhando uma barra ie uma poligonal com polylinestyle 6stylegrouped width05 coloryellow x1lengthy scf0 y1 3 5 barhy05yellow segundo exemplo desenhando três barras ie três poligonais com polylinestyle 6stylegrouped scf1 x1 2 5 y1 5 63 2 74 3 8 barhxy terceiro exemplo stylestacked scf2 x1 2 5 y1 4 72 5 83 6 9 barhxystacked quarto exemplo width02colorgreen stylegrouped scf3 x1 2 5 y1 4 72 5 83 6 9 barhxy02green Ver Também bar barhomogenize plot polylineproperties Autor Farid Belahcene 549 Name barhomogenize Homogeniza todas as barras inclusas nos eixos correntes barhomogenize barhomogenizehstylewidth Parâmetros h manipulador de eixos padrão hgca style string grouped ou stacked padrão grouped width opcional escalar real define a largura uma porcentagem do espaço disponível para a barra padrão 08 Descrição Se há várias chamadas a bar a função barhomogenize permite homogeneizar a largura e estilo de todas as barras ie que têm polylinestyle tipo 6 inclusas nos eixos correntes Estas barras devem ter os mesmos dados x barhomogenize toma os valores padrões hgca width08 stylegrouped barhomogenizeh define os eixos correntes onde o desenho é realizado barhomogenizewidth define a largura das barras em porcentagemgeralmente 0width1 barhomogenizestyle define como as barras são desenhadas A opção grouped permite centrar as M poligonais versus cada componente de x e a opção stacked permite empilhálas Exemplos Primeiro exemplo criação de uma barra amarela ie uma poligonal com polylinestyle6 e três barras ie três poligonais com polylinestyle6 subplot231 xtitleex1 criação de uma barra amarela e três barras x13 y113 y24 3 56 7 89 10 11 barxy1yellowbarxy2 homogeneização dessas quatro barras subplot232 xtitlehomogenização agrupada x13 y113 y24 3 56 7 89 10 11 barxy1yellowbarxy2 barhomogenize homogenização empilhada dessas quatro barras subplot233 xtitlehomogenização empilhada x13 y113 y24 3 56 7 89 10 11 barxy1yellowbarxy2 barhomogenizestacked1 Segundo exemplo criação de uma barra vermelha ie uma poligonal com polylinestyle6 e duas poligonais com type1 função de chamamento do esboço subplot234 barhomogenize 550 xtitleex2 criação de uma barra e duas poligonais x110 ysinx2 barxyred x1110y1sinxcosx plotx1y1 modificando o polylinestyle da segunda poligonal do esboço esta poligonal se torna em uma barra subplot235 xtitletransformação da segunda poligonal em uma barra x110 ysinx2 barxyred x1110y1sinxcosx plotx1y1 egce e2echildren2 e2polylinestyle6 homogenização da primeira barra da função bar e da segunda barra da modificação subplot236 xtitlehomogeneização em grupo x110 ysinx2 barxyred x1110y1sinxcosx plotx1y1 egce e2echildren2 e2polylinestyle6 barhomogenize mudança de estilo e largura barhomogenizestacked05 barhomogenizestacked1 Ver Também bar polylineproperties Autor Farid Belacehne 551 Name bonecolormap Mapa de cores cinza com um tom claro de azul cmapbonecolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição bonecolormap computa um mapa de cores cinza com um tom azul claro Exemplos f scf plot3d1 fcolormap bonecolormap32 Ver Também colormap autumncolormap coolcolormap coppercolormap graycolormap hotcolormap hsvcol ormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercol ormap whitecolormap wintercolormap 552 Name captions Impressão de legendas de gráficos hlcaptionsh strings location Parâmetros h vetor de manipuladores de entidades Polyline strings nvetor de strings stringsi é a legenda da iésima poligonal hl um manipulador do tipo Legend pontos para a estrutura contendo todas as informações das legendas ver legendproperties location string com possíveis valores inupperright as legendas são exibidas no canto superior direito da caixa de eixos inupperleft as legendas são exibidas no canto superior esquerdo da caixa de eixos inlowerright as legendas são exibidas no canto inferior direito da caixa de eixos inlowerleft as legendas são exibidas no canto inferior esquerdo da caixa de eixos outupperright as legendas são exibidas à direita do canto superior direito da caixa de eixos outupperleft as legendas são exibidas à esquerda do canto superior esquerdo da caixa de eixos outlowerright as legendas são exibidas à direita do canto inferior direito da caixa de eixos outlowerleft as legendas são exibidas à esquerda do canto inferior esquerdo da caixa de eixos uppercaption as legendas são exibidas acima do canto superior esquerdo da caixa de eixos lowercaption as legendas são exibidas abaixo do canto inferior esquerdo da caixa de eixos Esta opção corresponde ao argumento leg de plot2d bycoordinates o canto superior esquerdo da caixa das legendas é dada pelo campo position da estrutura de dados associada As posições x e y são fornecidas como frações dos tamanhos de axesbounds Descrição Coloca legendas no esboço corrente no canto inferior esquerdo da janela gráfica utilizandose os strings especificados como rótulos captions prefixa rótulos por uma nova chamada às poligonais corre spondentes O tipo e propriedades são recuperados do dado manipulador A função captions cria uma estrutura de dados Legend Há no máximo uma Legend associada a cada entidade Axes Se a função caption for chamada nova mente enquanto Legend ainda existe a legenda antiga é apagada captions 553 Exemplos t0012pi agcaadataboundst1 18t 18 amargins402 plot2dtcostcos2tcos3t12 3 egce echildren1thickness3 echildren2linestyle4 hlcaptionsechildrencostcos2tcos3t hlcaptionsechildrencostcos2tcos3tinupperright hllegendlocationinupperright hlfillmodeon Ver Também plot2d legend polylineproperties legendproperties 554 Name champ esboço de campo vetorial 2d champxyfxfyarfactrectstrf champxyfxfyoptargs Parâmetros xy dois vetores que definem o grid fx uma matriz que descreve o componente x do campo vetorial fxij é o componente x do campo vetorial no ponto xiyj fy uma matriz que descreve o componente y do campo vetorial fyijé o componente y do campo vetorial no ponto xiyj optargs representa a seqüência de declarações key1value1key2value2 onde key1 key2 podem ser um dos seguintes arfact rect strf ver abaixo arfact um argumento opcional do tipo real que fornece um fator de escala para a exibição das cabeças das setas no esboço o valor padrão é 10 rect um vetor rectxminyminxmaxymax que fornece as fronteiras da moldura gráfica à ser utilizada strf um string de comprimento 3 xyz que possui o mesmo significado do parâmetro strf de plot2d O primeiro caractere não tem efeito com champ Descrição champ desenha um campo vetorial 2d O comprimento das setas é proporcional é proporcional à intensidade do campo Se você quiser setas coloridas com a cor das setas dependendo da intensidade do campo use champ1 Entre com o comando champ para visualizar uma demonstração Exemplos usando rect como fronteiras do esboço champ5555rand1111rand1111rect10101010arfact2 usando xy para conseguir obter clf champ5555rand1111rand1111210101010021 Ver Também champ1 fchamp plot2d Autor JPhC 556 Name champ1 campo vetorial 2d com setas coloridas champ1xyfxfyarfactrectstrf Parâmetros xy dois vetores que definem o grid fx uma matriz que descreve o componente x do campo vetorial fxij é o componente x do campo vetorial no ponto xiyj fy uma matriz que descreve o componente y do campo vetorial fyij é o componente y do campo vetorial no ponto xiyj arfact um argumento opcional do tipo real que fornece um fator de escala para a exibição das cabeças das setas no esboço o valor padrão é 10 rect um vetor rectxminyminxmaxymax que fornece as fronteiras da moldura gráfica a ser utilizada frameflag ccontrola a computação dos intervalos de coordenadas verdadeiros a partir dos valores mínimos requeridos O valor associado deve ser um inteiro no intervalo de 0 a 8 axesflag especifica como os eixos são desenhados O valor associado deve ser um inteiro no intervalo de 0 a 5 strf um string de comprimento 3 xyz que possui o mesmo significado do parâmetro strf de plot2d O primeiro caractere não tem efeito com champ1 Descrição champ1 desenha um campo vetorial 2d com setas coloridas A cor das setas depende da intensidade do campo Se você quiser setas proporcionais à intensidade do campo use champ Entre com o comando champ1 para visualizar uma demonstração Exemplos champ15555rand1111rand1111rect10101010arfact2 Ver Também champ fchamp plot2d Autor JPhC 558 Name champproperties Descrição das propriedades da entidade campo vetorial 2d Descrição A entidade Champ é uma folha na hierarquia de entidade gráficas Esta entidade define parâmetros para um campo vetorial 2d visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Se on o campo vetorial é desenhado se off o campo vetorial não aparece na tela data este campo define uma estrutura de dados tlist de tipo champdata composto de uma linha e índices de colunas de cada elemento as coordenadas do grid x e y contidas respectiva mente em datax e datay Os campos complementares chamados datafx e datafy são matrizes que descrevem respectivamente os componentes x e y do campo vetorial no ponto xiyj userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade Champ e recuperála linestyle o valor da propriedade linestyle deve ser um valor inteiro no intervalo 0 9 0 significa linha sólida e os outros valores significam estilos de tracejados Esta propriedade aplicase a todas as linhas usadas para desenhar o campo vetorial thickness este campo contém o valor da propriedade thickness espessura para todas as linhas utilizadas no desenho Seu valor deve ser um inteiro nãonegativo colored se o valor desta propriedade for on os vetores são coloridos utilizandose uma cor porporcional à intensidade do campo clipstate este campo contém o valor da propriedade clipstate para a entidade Champ Pode ser off significa que o campo vetorial não é recortado clipgrf siginifica que o campo vetorial é recortado fora da caixa da entidade Axes on significa que o campo vetorial é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo contém o valor da propriedade clipbox Seu valor pode ser uma matriz vazia se a propriedade clipstate é off em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções do campo a serem exibidas contudo o valor da propriedade clipstate será modificado parent esta propriedade contém o manipulador da raiz A raiz de uma entidade campo vetorial 2d deve ser do tipo Axes ou Compound Exemplos champproperties 559 agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds10101010 champ5555rand1111rand1111 cachildren ccoloredon cthickness2 cdata exibindo um tlist do tipo scichampdata adatabounds5555 Ver Também set get delete champ champ1 graphicsentities Autor Djalel ABDEMOUCHE 560 Name clearpixmap Apaga o buffer de pixmap mapa de píxeis clearpixmap Descrição Se a propriedade de uma janela de gráficos pixmap for on as gravuras são enviadas para uma memória pixmap ao invés de serem exibidas na tela A instrução clearpixmap apaga o pixmap mas não a tela O modo pixmap pode ser usado para se obter animações suaves Ver Também figureproperties showpixmap Autor Serge Steer INRIA 561 Name clf Limpa ou reajusta a janela da figura gráfica corrente para valores padrões clfoptjobarg clfhoptjobarg clfnumoptjobarg Parâmetros h o manipulador da figura num identificador da figura figureid optjobarg um string clear ou reset especificando o trabalho de clf Descrição O comando clf é utilizado para reajustar uma figura para seus valores padrões eou deletar todos os seus galhos Se o valor do string optjobarg for clear então todos os galhos da figura especificada são deletados Se o valor do string optjobarg for reset então não só todos os galhos da figura são deletados mas os valores das propriedades da figura são reajustados para seus valores padrões uti lizandose a figura modelo padrão ver gdf As únicas exceções são as propriedades axessize e figuresize que não podem ser reajustadas se a figura está aportada com outros elementos clfnum limpa ou reajusta e limpa a figura com figureidnum clfh limpa ou reajusta e limpa a figura apontada pelo manipulador h clf limpa ou reajusta e limpa a figura existente corrente clf deleta todos os galhos de janelas especificadas incluindo menus e uicontrols adicionados pelo usuário Para evitar que menus e uicontrols sejam deletados o comando deletegca deve ser utilizado ao invés Exemplos f4scf4 criando figura com id4 e tornandoa a figura corrente f4colormap jetcolormap64 f4figuresize 400 200 plot2d clff4reset f0scf0 criando figura com id0 e tornandoa a figura corrente f0colormaphotcolormap128 mudando o mapa de cores tpi03pi plot3d1ttsintcost clf equivalent to clfgcfclear plot3d1ttsintcost colormap inalterado clf 562 clfgcfreset plot3d1ttsintcost colormap alterado de volta ao padrão com 32 cores See Also set get gcf gdf scf graphicsentities Authors S Steer FLeray INRIA 563 Name color Retorna o identificador de uma cor idcolorname idcolorrgb Parâmetros name nome de uma cor rgb valores RGB inteiros de uma cor id identificador da cor Descrição color retorna o identificador de cor correspondente ao seu argumento name deve ser um nome de cor conhecido ver colorlist r g e b devem ser inteiros entre 0 e 255 correspondentes aos componentes de cor vermelho verde e azul Como de uso 0 significa nenhuma intensidade e 255 significa total idensidade para a cor Se a cor requisitada não existe no mapa de cores corrente então ela é adicionada ao mapa de cores Esta função pode ser utilizada para se especificar as cores de plano de fundo e de primeiro plano em esboços Exemplos xlinspace2pi2pi100 utilizando cores existentes plot2dxsinxcosxstylecolorredcolorgreen novas cores adicionadas ao mapa de core egce p1echildren1 p2echildren2 p1foregroundcolorpurple p2foregroundcolornavy blue utilizando valores RGB p1foregroundcolor255128128 Ver Também colormap colorlist getcolor 564 Name colorlist Lista dos nomes das cores Descrição Abaixo você encontrará os nomes das cores conhecidas pelo Scilab Os valores RGB vermelho verde azul são dados após os nomes Note que algumas vezes as cores possuem mais de um nome scilab blue4 azul 0 0 144 scilabblue4 0 0 144 scilab blue3 0 0 176 scilabblue3 0 0 176 scilab blue2 0 0 208 scilabblue2 0 0 208 scilab green4 verde 0 144 0 scilabgreen4 0 144 0 scilab green3 0 176 0 scilabgreen3 0 176 0 scilab green2 0 208 0 scilabgreen2 0 208 0 scilab cyan4 ciano 0 144 144 scilabcyan4 0 144 144 scilab cyan3 0 176 176 scilabcyan3 0 176 176 scilab cyan2 0 208 208 scilabcyan2 0 208 208 scilab red4 vermelho 144 0 0 scilabred4 144 0 0 scilab red3 176 0 0 scilabred3 176 0 0 scilab red2 208 0 0 scilabred2 208 0 0 scilab magenta4 ma genta 144 0 144 scilabmagenta4 144 0 144 scilab magenta3 176 0 176 scilabmagenta3 176 0 176 scilab magenta2 208 0 208 scilabmagenta2 208 0 208 scilab brown4 marrom 128 48 0 scilabbrown4 128 48 0 scilab brown3 160 64 0 scilabbrown3 160 64 0 scilab brown2 192 96 0 colorlist 565 scilabbrown2 192 96 0 scilab pink4 rosa 255 128 128 scilabpink4 255 128 128 scilab pink3 255 160 160 scilabpink3 255 160 160 scilab pink2 255 192 192 scilabpink2 255 192 192 scilab pink 255 224 224 scilabpink 255 224 224 snow branco 255 250 250 ghost white branco 248 248 255 ghostwhite 248 248 255 white smoke branco 245 245 245 whitesmoke 245 245 245 gainsboro cinza 220 220 220 floral white branco 255 250 240 floralwhite 255 250 240 old lace creme 253 245 230 oldlace 253 245 230 linen creme 250 240 230 antique white creme 250 235 215 antiquewhite 250 235 215 papaya whip creme alaranjado 255 239 213 papayawhip 255 239 213 blanched almond creme alaranjado 255 235 205 blanchedalmond 255 235 205 bisque creme alaranja do 255 228 196 peach puff pêssego claro 255 218 185 peachpuff 255 218 185 navajo white pêssego 255 222 173 navajowhite 255 222 173 moccasin pêssego 255 228 181 cornsilk branco creme 255 248 220 ivory marfim 255 255 240 lemon chiffon branco rosa 255 250 205 lemonchiffon 255 250 205 seashell brancorosa 255 245 238 colorlist 566 honeydew branco men ta 240 255 240 mint cream creme de menta 245 255 250 mintcream 245 255 250 azure azulbebê 240 255 255 alice blue azulbebê 240 248 255 aliceblue 240 248 255 lavender lavanda 230 230 250 lavender blush lavanda claro 255 240 245 lavenderblush 255 240 245 misty rose rosa 255 228 225 mistyrose 255 228 225 white branco 255 255 255 black preto 0 0 0 dark slate gray cinza azulado escuro 47 79 79 darkslategray 47 79 79 dark slate grey 47 79 79 darkslategrey 47 79 79 dim gray cinza escuro 105 105 105 dimgray 105 105 105 dim grey 105 105 105 dimgrey 105 105 105 slate gray cinza azula do 112 128 144 slategray 112 128 144 slate grey 112 128 144 slategrey 112 128 144 light slate gray cinza azulado claro 119 136 153 lightslategray 119 136 153 light slate grey 119 136 153 lightslategrey 119 136 153 gray cinza 190 190 190 grey 190 190 190 light grey cinza claro 211 211 211 lightgrey 211 211 211 light gray 211 211 211 lightgray 211 211 211 midnight blue azul meianoite 25 25 112 colorlist 567 midnightblue 25 25 112 navy azul marinho 0 0 128 navy blue 0 0 128 navyblue 0 0 128 cornflower blue azul meio claro 100 149 237 cornflowerblue 100 149 237 dark slate blue púrpura azulado escuro 72 61 139 darkslateblue 72 61 139 slate blue púrpura azu lado 106 90 205 slateblue 106 90 205 medium slate blue púrpura azulado médio 123 104 238 mediumslateblue 123 104 238 light slate blue púrpura azulado claro 132 112 255 lightslateblue 132 112 255 medium blue azul médio 0 0 205 mediumblue 0 0 205 royal blue azul real 65 105 225 royalblue 65 105 225 blue azul 0 0 255 dodger blue azul meio claro 30 144 255 dodgerblue 30 144 255 deep sky blue azul claro 0 191 255 deepskyblue 0 191 255 sky blue azul leve mente esverdiado 135 206 235 skyblue 135 206 235 light sky blue azul lev emente esverdiado 135 206 250 lightskyblue 135 206 250 steel blue azul metálico 70 130 180 steelblue 70 130 180 light steel blue cinza levemente azulado 176 196 222 lightsteelblue 176 196 222 light blue 173 216 230 colorlist 568 lightblue 173 216 230 powder blue turquesa clara 176 224 230 powderblue 176 224 230 pale turquoise turquesa clara 175 238 238 paleturquoise 175 238 238 dark turquoise turquesa escura 0 206 209 darkturquoise 0 206 209 medium turquoise turquesa média 72 209 204 mediumturquoise 72 209 204 turquoise turquesa 64 224 208 cyan ciano 0 255 255 light cyan branco ciano 224 255 255 lightcyan 224 255 255 cadet blue azul cin zaesverdeado 95 158 160 cadetblue 95 158 160 medium aquamarine aquamarine média 102 205 170 mediumaquamarine 102 205 170 aquamarine aquama rine 127 255 212 dark green verde es curo 0 100 0 darkgreen 0 100 0 dark olive green verde oliva escuro 85 107 47 darkolivegreen 85 107 47 dark sea green verde mar claro 143 188 143 darkseagreen 143 188 143 sea green verdemar 46 139 87 seagreen 46 139 87 medium sea green verdemar médio 60 179 113 mediumseagreen 60 179 113 light sea green verde mar claro 32 178 170 lightseagreen 32 178 170 pale green verde pálido 152 251 152 colorlist 569 palegreen 152 251 152 spring green verde pri mavera 0 255 127 springgreen 0 255 127 lawn green verde gra ma 124 252 0 lawngreen 124 252 0 green verde 0 255 0 chartreuse verde claro 127 255 0 medium spring green verde azulado 0 250 154 mediumspringgreen 0 250 154 green yellow verde amarelado 173 255 47 greenyellow 173 255 47 lime green verdelodo 50 205 50 limegreen 50 205 50 yellow green amarelo esverdeado 154 205 50 yellowgreen 154 205 50 forest green verdeflo resta 34 139 34 forestgreen 34 139 34 olive drab verde azeitona 107 142 35 olivedrab 107 142 35 dark khaki cáqui es curo 189 183 107 darkkhaki 189 183 107 khaki 240 230 140 pale goldenrod amarelo queimado pálido 238 232 170 palegoldenrod 238 232 170 light goldenrod yellow bege claro 250 250 210 lightgoldenrodyellow 250 250 210 light yellow amarelo claro 255 255 224 lightyellow 255 255 224 yellow amarelo 255 255 0 gold ouro 255 215 0 light goldenrod amare lo queimado claro 238 221 130 lightgoldenrod 238 221 130 colorlist 570 goldenrod amarelo queimado 218 165 32 dark goldenrod amare lo queimado escuro 184 134 11 darkgoldenrod 184 134 11 rosy brown rosa com tonalidade marrom 188 143 143 rosybrown 188 143 143 indian red vermelho índio 205 92 92 indianred 205 92 92 saddle brown marrom sela 139 69 19 saddlebrown 139 69 19 sienna marrom 160 82 45 peru marrom 205 133 63 burlywood marrom claro 222 184 135 beige bege 245 245 220 wheat trigo 245 222 179 sandy brown marrom arenoso 244 164 96 sandybrown 244 164 96 tan marrom bronzeado 210 180 140 chocolate chocolate 210 105 30 firebrick vermelho sangue 178 34 34 brown marrom 165 42 42 dark salmon salmão es curo 233 150 122 darksalmon 233 150 122 salmon salmão 250 128 114 light salmon salmão claro 255 160 122 lightsalmon 255 160 122 orange laranja 255 165 0 dark orange laranja es curo 255 140 0 darkorange 255 140 0 coral laranja salmon 255 127 80 light coral salmon rosa do 240 128 128 lightcoral 240 128 128 tomato tomate 255 99 71 colorlist 571 orange red laranja aver melhado 255 69 0 orangered 255 69 0 red vermelho 255 0 0 hot pink rosa quente 255 105 180 hotpink 255 105 180 deep pink rosa vivo 255 20 147 deeppink 255 20 147 pink rosa claro 255 192 203 light pink rosa 255 182 193 lightpink 255 182 193 pale violet red violeta avermelhado claro 219 112 147 palevioletred 219 112 147 maroon vinho rosado 176 48 96 medium violet red violeta avermelhado médio 199 21 133 mediumvioletred 199 21 133 violet red violeta aver melhado 208 32 144 violetred 208 32 144 magenta magenta 255 0 255 violet violeta 238 130 238 plum ameixa 221 160 221 orchid orquídea 218 112 214 medium orchid orquídea médio 186 85 211 mediumorchid 186 85 211 dark orchid orquídea escuro 153 50 204 darkorchid 153 50 204 dark violet violeta es curo 148 0 211 darkviolet 148 0 211 blue violet violeta azu lado 138 43 226 blueviolet 138 43 226 purple púrpura 160 32 240 medium purple púrpura claro 147 112 219 mediumpurple 147 112 219 thistle roxo acinzenta do 216 191 216 colorlist 572 daqui em diante são séries de gradações de cores snow1 255 250 250 snow2 238 233 233 snow3 205 201 201 snow4 139 137 137 seashell1 255 245 238 seashell2 238 229 222 seashell3 205 197 191 seashell4 139 134 130 antiquewhite1 255 239 219 antiquewhite2 238 223 204 antiquewhite3 205 192 176 antiquewhite4 139 131 120 bisque1 255 228 196 bisque2 238 213 183 bisque3 205 183 158 bisque4 139 125 107 peachpuff1 255 218 185 peachpuff2 238 203 173 peachpuff3 205 175 149 peachpuff4 139 119 101 navajowhite1 255 222 173 navajowhite2 238 207 161 navajowhite3 205 179 139 navajowhite4 139 121 94 lemonchiffon1 255 250 205 lemonchiffon2 238 233 191 lemonchiffon3 205 201 165 lemonchiffon4 139 137 112 cornsilk1 255 248 220 cornsilk2 238 232 205 cornsilk3 205 200 177 cornsilk4 139 136 120 ivory1 255 255 240 ivory2 238 238 224 ivory3 205 205 193 ivory4 139 139 131 honeydew1 240 255 240 honeydew2 224 238 224 honeydew3 193 205 193 honeydew4 131 139 131 colorlist 573 lavenderblush1 255 240 245 lavenderblush2 238 224 229 lavenderblush3 205 193 197 lavenderblush4 139 131 134 mistyrose1 255 228 225 mistyrose2 238 213 210 mistyrose3 205 183 181 mistyrose4 139 125 123 azure1 240 255 255 azure2 224 238 238 azure3 193 205 205 azure4 131 139 139 slateblue1 131 111 255 slateblue2 122 103 238 slateblue3 105 89 205 slateblue4 71 60 139 royalblue1 72 118 255 royalblue2 67 110 238 royalblue3 58 95 205 royalblue4 39 64 139 blue1 0 0 255 blue2 0 0 238 blue3 0 0 205 blue4 0 0 139 dodgerblue1 30 144 255 dodgerblue2 28 134 238 dodgerblue3 24 116 205 dodgerblue4 16 78 139 steelblue1 99 184 255 steelblue2 92 172 238 steelblue3 79 148 205 steelblue4 54 100 139 deepskyblue1 0 191 255 deepskyblue2 0 178 238 deepskyblue3 0 154 205 deepskyblue4 0 104 139 skyblue1 135 206 255 skyblue2 126 192 238 skyblue3 108 166 205 skyblue4 74 112 139 lightskyblue1 176 226 255 colorlist 574 lightskyblue2 164 211 238 lightskyblue3 141 182 205 lightskyblue4 96 123 139 slategray1 198 226 255 slategray2 185 211 238 slategray3 159 182 205 slategray4 108 123 139 lightsteelblue1 202 225 255 lightsteelblue2 188 210 238 lightsteelblue3 162 181 205 lightsteelblue4 110 123 139 lightblue1 191 239 255 lightblue2 178 223 238 lightblue3 154 192 205 lightblue4 104 131 139 lightcyan1 224 255 255 lightcyan2 209 238 238 lightcyan3 180 205 205 lightcyan4 122 139 139 paleturquoise1 187 255 255 paleturquoise2 174 238 238 paleturquoise3 150 205 205 paleturquoise4 102 139 139 cadetblue1 152 245 255 cadetblue2 142 229 238 cadetblue3 122 197 205 cadetblue4 83 134 139 turquoise1 0 245 255 turquoise2 0 229 238 turquoise3 0 197 205 turquoise4 0 134 139 cyan1 0 255 255 cyan2 0 238 238 cyan3 0 205 205 cyan4 0 139 139 darkslategray1 151 255 255 darkslategray2 141 238 238 darkslategray3 121 205 205 darkslategray4 82 139 139 aquamarine1 127 255 212 colorlist 575 aquamarine2 118 238 198 aquamarine3 102 205 170 aquamarine4 69 139 116 darkseagreen1 193 255 193 darkseagreen2 180 238 180 darkseagreen3 155 205 155 darkseagreen4 105 139 105 seagreen1 84 255 159 seagreen2 78 238 148 seagreen3 67 205 128 seagreen4 46 139 87 palegreen1 154 255 154 palegreen2 144 238 144 palegreen3 124 205 124 palegreen4 84 139 84 springgreen1 0 255 127 springgreen2 0 238 118 springgreen3 0 205 102 springgreen4 0 139 69 green1 0 255 0 green2 0 238 0 green3 0 205 0 green4 0 139 0 chartreuse1 127 255 0 chartreuse2 118 238 0 chartreuse3 102 205 0 chartreuse4 69 139 0 olivedrab1 192 255 62 olivedrab2 179 238 58 olivedrab3 154 205 50 olivedrab4 105 139 34 darkolivegreen1 202 255 112 darkolivegreen2 188 238 104 darkolivegreen3 162 205 90 darkolivegreen4 110 139 61 khaki1 255 246 143 khaki2 238 230 133 khaki3 205 198 115 khaki4 139 134 78 lightgoldenrod1 255 236 139 lightgoldenrod2 238 220 130 colorlist 576 lightgoldenrod3 205 190 112 lightgoldenrod4 139 129 76 lightyellow1 255 255 224 lightyellow2 238 238 209 lightyellow3 205 205 180 lightyellow4 139 139 122 yellow1 255 255 0 yellow2 238 238 0 yellow3 205 205 0 yellow4 139 139 0 gold1 255 215 0 gold2 238 201 0 gold3 205 173 0 gold4 139 117 0 goldenrod1 255 193 37 goldenrod2 238 180 34 goldenrod3 205 155 29 goldenrod4 139 105 20 darkgoldenrod1 255 185 15 darkgoldenrod2 238 173 14 darkgoldenrod3 205 149 12 darkgoldenrod4 139 101 8 rosybrown1 255 193 193 rosybrown2 238 180 180 rosybrown3 205 155 155 rosybrown4 139 105 105 indianred1 255 106 106 indianred2 238 99 99 indianred3 205 85 85 indianred4 139 58 58 sienna1 255 130 71 sienna2 238 121 66 sienna3 205 104 57 sienna4 139 71 38 burlywood1 255 211 155 burlywood2 238 197 145 burlywood3 205 170 125 burlywood4 139 115 85 wheat1 255 231 186 wheat2 238 216 174 wheat3 205 186 150 colorlist 577 wheat4 139 126 102 tan1 255 165 79 tan2 238 154 73 tan3 205 133 63 tan4 139 90 43 chocolate1 255 127 36 chocolate2 238 118 33 chocolate3 205 102 29 chocolate4 139 69 19 firebrick1 255 48 48 firebrick2 238 44 44 firebrick3 205 38 38 firebrick4 139 26 26 brown1 255 64 64 brown2 238 59 59 brown3 205 51 51 brown4 139 35 35 salmon1 255 140 105 salmon2 238 130 98 salmon3 205 112 84 salmon4 139 76 57 lightsalmon1 255 160 122 lightsalmon2 238 149 114 lightsalmon3 205 129 98 lightsalmon4 139 87 66 orange1 255 165 0 orange2 238 154 0 orange3 205 133 0 orange4 139 90 0 darkorange1 255 127 0 darkorange2 238 118 0 darkorange3 205 102 0 darkorange4 139 69 0 coral1 255 114 86 coral2 238 106 80 coral3 205 91 69 coral4 139 62 47 tomato1 255 99 71 tomato2 238 92 66 tomato3 205 79 57 tomato4 139 54 38 colorlist 578 orangered1 255 69 0 orangered2 238 64 0 orangered3 205 55 0 orangered4 139 37 0 red1 255 0 0 red2 238 0 0 red3 205 0 0 red4 139 0 0 deeppink1 255 20 147 deeppink2 238 18 137 deeppink3 205 16 118 deeppink4 139 10 80 hotpink1 255 110 180 hotpink2 238 106 167 hotpink3 205 96 144 hotpink4 139 58 98 pink1 255 181 197 pink2 238 169 184 pink3 205 145 158 pink4 139 99 108 lightpink1 255 174 185 lightpink2 238 162 173 lightpink3 205 140 149 lightpink4 139 95 101 palevioletred1 255 130 171 palevioletred2 238 121 159 palevioletred3 205 104 137 palevioletred4 139 71 93 maroon1 255 52 179 maroon2 238 48 167 maroon3 205 41 144 maroon4 139 28 98 violetred1 255 62 150 violetred2 238 58 140 violetred3 205 50 120 violetred4 139 34 82 magenta1 255 0 255 magenta2 238 0 238 magenta3 205 0 205 magenta4 139 0 139 orchid1 255 131 250 colorlist 579 orchid2 238 122 233 orchid3 205 105 201 orchid4 139 71 137 plum1 255 187 255 plum2 238 174 238 plum3 205 150 205 plum4 139 102 139 mediumorchid1 224 102 255 mediumorchid2 209 95 238 mediumorchid3 180 82 205 mediumorchid4 122 55 139 darkorchid1 191 62 255 darkorchid2 178 58 238 darkorchid3 154 50 205 darkorchid4 104 34 139 purple1 155 48 255 purple2 145 44 238 purple3 125 38 205 purple4 85 26 139 mediumpurple1 171 130 255 mediumpurple2 159 121 238 mediumpurple3 137 104 205 mediumpurple4 93 71 139 thistle1 255 225 255 thistle2 238 210 238 thistle3 205 181 205 thistle4 139 123 139 gray0 0 0 0 grey0 0 0 0 gray1 3 3 3 grey1 3 3 3 gray2 5 5 5 grey2 5 5 5 gray3 8 8 8 grey3 8 8 8 gray4 10 10 10 grey4 10 10 10 gray5 13 13 13 grey5 13 13 13 gray6 15 15 15 grey6 15 15 15 colorlist 580 gray7 18 18 18 grey7 18 18 18 gray8 20 20 20 grey8 20 20 20 gray9 23 23 23 grey9 23 23 23 gray10 26 26 26 grey10 26 26 26 gray11 28 28 28 grey11 28 28 28 gray12 31 31 31 grey12 31 31 31 gray13 33 33 33 grey13 33 33 33 gray14 36 36 36 grey14 36 36 36 gray15 38 38 38 grey15 38 38 38 gray16 41 41 41 grey16 41 41 41 gray17 43 43 43 grey17 43 43 43 gray18 46 46 46 grey18 46 46 46 gray19 48 48 48 grey19 48 48 48 gray20 51 51 51 grey20 51 51 51 gray21 54 54 54 grey21 54 54 54 gray22 56 56 56 grey22 56 56 56 gray23 59 59 59 grey23 59 59 59 gray24 61 61 61 grey24 61 61 61 gray25 64 64 64 grey25 64 64 64 gray26 66 66 66 grey26 66 66 66 gray27 69 69 69 grey27 69 69 69 colorlist 581 gray28 71 71 71 grey28 71 71 71 gray29 74 74 74 grey29 74 74 74 gray30 77 77 77 grey30 77 77 77 gray31 79 79 79 grey31 79 79 79 gray32 82 82 82 grey32 82 82 82 gray33 84 84 84 grey33 84 84 84 gray34 87 87 87 grey34 87 87 87 gray35 89 89 89 grey35 89 89 89 gray36 92 92 92 grey36 92 92 92 gray37 94 94 94 grey37 94 94 94 gray38 97 97 97 grey38 97 97 97 gray39 99 99 99 grey39 99 99 99 gray40 102 102 102 grey40 102 102 102 gray41 105 105 105 grey41 105 105 105 gray42 107 107 107 grey42 107 107 107 gray43 110 110 110 grey43 110 110 110 gray44 112 112 112 grey44 112 112 112 gray45 115 115 115 grey45 115 115 115 gray46 117 117 117 grey46 117 117 117 gray47 120 120 120 grey47 120 120 120 gray48 122 122 122 colorlist 582 grey48 122 122 122 gray49 125 125 125 grey49 125 125 125 gray50 127 127 127 grey50 127 127 127 gray51 130 130 130 grey51 130 130 130 gray52 133 133 133 grey52 133 133 133 gray53 135 135 135 grey53 135 135 135 gray54 138 138 138 grey54 138 138 138 gray55 140 140 140 grey55 140 140 140 gray56 143 143 143 grey56 143 143 143 gray57 145 145 145 grey57 145 145 145 gray58 148 148 148 grey58 148 148 148 gray59 150 150 150 grey59 150 150 150 gray60 153 153 153 grey60 153 153 153 gray61 156 156 156 grey61 156 156 156 gray62 158 158 158 grey62 158 158 158 gray63 161 161 161 grey63 161 161 161 gray64 163 163 163 grey64 163 163 163 gray65 166 166 166 grey65 166 166 166 gray66 168 168 168 grey66 168 168 168 gray67 171 171 171 grey67 171 171 171 gray68 173 173 173 grey68 173 173 173 colorlist 583 gray69 176 176 176 grey69 176 176 176 gray70 179 179 179 grey70 179 179 179 gray71 181 181 181 grey71 181 181 181 gray72 184 184 184 grey72 184 184 184 gray73 186 186 186 grey73 186 186 186 gray74 189 189 189 grey74 189 189 189 gray75 191 191 191 grey75 191 191 191 gray76 194 194 194 grey76 194 194 194 gray77 196 196 196 grey77 196 196 196 gray78 199 199 199 grey78 199 199 199 gray79 201 201 201 grey79 201 201 201 gray80 204 204 204 grey80 204 204 204 gray81 207 207 207 grey81 207 207 207 gray82 209 209 209 grey82 209 209 209 gray83 212 212 212 grey83 212 212 212 gray84 214 214 214 grey84 214 214 214 gray85 217 217 217 grey85 217 217 217 gray86 219 219 219 grey86 219 219 219 gray87 222 222 222 grey87 222 222 222 gray88 224 224 224 grey88 224 224 224 gray89 227 227 227 colorlist 584 grey89 227 227 227 gray90 229 229 229 grey90 229 229 229 gray91 232 232 232 grey91 232 232 232 gray92 235 235 235 grey92 235 235 235 gray93 237 237 237 grey93 237 237 237 gray94 240 240 240 grey94 240 240 240 gray95 242 242 242 grey95 242 242 242 gray96 245 245 245 grey96 245 245 245 gray97 247 247 247 grey97 247 247 247 gray98 250 250 250 grey98 250 250 250 gray99 252 252 252 grey99 252 252 252 gray100 255 255 255 grey100 255 255 255 dark grey cinza escuro 169 169 169 darkgrey 169 169 169 dark gray 169 169 169 darkgray 169 169 169 dark blue azul escuro 0 0 139 darkblue 0 0 139 dark cyan ciano escuro 0 139 139 darkcyan 0 139 139 dark magenta magenta escuro 139 0 139 darkmagenta 139 0 139 dark red vermelho es curo 139 0 0 darkred 139 0 0 light green verde claro 144 238 144 lightgreen 144 238 144 Ver Também color name2rgb rgb2name 585 Name colorbar Desenha uma barra de cores colorbarumin umax colminmax fmt Parâmetros umin escalar real o valor mínimo associado ao esboço umax escalar real o valor máximo associado ao esboço colminmax opcional um vetor com dois componentes inteiros fmt optional um string para se ajustar o formato de exbição para as graduações da barra de cores Descrição Desenha uma barra de cores para um plot3d fec Sgrayplot etc Esta função deve ser chamada BE FORE do plot3d fec Sgrayplot porque ela ajusta e modifica a moldura para o esboço Desta for ma a barra de cores não é parte do esboço associado e assim não é modificada por uma ampliação diminuição ou rotação O argumento opcional colminmax pode ser utilizado para precisar a primeira cor associada a umin e a última cor associada a umax do mapa de cores corrente Por padrão colminmax1 nbcolors onde nbcolors é o número de cores do mapa de cores corrente O argumento opcional fmt é um string com formato C como 2f e etc Para os dois argumentos opcionais você pode utilizar a sintaxe keywordvalue que é útil para fornecer o formato sem fornecer colminmax veja o útilmo exemplo Examples exemplo 1 x linspace0181 z cos2pixsin2pix zm minz zM maxz xbasc xsetcolormapjetcolormap64 colorbarzmzM Sgrayplotxxz xtitleThe function cos2 pi xsin2 pi y exemplo 2 x linspace0181 z cos2pixsin2pix zm minz zM maxz zz abs05cos2pixcos2pix zzm minzz zzM maxzz xbasc xsetcolormapjetcolormap64 colorbar 586 drawlater subplot221 colorbarzmzM Sgrayplotxxz strf031 rect0 0 1 1 xtitleum Sgrayplot com barra de cores subplot222 colorbarzmzM plot3d1xxz xtitleum plot3d1 com barra de cores subplot223 colorbarzzmzzM plot3d1xxzz xtitleum plot3d1 com barra de cores subplot224 colorbarzzmzzM Sgrayplotxxzz strf031 rect0 0 1 1 xtitleum Sgrayplot com barra de cores drawnow exemplo 3 x linspace0181 zz abs05cos2pixcos2pix zzm minzz zzM maxzz xfyfzfgenfac3dxxzz nbcol 64 xbasc xsetcolormaphotcolormapnbcol drawlater colorbarzzmzzMfmt1f nbcol xgetlastpattern zcol dsearchzf linspacezzm zzM nbcol1 plot3dxf yf listzf zcol flag 2 6 4 xtitleum plot3d com cores de gradação interpolada drawnow xselect See Also colormap Authors B Pincon S Steer 587 Name colordef Ajusta os valores de cor padrões para exibição de diferentes esquemas de cores colordefcolorscheme colordeffcolorscheme colordefnewcolorscheme Parâmetros colorscheme string com valores possíveis white blacknone f manipulador para uma figura gráfica Descrição colordefwhite ajusta o mapa de cores padrão da figura ver gdf para jetcol ormap64 a cor de plano de fundo padrão da figura para cinza claro a cor de plano de fundo dos eixos ver gda para branco e as cores de primeiro plano da fonte e das linhas dos eixos para preto colordefblack ajusta o mapa de cores padrão da figura ver gdf para jetcol ormap64 a cor de plano de fundo padrão da figura para cinza escuro a cor de plano de fundo dos eixos ver gda para preto e as cores de primeiro plano da fonte e das linhas dos eixos para branco colordefnone ajusta o mapa de cores padrão da figura ver gdf para hsvcol ormap64 a cor de plano de fundo padrão da figura para cinza escuro a cor de plano de fundo dos eixos ver gda para preto e as cores de primeiro plano da fonte e das linhas dos eixos para branco colordeffcolorscheme ajusta as propriedades de cor da figura fornecida pelo manip ulador f tanto quanto as propriedades de cor de seus eixos correntes colordefnewcolorscheme cria uma nova janela de gráficos e ajusta suas pro priedades de cor bem como as propriedades de seus eixos Exemplos Adicionar aqui instruções Scilab e comentários Ver Também gdf gda figureproperties axesproperties Autor S Steer INRIA 588 Name colormap mapa de cores Descrição Um mapa de cores cmap é definido por uma matriz m x 3 m é o número de cores A cor de número i é dada pela tripla cmapi1 cmapi2 cmapi3 correspondentes às intensidades de ver melho verde e azul entre 0 e 1 De início 32 cores são definidas no mapa de cores Você pode modificar o mapa de cores de uma figura através da opção setfcolormapcmap onde f é o manipulador da figura Cada cor no mapa de cores possui um identificador que você deve utilizar para especificar a cor na maioria das funções de esboço Para visualizar os identificadores use a função getcolor As funções hotcolormap jetcolormap e graycolormap fornecem mapas de cores com variação contínua de cores Você pode obter o mapa de cores padrão através de cmapgetsdfcolormap Exemplos n64 rlinspace01n glinspace10n bonesr cmapr g b fgcf fcolormapcmap plot3d1 fcolormapgetsdfcolormap Ver Também autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcolormap hsv colormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summer colormap whitecolormap wintercolormap color getcolor 589 Name Compoundproperties Descrição das propriedades da entidade compound Descrição A entidade Compound é uma entidade de terceiro nível na hierarquia de entidades gráficas Esta en tidade define interdependências entre várias entidades gráficas e suas propriedades de visibilidade global parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Text deve ser do tipo Axes ou Compound children um vetor contendo manipuladores para os objetos gráficos galhos do Compound Estes obje tos gráficos podem ser do tipo Compound Rectangle Polyline Patch Segs Arc Grayplot visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o valor é on onde as entidades gráficas galhos do Compound são desenhadas Se off nenhum dos galhos do Compound é desenhado na tela userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da figura e recuperála Ver Também glue unglue graphicsentities Autor Djalel ABDEMOUCHE 590 Name contour curvas de nível em uma superfície 3d contourxyznzthetaalphalegflageboxzlev contourxyznzoptargs Parâmetros xy vetores de reais de tamanhos n1 e n2 z matriz de reais de tamanho n1n2 os valores da função sobre o gride ou uma função Scilab que define uma superfície zfxy nz os valores de nível ou o número de níveis Se nz for um inteiro seu valor fornece o número de níveis igualmente espaçados de zmin a zmax como segue z zmin 1nzzmaxzminnz1 Note que os níveis zmin e zmax não são desenhados genericamente eles são reduzidos a pontos mas podem ser adicionados através de imjm findz zmin ou zmax plot2dximyjm9000 Se nz for um vetor nzi fornece o valor da iésima curva de nível Note que isto pode ser útil para se visualizar as curvas de nível zmin e zmax para se adicionar uma tolerância eps nzzminepszmaxeps optargs uma seqüência de declarações key1value1 key2value2 onde keys podem ser thetaalphalegflag eboxzlev ver abaixo Neste caso a ordem não possui significa do especial theta alpha valores reais de dados em graus as coordenadas esféricas do ponto de observação leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho três flagmodetypebox mode string de representação de modo mode0 as curvas são desenhadas na superfície definida por xyz contour 591 mode1 as curvas são desenhadas em um esboço 3d e sobre o plano definido pela equação zzlev mode2 as curvas são desenhadas em um esboço 2D type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados ebox usado quando type em flag é 1 Especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax zlev número real contour 592 Descrição contour desenha curvas de nível de uma superfície z fxy As curvas de nível são desenhadas sobre uma superfície 3d Os argumentos opcionais são os mesmos que os da função plot3d exceto por zleve seus significados são os mesmos Eles controlam o desenho das curva de nível em um esboço 3d Apenas flag1mode tem significado especial mode0 as curvas são desenhadas na superfície definida por xyz mode1 as curvas são desenhadas em um esboço 3d e sobre o plano definido pela equação zzlev mode2 as curvas são desenhadas em um esboço 2D Você pode modificar o formato dos pontos flutuantes impressos sobre os níveis utilizando xsetfpfstring onde string fornece o formato em na sintaxe de formato C por exem plo string3f Use string para voltar ao formato padrão e use string para suprimir a impressão Geralmente é usado contour2d para se esboçar curvas de nível em um esboço 2d Entre com o comando contour para visualizar uma demonstração Exemplos tlinspacepipi30 function zmysurfacexyzxsinx2cosyendfunction contourttmysurface10 mudando o formato da impressão dos níveis xsetfpf1f xbasc contourttmysurface10 3D xbasc zfevalttmysurface plot3dttzcontourttz02absz20flag0 2 4 Ver Também contour2d plot3d Autor JPhC 593 Name contour2d curvas de nível de uma superfície em um esboço 2d contour2dxyznzstylestrflegrectnax contour2dxyznzoptargs Parâmetros xy vetores de reais de tamanhos n1 e n2 o grid z matriz de reais de tamanho n1n2 os valores da função sobre o grid ou uma função Scilab que define uma superfície zfxy nz os valores de nível ou o número de níveis Se nz for um inteiro seu valor fornece o número de níveis igualmente espaçados de zmin a zmax como segue z zmin 1nzzmaxzminnz1 Note que os níveis zmin e zmax não são desenhados genericamente eles são reduzidos a pontos mas podem ser adicionados através de imjm findz zmin ou zmax plot2dximyjm9000 Se nz for um vetor nzi fornece o valor da iésima curva de nível optargs representa uma seqüência de declarações key1value1key2value2 onde key1 key2 pode ser um dos seguintes style leg rect nax strf ou axesflag e frameflag ver plot2d stylestrflegrectnax ver plot2d O argumento style fornece os estilos de tracejado ou cores que serão usadas para as curvas de nível Deve ter o mesmo tamanho que o número de níveis Descrição contour2d desenha curvas de nível de uma superfície zfxy em um esboço 2d Os valores de fxy são dados pela matriz z nos pontos de grid definidos por por x e y Você pode modificar o formato dos pontos flutuantes impressos sobre os níveis utilizando xsetfpfstring onde string fornece o formato em na sintaxe de formato C por exem plo string3f Use string para voltar ao formato padrão e use string para suprimir a impressão Este último recurso é útil em conjunção com legends para exibir os números de nível em uma legenda e não diretamente em curvas de nível como de uso ver Exemplos Os argumentos opcionais stylestrflegrectnax podem ser passados através de uma seqüência de declarações key1value1 key2value2 onde podem ser stylestrflegrectnax Neste caso a ordem não tem significado especial contour2d 594 Use contour para esboçar curvas de nível em uma superfície 3d Exemplos contour2d110110rand10105rect001111 mudando o formato de impressão dos níveis xsetfpf2f clf contour2d110110rand10105rect001111 agora um exemplo com números de níveis desenhados em uma legenda Cuidado há alguns truques aqui x linspace04pi80 z cosxcosx clf fgcf xsetfpf truque 1 isto faz com que alguns números de níveis não sejam impressos sobre as curvas de nível fcolormapjetcolormap7 truque 2 para fazer com que se possa colocar a legenda à direita sem sem interferir com as curvas de nível use rect com um valor xmax grande o suficiente contour2dxxz075025075frameflag3rect005pi4pi truque 3 use legends note que a função mais prática legend não funcionará quando um dos níveis for formado por duas curvas legendsstring07502507517lr xtitleAlgumas curvas de nível da função cosxcosy Ver Também contour contour2di plot2d Autor JPhC 595 Name contour2di Computa curvas de nível em um esboço 2d xcyccontour2dixyznz Parâmetros xy dois vetores de reais de tamanhos n1 e n2 definindo o grid z matriz de reais de tamanho n1n2 os valores da função nz os valores de nível ou o número de níveis Se nz for um inteiro seu valor fornece o número de níveis igualmente espaçados de zmin a zmax como segue z zmin 1nzzmaxzminnz1 Note que os níveis zmin e zmax não são desenhados genericamente eles são reduzidos a pontos mas podem ser adicionados através de imjm findz zmin ou zmax plot2dximyjm9000 Se nz for um vetor nzi fornece o valor da iésima curva de nível xcyc vetores de tamanhos idênticos contendo as definições dos contornos Ver detalhes abaixo Descrição contour2di computa as curvas de nível de uma superfície zfxy em um esboço 2d Os valores de fxy asão dados pela matriz z nos pontos de grid definidos por x e y xc1 contém o nível associado ao primeiro caminho de contorno yc1 contém o número N1 de pontos definindo este caminho de contorno e xc11N1 yc11N1 contém as coordenadas dos pontos do caminho O segundo caminho começa em xc2N1 e yc2N1 e assim por diante Exemplos xcyccontour2di110110rand10105 k1nyckc1 while kycksizexc nyck plot2dxck1nyck1nc cc1 kkn1 end contour2di 596 Ver Também contour fcontour fcontour2d contour2d plot2d xset Autor JPhC 597 Name contourf Curvas de nível preenchidas de uma superfície em um esboço 2d contourfxyznzstylestrflegrectnax Parâmetrtos xy dois vetores de reais de tamanhos n1 e n2 definindo o grid z matriz de reais de tamanho n1n2 os valores da função nz os valores de nível ou o número de níveis Se nz for um inteiro seu valor fornece o número de níveis igualmente espaçados de zmin a zmax como segue z zmin 1nzzmaxzminnz1 Note que os níveis zmin e zmax não são desenhados genericamente eles são reduzidos a pontos mas podem ser adicionados através de imjm findz zmin ou zmax plot2dximyjm9000 Se nz for um vetor nzi fornece o valor da iésima curva de nível stylestrflegrectnax ver plot2d O argumento style fornece as cores a serem utilizadas pelas curvas de nível Deve ter o mesmo tamanho que o número de níveis Descrição contourf pinta a superfície entre duas curvas de nível consecutivas zfxy em um esboço 2d Os valores de fxy são fornecidos pela matriz z nos pontos de grid definidos por x e y Você pode mudar o formato dos pontos flutuantes impressos sobre os níveis utilizando xsetfpfstring onde string fornece o formato em sintaxe de formato C por exemplo string3f Use string para voltar ao formato padrão Entre com o comando contourf para visualizar uma demonstração Exemplos contourf110110rand1010515011 001111 function zpeaksxy x1xones1sizey contourf 598 y1yonessizex1 z 31x12expx12 y112 10x15 x13 y15expx12y12 13expx112 y12 endfunction function zpeakit x4014yxzpeaksxy endfunction zpeakit levels61logspace5010logspace501018 msizelevels n fix38m r 1nn onesmn1 g zerosn1 1nn onesm2n1 b zeros2n1 1m2nm2n h r g b xsetcolormaph xsetfpf xbasc contourfz61logspace5010logspace5010180ones1m xsetfpf xbasc contourfz61logspace5010logspace501018 Ver Também contour fcontour fcontour2d contour2di plot2d xset Autor JPhC 599 Name coolcolormap Mapa de cores de ciano a magenta cmapcoolcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição coolcolormap computa um mapa de cores com n cores variando de ciano a magenta Exemplos f scf plot3d1 fcolormap coolcolormap32 Ver Também colormap autumncolormap bonecolormap coppercolormap graycolormap hotcolormap hsvcol ormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercol ormap whitecolormap wintercolormap 600 Name coppercolormap Mapa de cores de preto a um tom claro de cobre cmapcoppercolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição coppercolormap computa um mapa de cores com n cores que variam de preto a um tom claro de cobre Exemplos f scf plot3d1 fcolormap coppercolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap graycolormap hotcolormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 601 Name copy Copia uma entidade de gráficos copyh copyhhaxes hcopycopyh Parâmetros h manipulador da entidade a ser copiada haxes manipulador da entidade raiz para destino Deve ser uma entidade Axes de eixos hcopy manipulador da entidade copiada Descrição Esta rotina pode ser usada para copiar uma entidade de gráficos com todos os seus valores de pro priedades retornando o manipulador da nova entidade Se haxes for omitido a entidade gráfica é clonada e copiada no mesmo na mesma entidade Axes raiz Exemplos subplot211a1gca plot2d egce p1echildren1 p2copyp1p2data2p2data205 subplot212a2gca a2databoundsa1databounds copyp1a2 Ver Também get set delete move graphicsentities Autor Djalel ABDEMOUCHE 602 Name delete Deleta uma entidade gráfica e seus galhos deleteh deletehcallback delete deleteall Parâmetros h manipulador da entidade gráfica a ser deletada h pode ser um vetor de manipuladores em qual caso todos os objetos identificados por hi serão deletados all palavrachave string opcional Descrição Esta rotina pode ser utilizada para deletar uma entidade gráfica identificada pelo manipulador dado como argumento Neste caso todos os galhos desta entidade gráfica serão deletados Sem qualaquer argumento delete remove a entidade corrente Com o argumento all deleta todas as entidades da figura corrente O argumento callback ainda não é manipulado Exemplos subplot211 t110plot2dtt2 subplot223 plot3d subplot224 plot2d xfrect1031 agetcurrentaxes delete deletando o novo objeto gráfico criado deleteachildren deletando todos os galhos dos eixos corentes deletea deletando os eixos deleteall deletando todos os objetos gráficos da figura Ver Também get set copy move ishandlevalid graphicsentities Autor Djalel ABDEMOUCHE 603 Name dragrect Arrasta retângulos com o mouse finalrectbtndragrectinitialrect Parâmetros initialrect matrtiz 4xn contendo as definições iniciais do retângulo Cada coluna contém xesquerdo ytopo largura altura Se apenas um retângulo estiver presente initialrect pode ser também um vetor finalrect um retângulo xesquerdo ytopo largura altura btn um inteiro o número do botão do mouse clicado Descrição dragrect arrasta um ou mais retângulos para qualquer lugar da tela A matriz rect 4xn define os retângulos Cada coluna de initialrect deve conter a posição inicial do retângulo como valores xesquerdoytopolarguraaltura Quando um botão é clicado dragrect retorna as definições dos retângulos finais em finalRect Exemplos xsetechfrect00100100 rdragrect10103010 xrectr Ver Também xrect xrects xclick xgetmouse 604 Name draw Desenha uma entidade draw drawh Parâmetros h a o manipulador de uma entidade a ser desenhada h pode ser um vetor de manipuladores Neste caso todos os objetos identificados por hi will serão desenhados Descrição Esta função pode ser utilizada para desenhar entidades especificadas por h mesmo se a propriedade de figura raiz immediatedrawing for off Se nenhum argumento for especificado o objeto corrente é desenhado Note que a janela não deve ser redimensionada se for esses objetos serão escondidos Exemplos subplot212 agca plot2d drawlater subplot211 plot2d1 modo de desenho padrão egce drawechildren2 desenhando uma única poligonal dos segundos eixos echildren1visibleoff podemos escolher tornar uma linha invisível drawe desenha o Compound e seus galhos ltgt desenha todas as poligonais visíveis drawnow agora echildren1visibleon Ver Também get set drawnow drawlater graphicsentities Autores Djalel ABDEMOUCHE FLeray 605 Name drawaxis Desenha um eixo drawaxisoptions opções xydirsubintfontsizeformatnsegtextcolorticscolortics Parâmetros dirstring é utilizado para se especificar a direção dos tiques string can pode ser escolhido entre urdl e l é o valor padrão Os valores urdl correspondem respectivamente a para cima para direita para baixo e para esquerda ticsstring um flag definindo como os tiques são fornecidos string pode ser escolhido entre vr e i e v é o valor padrão xy dois vetores que fornecem as posições dos tiques val string matrix uma matriz de strings que quando dada fornece os strings a serem impressos ao longo dos eixos nas posições dos tiques fontsizeint especifica o tamanho de fonte a ser utilizado para se exibir os valores ao longo dos eixos O valor padrão é 1 que corresponde ao tamanho de fonte atual formatnstring formato a ser utilizado para se exibir os números ao longo dos eixos seg 1 ou 0 um flag que controla a exibição do segmento base do eixo o valor padrão é 1 subintinteger um inteiro que fornece o número de subintervalos entre dois tiques maiores textcolorinteger especifica a cor a ser utilizada para a exibição de valores ao longo dos eixos O valor padrão é 1 que corresponde a cor corrente ticscolorinteger especifica a cor a ser utilizada para o desenho dos tiques O valor padrão é 1 que corresponde à cor corrente Descrição drawaxis é utilizado para desenhar um eixo na direção horizontal ou vertical A direção do eixo é dada por dir dir u ou d fornece a direção com os tiques indo para cima u ou para baixo d dir r ou l fornece um eixo vertical com os tiques indo para a direita r ou esquerda l x e y fornecem as posições dos tiques dos eixos Se o eixo é horizontal então y deve ser um escalar ou pode ser omitido e x é um vetor Scilab O significado de x é controlado por tics Se ticsv então x fornece as posições dos tiques ao longo do eixo x Se ticsr então x deve ter tamanho 3 xxminxmaxn e n fornece o número de intervalos drawaxis 606 Se ticsi então x deve ser de tamanho 4 xk1k2an Então xmink110a xmaxk210a e n fornece o número de intervalos Se y for omitido então o eixo será posicionado ao topo da moldura se diru ou ao fundo se dird Por padrão os números são impressos ao longo do eixo Eles são impressos utilizandose um formato padrão que pode ser alterado através de formatn ITambém é possível exibir strings dados e não números isto é feito se val é fornecido O tamanho de val deve corresponder ao número de tiques Exemplos plot2d1101101020 eixo horizontal drawaxisx27y4diruticsv eixo horizontal na parte superior da moldura drawaxisx27diruticsv eixo horizontal na parte inferior da moldura drawaxisx27dirdticsv eixo horizontal dado por um intervalo drawaxisx273y4dirdticsr eixo vertical drawaxisx4y27dirrticsv drawaxisx2y273dirlticsr drawaxisy27dirrticsv drawaxisy27dirlticsv eixo horizontal com strings exibidos nas posições dos tiques drawaxisx27y8diruticsvvalAstring16 eixo vertical com strings exibidos nas posições dos tiques drawaxisx8y27dirrticsvvalBstring16 eixo horizontal dado com um intervalo i drawaxisx2503y9diruticsi drawaxisx9y2503dirrticsisubint5 eixo horizontal de novo drawaxisx27y4diruticsvfontsize10textcolor9ticscolor7seg0subint20 Autor JPhC 607 Name drawlater Torna galhos dos eixos invisíveis drawlater Descrição Esta função pode ser utilizada para não se exibir imediatamente na figura corrente os próximos objetos gráficos a serem criados por uma chamada a funções de altonível tais como funções de esboço ou ajuste de propriedades de objetos existentes A propriedade immediatedrawing da figura cor rente é ajustada para off para se adiar os próximos desenhos Pode ser utilizada especialmente com a função Para reabilitar immediatedrawing para a figura corrente você pode utilizar a função Aviso note que entre chamadas às funções drawlater e drawnow a figura corrente pode ser modifi cada Logo estas funções devem ser usadas com cuidado Exemplos Exemplo 1 uma entidade Axes uma entidade Figure drawlater xfarc2555115064360 xfarc5555115064360 xfrect3832 xfrect2752 xfrect327811 xfrect4478141 xfrect24158 xstring0339A Scilab Car agetcurrentaxes achildren1fontsize4 achildren1fontstyle4 achildren1background5 achildren3background8 achildren4background8 achildren5background17 achildren6background17 achildren7background25 achildren8background25 xclickdrawnow Exemplo 2 duas entidades Axes uma entidade Figure subplot212 agca drawlater o que estará presente nestes eixos será desenhado depois plot2d desenhará estes eixos e seus galhos depois subplot211 aviso mudamos os eixos plot2d1 modo de desenho padrão drawa os eixos são visíveis apenas se você não resdesenhar a janela drawnow tudo está visível drawlater 608 Ver Também get set drawnow graphicsentities Autor Djalel ABDEMOUCHE FLeray 609 Name drawnow Desenha entidades gráficas escondidas drawnow Descrição Considerando a figura corrente esta função pode ser usada para desenhar as entidades gráficas es condidas e todos os seus galhos que podem ter sido adiados por uma chamada anterior à função drawlater A propriedade immediatedrawing da figura corrente é ajustada para on Pode ser usado especialmente com a função drawlater Exemplos fgetcurrentfigure manipulador da figura corrente drawlater subplot221 t110plot2dtt2 subplot222 x017plot2dxcosx2 subplot234 plot2dtcost3 subplot235 plot2dxsin2x5 subplot236 plot2dttan2t drawgca desenhando os eixos correntes e seus galhos drawfchildren3 4 desenhando os eixos especificados e seus galhos drawnow desenhando a figura corrente Ver Também get set drawlater graphicsentities Autores Djalel ABDEMOUCHE FLeray 610 Name editcurv editor interativo de curvas gráficas xyokgc editcurvy xyokgc editcurvxy xyokgc editcurvxyjob xyokgc editcurvxyjobtit xyokgc editcurvxyjobtitgc Parâmetros x vetor de coordenadas x y vetor de coordenadas y job um string formado por um a três dos caracteres axy a adicionar pontos à curva editada x modificar coordenadas x dos pontos das curvas editadas y modificar coordenadas y dos pontos das curvas editadas tit um vetor de três strings que fornecem a legenda da curva gc uma lista de parâmetros de janela de gráficos gclistrectnax rect bordas dos gráficos ver plot2d para detalhes nax parâmetros de graduação ver plot2d para detalhes ok indicador Se ok t retorna com menu ok senão retorna com menu abort lista objetos gráficos criados sob editcurv Descrição editcurv é um editor de curvas gráficas interativo Para adicionar um ponto novo apenas clique na localização desejada o ponto adicionado será conectado à extremidade mais próxima Para mover um ponto clique nele arraste o mouse para a nova posição e clique para ajustar a nova posição Autor Serge Steer 611 Name errbar adiciona barras de erro veriticais a um esboço 2d errbarxyemep Parâmetros xyemep quatro matrizes de mesmo tamanho Descrição errbar adiciona barras de erro verticais a um esboço 2d x e y têm o mesmo significado que em plot2d emij e epij são os intervalos de erro sobre os valores yij yij emijyijepij Entre com o comando errbar para visualizar uma demonstração Exemplos t0012pi ysint cost xt t plot2dxy errbarxy005onesx003onesx Ver Também plot2d Autor JPhC 612 Name eval3d valores de uma função em um grid zeval3dfunxy Parâmetros fun função que aceita vetores como argumentos xy 2 vetores de tamanhos 1n1 e 1n2 valor padrão para y yx z matriz de tamanho n1n2 Descrição Esta função retorna uma matriz zn1n2 zijfunxiyj Se a função fun não aceitar argumentos do tipo vetor use a primitiva feval Exemplos x55yx deffzfxyz xy zeval3dfxy plot3dxyz deffzfxyz xy zfevalxyf plot3dxyz Ver Também feval Autor Steer S 613 Name eval3dp computa facetas 3d de uma superfície parametrizada XfYfZfeval3dpfunp1p2 Parâmetros XfYfZf matrizes de tamanho 4n1m1 Xfi Yfi e Zfi são respectivamente as coordenadas nos eixos x y e z dos 4 pontos da iésima faceta de quatro lados fun uma função do Scilab p1 um vetor de tamanho n p2 um vetor de tamanho m Descrição eval3dp computa uma representação de uma faceta de quatro lados de uma superfície 3d parametrizada definida pela função fun funp1p2 computa as coordenadas nos eixos x y e z dos pontos correspondentes da superfície como xiyizifunp1ip2i Isto é usado para eficiência Exemplos p1linspace02pi10 p2linspace02pi10 deffxyzscpp1p2xp1sinp1cosp2 yp1cosp1cosp2 zp1sinp2 XfYfZfeval3dpscpp1p2 plot3dXfYfZf Ver Também genfac3d plot3d 614 Name event handler functions Protótipo de funções que podem se utilizadas como gerenciadoras de even tos enventhandlerfunctionwinxyibut Parâmetros win número da janela onde o evento ocorreu x coordenada X em píxeis do ponteiro do mouse no momento onde o evento ocorreu y coordenada Y em píxeis do ponteiro do mouse no momento onde o evento ocorreu ibut número correspondente ao tipo de evento Descrição Quando o modo de gerenciador de eventos está habilitado o Scilab chamaráo gerenciador de eventos especificado a cada vez que um evento ocorre na janela gráfica A função de gerenciamento de evento deve concordar com o protótipo acima A cada vez que um evento ocorre a função é chamada e os quatro eventos são ajustados de acordo com o número da janela a posição do mouse e o tipo do evento O parâmetro ibut toma um dos seguintes valores dependendo do tipo do evento ocorrido ibut0 o botão esquerdo foi pressionado ibut1 o botão do meio foi pressionado ibut2 o botão direito foi pressionado ibut3 o botão esquerdo do mouse foi clicado ibut4 o botão do meio do mouse foi clicado ibut5 o botão direito do mouse foi clicado ibut10 o botão esquerdo do mouse foi clicado duas vezes ibut11 o botão do meio do mouse foi clicado duas vezes ibut12 o botão direito do mouse foi clicado duas vezes event handler functions 615 ibut5 o botão esquerdo do mouse foi liberado ibut4 o botão do meio do mouse foi liberado ibut3 o botão direito do mouse foi liberado ibut1 o ponteiro do mouse foi movido ibut 32 uma tecla com código asciiibut foi pressionada ibut 32 uma tecla com código asciiibut foi liberadav ibut 100032 uma tecla com código asciiibut1000 foi pressionada enquanto a tecla CTRL estava sendo pres sionada ibut1000 a janela de gráficos foi fechada Por exemplo digamos que o nome da função de gerenciamento de eventos seja fooHandler para a janela de número 0 Um clique com o botão esquerdo na janela na posição 100150 em píxeis será equivalente a chamar fooHandler 0 100 150 3 Ver figureproperties ou seteventhandler para mais informações sobre como especificar o nome do gerenciador de eventos Exemplos function myeventhandlerwinxyibut if ibut1000 then returnend xyxchangexyi2f xinfomsprintfEvento de código d na posição do mouse é ffibutxy endfunction plot2d fig gcf figeventhandler myeventhandler figeventhandlerenable on agora mova o mouse sobre a janela gráfica pressione e libere as teclas com shift pressionado ou não e com Ctrl pressionado ou não pressione um botão espere um pouco e libere pressione e libere um botão clique duas vezes em um botão figeventhandlerenable off suprimindo o gerenciador de eventos Ver Também figureproperties seteventhandler xgetmouse xclick event handler functions 616 Autor JeanBaptiste Silvy 617 Name fac3d Esboço de uma superfície 3d obsoleta fac3dxyzthetaalphalegflagebox fac3d1xyzthetaalphalegflagebox Descrição Estas funções estão obsoletas e foram substituídas por plot3d e plot3d1 Ver Também plot3d plot3d1 618 Name fchamp campo direcional de uma EDO 2d de primeira ordem fchampftxryrarfactrectstrf fchampftxryroptargs Parâmetros f uma external função ou string ou uma lista descrevendo a EDO Pode ser um nome de função f onde f se supõe ser uma função do tipo yftxy p1pn f retorna um vetor coluna de tamanho 2 y que fornece o valor do campo direcional f no ponto xyxy e no tempo t Também pode ser um objeto do tipo lista listfP1Pn onde f é uma função do tipo yftxyp1pn e Pi fornece o valor do parâmetro pi t o tempo selecionado xryr dois vetores linhas de tamanhos n1 e n2 que definem o grid sobre o qual o campo direcional é computado optargs representa uma seqüência de decarações key1value1key2value2 onde key1 key2 pode ser um dos seguintes arfact rect strf ver abaixo arfactrectstrf argumentos opcionais ver champ Descrição fchamp é utilizado para desenhar o campo direcional de uma EDO 2d de primeira ordem definida pela função externa f Note que se a EDO é autônoma o argumento t não possui utilidade mas deve ser fornecido Entre com o comando fchamp para visualizar uma demonstração Exemplos deffxdot derpoltx xd1 x2 xd2 x1 1 x12x2 xdot xd1 xd2 xf 1011 yf 1011 fchampderpol0xfyf clf fchampderpol0xfyf12222011 Ver Também champ champ1 Autor JPhC 620 Name fcontour curvas de nível sobre uma superfície 3d definida por uma função fcontourxryrfnzthetaalphalegflageboxzlev fcontourxryrfnzoptargs Descrição Esta função está obsoleta Está agora inclusa na função contour Autor JPhC 621 Name fcontour2d curvas de nível de uma superfície definida por uma função em um esboço 2d fcontour2dxryrfnzstylestrflegrectnax fcontour2dxryrfnzoptargs Descrição Esta função está obsoleta Está agora inclusa na função contour2d Autor JPhC 622 Name fec Esboço pseudocolorido triangular de uma função definida por uma malha triangular fecxytrianglesfuncoptargs fecxytrianglesfuncstrflegrectnaxzminmaxcolminmaxcoloutmesh Parâmetros xy dois vetores de tamanho n xiyi fornece as coordenadas do nó i func vetor de tamanho n funci fornece o valor no nó i da função para a qual queremos o esboço pseudocolorido triangles é uma matriz Ntr5 Cada linha de triangles especifica um triângulo da malha trianglej numbernode1node2node3flag node1node2node3 são os números dos nós que constituem o triângulo number é o número do triângulo e flag é um inteiro que não é usado na função fec optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes strf leg rect nax zminmax colminmax colout mesh ver plot2d para os quatro primeiros strflegrectnax ver plot2d zminmax vetor com dois compontenteszmin zmax útil para animações em particular colminmax vetor de dois inteiros positivos colmin colmax colout vetor de dois inteiros undermincol uppermaxcol mesh escalar booleano valor padrão f deve ser verdadeiro se você também quiser exibir a malha Descrição Esta função é boa para se desenhar soluções de elementos finitos triangulares lineares ou simplesmente para se exibir uma função definida sobre uma triangularização A interpolação de cores é feita através de um software de computação e portanto não é tão rápida A função colorbar pode se utilizada para se visualizar a escala de cores ver a seção de exemplos O argumento zminmax fornece os valores de z asosicados às primeira e últimas cores do mapa de cores corrente Mais exatamente se o mapa de cores possue nc cores e se notarmos dz zmaxzmin nc então a parte da triangularização onde zmin i1dz z zmin i dz é preenchida com a cor i Por padrão zmin minfunc e zmax maxfunc Se você quiser uma animação com valores da função que variam no tempo tome para zmin e zmax os valores máximo e mínimo globais ou algo próximo O argumento colout permite que o usuário escolha as cores para as duas regiões extremas func zmin and func zmax undermincol e uppermaxcol podem ser iguais independen temente a fec 623 1 neste caso a mesma cor que a zona de vizinhança é utilizada CUIDADO você não vê que o limite correspondente é cruzado este é o caso padrão 0 neste caso a região de extremidade não é pintanda k k sendo um índice de cor válido no mapa de cores corrente a região de extremidade é pintada com a cor k Se você não quiser usar o mapa de cores completo você pode utilizar o argumento 1 colmin colmax nc nc sendo o número de cores do mapa de cores corrente para utilizar apenas a sub parte colmincolmax do mapa de cores por padrão todas as cores do mapa de cores são utilizadas Ver arquivos de demonstração demosfec fecex1 é um simples arquivo de exemplo no qual uma malha e uma função sobre esta malha é completamente construída em sintaxe do Scilab fecex2 é um exemplo no qual a malha e os valores da função foram computados por um construtor de malhas externo malha do tipo amdba e um programa externo Um conjunto de macros fornecido pelo arquivo macrossci pode ser utilizado para ler os arquivos de dados no Scilab e esboçar os resultados Exemplos definindo uma minitriangularização 4 vértices 2 triângulos x 0 1 0 1 y 0 0 1 1 T 1 1 2 3 1 2 3 4 1 1 z 0 1 0 1 valores da função em cada vértice xbasc xsetcolormapjetcolormap64 subplot121 colorbar11 fecxyTzstrf040mesht xtitleexemplo de fec com a malha subplot122 colorbar11 fecxyTzstrf040 rmq meshf por padrão xtitleexemplo de fec em a malha xselect este exemplo mostra o efeito de zminmax e usa os dados de exemplos anteriores você tem que executálos primeiro xbasc xsetcolormapjetcolormap64 colorbar0505 cuidado a barra de cores deve ser ajustada na mão fecxyTzstrf040 zminmax05 05 mesht xtitleexemplo de fec utilizando o argumento zminmax xselect este exemplo mostra os efeitos de zminmax e colout Utiliza também os dados de exemplos anteriores você tem que executálos primeiro xbasc xsetcolormapjetcolormap64 fec 624 subplot221 colorbar0505 fecxyTzstrf040 zminmax05 05 colout0 0 mesht xtitleexemplo de fec utilizando zminmax e colout 0 0 subplot222 colorbar0505 fecxyTzstrf040 zminmax05 05 colout32 32 mesht xtitleexemplo de fec utilizando zminmax e colout 32 32 subplot223 colorbar0505 fecxyTzstrf040 zminmax05 05 colout1 0 mesht xtitleexemplo de fec utilizando zminmax e colout 1 0 subplot224 colorbar0505 fecxyTzstrf040 zminmax05 05 colout0 1 mesht xtitleexemplo de fec utilizando zminmax e colout 0 1 xselect este exemplo mostra um recurso de colminmax utilizando dois mapas de cores para dois subesboços Também utiliza dados de exemplos anteriores xbasc xsetcolormaphotcolormap64jetcolormap64 subplot121 colorbar111 64 fecxyTzstrf040 colminmax1 64 mesht xtitlefec utilizando mapa de cores hot subplot122 colorbar1165 128 fecxyTzstrf040 colminmax65 128 mesht xtitlefec utilizando mapa de cores jet xselect Ver Também colorbar Sfgrayplot Sgrayplot 625 Name fecproperties Descrição das propriedades da entidade Fec Descrição A entidade Fec é uma folha na hierarquia de entidade gráficas Representa um esboço 2d de elementos finitos ver fec Sgrayplot parent esta propriedade contém o manipulador para a raiz A raiz da entidade Fec deve ser do tipo Ax es ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores Fec correntemente não possuem galhos visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o esboço é visível a propriedade é on Se off o esboço não é exibido na tela data uma matriz de três colunas xyf onde xi e yi são as coordenadas do iésimo nó fi é o valor associado ao nó i triangles uma matriz de cinco colunas tnn1n2n3flag tnj é o número do triângulo n1j n2j e n3j são índices dos nós que constituem o triângulo flagj não é us ado zbounds este vetor de tamanho 2 zminzmax fornece os valores z associados às primeira e última cores do mapa de cores corrente Mais exatamente se o mapa de cores possui nc cores e se notarmos dz zmaxzminnc então a parte da triângularização onde zmin i1dz z zmin i dz é preenchida com a cor i Por padrão o valor da propriedade zbounds é 00 Neste caso zmin e zmax são automaticamente ajustados para os valores mínimo e máximo do argumento func outsidecolor este vetor de tamanho 2 cmin cmax define a cor utilizada quando os valores dos nós estão fora do intervalo zbounds zminzmax Quando os valores dos nós são menores do que zmin a cor com índice cmin é utilizada Quando os valores dos nós são menores do que zmax a cor com índice cmax é utilizada Por padrão o valor da propriedade outsidecolor é 00 Neste caso cmin e cmax são automaticamente ajustados para os limites do mapa de cores Se cmin ou cmax são negativos então os valores fora do intervalo zbounds não são exibidos eles aparecem transparentes colorrange este vetor de tamanho 2 rmin rmax permite utilizar apenas uma parte do mapa de cores para a exibição rmin e rmax são os índices do mapa de cores Se ambos forem maiores do que 1 então o mapa de cores utilizados para exibir a entidade fec é colormaprminrmax onde colormap é o mapa de cores da figura raiz Por padrão O valor da propriedade colorrange é 00 Neste caso todo o mapa de cores é utilizado linemode Se on o wireframe esqueleto encerrando os triângulos é desenhado Se off apenas os triângulos de dentro são desenhados foreground este índice de cor especifica a cor da malha Se a propriedade linemode for on o wireframe é desenhado utilizandose esta cor fecproperties 626 clipstate este campo contém o valor da propriedade clipstate para o fec o valor de clipstate pode ser off significa que o fec não é recortado clipgrf significa que o fec é recortado fora da caixa dos eixos on significa que o fec é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquer do largura altura define as porções do retângulo a ser exibido contudo o valor da propriedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade Fec e recuperála Exemplos x1010 y1010m rand2121 Sgrayplotxym agetcurrentaxes fachildrenchildren1 fdata31sizefdata1 aparentcolormaphotcolormap64 Ver Também set get delete fec Sgrayplot graphicsentities Autor Djalel ABDEMOUCHE 627 Name fgrayplot esboço 2d de uma superfície definida por uma função utilizando cores fgrayplotxyfstrfrectnax fgrayplotxyfoptargs Parâmetros xy vetor linha de reais f função externa do tipo yfxy optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 pode ser um dos seguintes rect nax strf ou axesflag e frameflag ver plot2d strfrectnax ver plot2d Descrição fgrayplot realiza um esboço 2d de uma superfície dada por zfxy em um grid definido por x e y Cada retângulo no grid é preenchido com um nível de cinza ou de cor dependendo do valor médio de z nas quinas do retângulo Entre com o comando fgrayplot para visualizar uma demonstração Exemplos t1011 deffzmysurfacexyzx2y2 fgrayplotttmysurfacerect2222 Ver Também grayplot plot2d Sgrayplot Sfgrayplot Autor JPhC 628 Name figureproperties Descrição das propriedades da entidade gráfica Figure figura Descrição A figura é o topo da hierarquia de entidades gráficas Esta entidade contém um número de propriedades designadas a controlar muitos aspectos da exibição de objetos gráficos do Scilab Estas propriedades estão dividas em duas categorias Propriedades que contém informação sobre a própria figura e outras relacionadas a valores padrões para criação de galhos Figure properties children estes manipuladores representam o vetor dos galhos da figura Note que todos os galhos de figuras são do tipo Axes Também tenha em mente que ao se criar uma entidade figura utilizando o comando scf uma entidade Axes de eixos é simultaneamente criada figurestyle o valor deste campo determina o estilo da figura Desde o Scilab 50 o modo gráfico antigo foi desabilitado Esta propriedade é mantida por compatibilidade mas não pode ser alterada figureposition este campo contém a posição em pixel da janela de gráficos na tela É um vetor xy definindo a posição do canto superior esquerdo da janela A posição 00 é o canto superior esquerdo da tela A posição inicial de uma janela de gráficos é tomada a partir da entidade figura padrão ver gdf A única excessão é quando o valor figureposition da figura padrão é 11 Neste caso A posição inicial da janela de gráficos é ajustada automaticamente pelo sistema de janelamento figuresize esta propriedade controla o tamanho em pixel da janela de gráficos da tela O tamanho é o vetor widthheight axessize usado para especificar o tamanho da janela de gráficos virtual O tamanho é o vetor widthheight A janela de gráficos virtual deveria ser maior que a parte realmente visível na tela Esta propriedade não poderia ser alterada se a figura está aportada com outros elementos autoresize esta propriedade determina se a janela de gráficos é redimensionada Se o valor é on então a propriedade axessize é igualada a figuresize e os galhos eixos são ampliados de modo correspondente Se o valor é off axessize não pode ser redimensionado quando figuresize é modificado viewport posição da parte visível do gráfico na janela figurename este campo contém o nome da figura O nome é um string exibido no topo da janela de gráficos Pode conter um único substring d que será substituido por figureid Em nen hum outro caso o caractere é permitido dentro do nome figureid este campo contém o identificador da figura É um número inteiro que é ajustado na criação da figura e não pode ser mudado depois figureproperties 629 infomessage este string ajusta o texto que será exibido na barra de informações da janela colormap propriedade que define o mapa de cores utilizado pela figura O mapa de cores é uma matriz m por 3 m é o número de cores O número da cor i é dado pela tripla 3uple R G B corre spondentes respectivamente às intensidades de vermelho verde e azul entre 0 e 1 pixmap esta propriedade controla o status de pixmap de uma janela de gráficos Se o valor é off os gráficos são diretamente exibidos na tela Se é on os gráficos são feitos em um pixmap e são enviados à janela através do comando showpixmap pixeldrawingmode este campo define a operação bit a bit usada para desenhar o pixel na tela O modo padrão é copy que significa dizer que o pixel é desenhado como requerido De modo mais geral a operação bit a bit é realizada entre a cor do pixel fonte e a cor do pixel já presente na tela As operações são clear and andReverse copy andInverted noop xor or nor equiv invert orReverse copy Inverted orInverted nand set immediatedrawing esta propriedade controla a exibição da figura Pode ser on modo padrão ou off É utilizada par atrasar uma grande sucessão de comandos gráficos implicando vários esboços ou reesboços Note que ao se utilizar os comandos drawlater ou drawnow É utilizada par atrasar uma grande sucessão de comandos gráficos implicando vários esboços ou re esboços Note que ao se utilizar os comandos off ou on background esta propriedade controla a cor de plano de fundo da figura O valor é um índice de cor correspondente ao mapa de cores corrente eventhandler um string O nome da função do Scilab que deverá manipular os eventos Note que definir um string vazio desabilitará o manipulador de eventos Para mais informações sobre o ma nipulador de eventos veja a ajuda event handler functions eventhandlerenable habilita ou desabilita o manipulador de eventos Seu valor deve ser on ou off userdata este campo pode ser utilizado para se armazenar qualquer variável Scilab na estrutura de dados da entidade figura e recuperála tag este campo pode ser utilizado para armazenar um string geralmente utilizado para identificar o controle Ele permite fornecer um nome Principalmente utilizado em conjunção a find obj Valores padrões para galhos visible este campo determina se o conteúdo da figura deve ser redesenhado O valor pode ser on ou off rotationstyle este campo está relacionado ao botão 3D Rot Toma unary como valor padrão para rotacionar apenas o esboço 3d selecionado Em outros casos o valor pode ser multiple todos os esboços 3d são rotacionados figureproperties 630 Nota sobre valores padrões todas estas propriedades e campos listados herdam valores de valores padrões armazenados num modelo de figura Estes valores padrões podem ser vistos e salvos Para fazêlo use o comando getdefaultfigure ele retorna o manipulador gráfico de uma figura Note que nen huma janela de gráficos é criada por este comando As próximas figuras criadas herdarão valores deste modelo ver o exemplo 2 abaixo Exemplos lines0 desabilitando paginamento vertical Exemplo 1 fgetcurrentfigure obtendo o manipulador da figura corrente se nenhum existir cria uma figura e retorna o manipulador correspondente ffigureposition ffiguresize200200 fbackground2 fchildren podese ver que uma entidade Axes já existe deletef fgcf atalho de macro ltgt fgetcurrentfigure fpixmap on ajusta o status de pixmap para on plot2d nada acontece na tela showpixmap exibe o pixmap na tela Exemplo 2 configurações de defaultfigure dfgetdefaultfigure obtendo os valores padrões o atalho é gdf vamos mudar os padrões dfcolormaphotcolormap128 dfbackground 110 ajustando o plano de fundo para um tipo de amarelo note que estamos utilizando um índice de cor dentro do mapa de cores colormap redefinido previamente scf122 criando uma nova figura de número122 com o novo padrão plot2d scf214 tpi03pi plot3dttsintcost3545XYZ1524 Ver Também lines set get scf gcf gdf gca gda axesproperties showpixmap clearpixmap hotcolormap event handler functions Autor Djalel ABDEMOUCHE 631 Name fplot2d esboço 2d de uma curva definida por uma função fplot2dxrfstylestrflegrectnax fplot2dxrfoptargs Parâmetros xr vetor f função externa do tipo yfx ie uma função scilab ou rotina dinamicamente linkada ligada referida como um string stylestrflegrectnax ver plot2d optargs ver plot2d Descrição fplot2d esboça uma curva definida pela função externa f A curva é aproximada por uma interpolação linear seccional utilizando os pontos xrifxri Os valores de fx são obti dos por fevalxrf Entre com o comando fplot2d para visualizar uma demonstração Exemplos deffyfxysinxcosx x00110pi10 fplot2dxf clf fplot2d110parab Ver Também plot2d feval paramfplot2d Autor JPhC 632 Name fplot3d esboço 3d de uma superfície definida por uma função fplot3dxryrfthetaalphalegflagebox fplot3dxryrfoptargs Parâmetros xr vetor linha de tamanho n1 yr vetor linha de tamanho n2 f external do tipo zfxy thetaalphalegflagebox ver plot3d optargs ver plot3d Descrição fplot3d esboça uma superfície definida pela função externa f no grid definido por xr e yr Entre com o comando fplot3d para ver uma demonstração Exemplos deffzfxyzx4y4 x3023 yx clf fplot3dxyfalpha5theta31 Ver Também plot3d Autor JPhC 633 Name fplot3d1 Esboço 3d em escala de cinza ou colorido de nível de uma superfície definida por uma função fplot3d1xryrfthetaalphalegflagebox fplot3d1xryrfoptargs Parâmetros xr vetor linha de tamanho n1 yr vetor linha de tamanho n2 f função externa external do tipo zfxy thetaalphalegflagebox ver plot3d1 optargs ver plot3d Descrição fplot3d1 esboça em 3d em escala de cinza ou colorido níveis de uma superfície definida pela função externa f no grid definido por xr e yr Entre com o comando fplot3d1 para visualizar uma demonstração Exemplos deffzfxyzx4y4 x3023 yx clf fplot3d1xyfalpha5theta31 Ver Também plot3d1 Autor JPhC 634 Name gca Retorna o manipulador da entidade Axes corrente a gca Parâmetros a manipulador o manipulador da entidade Axes corrente Descrição Esta rotina retorna o manipulador da entidade Axes da figura corrente Exmplos subplot211 agca obtendo os eixos correntes aboxoff tpi03piplot3dttsintcost8050XYZ524 subplot212 plot2d esboço simples agca obtendo os eixos correntes aboxoff axlocationmiddle aparentbackground4 deletegca deletando os eixos correntes xdel0 deletando uma janela de gráficos Ver Também gda gcf gce get graphicsentities Autor Djalel ABDEMOUCHE 635 Name gce Retorna o manipulador da entidade corrente e gce Parâmetros e manipulador da entidade corrente Descrição Esta rotina retorna o manipulador da última e ainda existente entidade criada Exemplos agca obtendo o manipulador dos novos eixos criados adatabounds111010 aaxesvisible on for i15 xfrect7i9i33 egce ebackgroundi end delete deletando a entidade corrente deletegce deletando a entidade corrente deletegcf deletando a figura corrente Ver Também gcf gca get graphicsentities Autor Djalel ABDEMOUCHE 636 Name gcf Retorna o manipulador da janela GUI ou de gráficos corrente h gcf Parâmetros h manipulador Descrição Esta função retorna o manipulador da janela gráfica corrente Exemplos fgcf criando uma figura ffiguresize 6104692 ffigurename Foo ffigure criando uma figura huicontrolfstylelistboxposition 10 10 150 160 criando um listbox seth string item 1item 2item3 preenchendo a lista seth value 1 3 selecionando os itens 1 e 3 na lista gcf scf0 tornando a janela de gráficos 0 a figura corrente gcf obtendo o manipulador gráfico da figura corrente figuref tornando a janela GUI f a figura corrente gcf retorna o manipulador gráfico da figura corrente Ver Também gdf gca gce get scf set graphicsentities uicontrol Autor Serge Steer INRIA 637 Name gda Retorna o manipulador dos eixos padrões a gda a getdefaultaxes Parâmetros a o manipulador dos eixos padrões Descrição Os eixos padrões são uma entidade gráfica entidade Axes que nunca é desenhada Ela usada como referência para os valores de propriedades padrões dos eixos Estes valores de propriedades padrões são usados para inicializar novos eixos dentro de figuras A função gda retorna o manipulador dos eixos padrões O usuário pode utilizar este manipulador para ajustar ou obter os valores padrões de propriedades dos eixos Note que uma entidade gráfica padrão equivalente também existe para entidades Figure ver gdf Exemplos agda obtendo o manipulador dos eixos modelos ajustando suas propriedades aboxoff aforeground2 alabelsfontsize3 alabelsfontcolor5 asubtics5 5 3 axlocationtop os eixos modelos são agora usados subplot211 criando uma nova entidade Axes plot2d veja outros modelos de propriedades abackgroundcolorgray agrid5 5 5 subplot212 t0015pi plot2dsintcost setadefaultvalues1 retornando para os valores padrões do modelo ver a função sda clf plot2dsintcost Ver Também gdf sda sdf clf gca get graphicsentities Autor 639 Name gdf Retorna o manipulador da figura corrente f gdf f getdefaultfigure Parâmetros f manipulador da figura corrente Descrição A figura padrão é uma entidade gráfica entidade Figure que nunca é desenhada É usada como referência para os valores padrões das propriedades da figura Estes valores padrões são utilizados para iniciar novas figuras A função gdf retorna o manipulador da figura corrente O usuário pode utilizar este manipulador para ajustar ou obter os valores padrões das propriedades da figura Note que uma entidade gráfica padrão equivalente também existe para entidades Axes de eixos ver gda Exemplos fgdf obtendo o manipulador da figura modelo ajustando suas propriedades fbackground7 ffigurenameFunction gdf ffigureposition1 100 fautoresizeoff ffiguresize300 461 faxessize600 400 plot2d criando uma figura scf1 plot3d criando uma segunda figura setfdefaultvalues1 retornando para os valores padrões do modelo da figura ver a função sdf scf2 plot2d Ver Também gda sdf sda gcf get scf set graphicsentities Autor Djalel ABDEMOUCHE 640 Name ged Editor Gráfico do Scilab gedaction fignum Parâmetros action Real ação a ser executada na janela gráfica dada por fignum 1 Ajusta a janela fignum como sendo a corrente 2 Redesenha a janela fignum 3 Limpa a janela fignum 4 Pede que o usuário selecione uma entidade gráfica para efetuar cópia 5 Cola a última entidade gráfica copiada pela ação 4 6 Pede ao usuário para que selecione uma entidade gráfica e então a mova 7 Pede ao usuário que selecione uma entidade gráfica para efetuar deleção 8 Inicia uma GUI para se editar propriedades da janela 9 Inicia uma GUI para se editar propriedade dos eixos correntes 10 Inicia um selecionador para selecionar um objeto e editálo através da GUI do Editor Gráfico 11 Para o selecionador de entidades fignum Real número da janela de gráficos a figura a ser editada Descrição ged inicia um Editor Gráfico do Scilab sobre a figura de número fignum e executa a ação fornecida por action Autor VC 641 Name genfac3d computa facetas de uma superfície 3d xxyyzzgenfac3dxyzmask Parâmetros xxyyzz matrizes de tamanho 4n1xm1 xxi yyi e zzi são respectivamente as coordenadas nos eixos x y e z dos 4 pontos da iésima faceta de quatro lados x vetor de coordenadas no eixo y de tamanho n y vetor de coordenadas no eixo y de tamanho n z matriz de tamanho mn zij é o valor da superfície no ponto xiyj mask matriz de valores booleanos opcional de mesmo tamanho que z utilizada para selecionar entradas de z a serem representadas por facetas Descrição genfac3d computa uma faceta de quatro lados de uma superfície 3d zfxy definida por x y e z Exemplos t0032pi zsintcost xxyyzzgenfac3dttz plot3dxxyyzz Ver Também eval3dp plot3d 642 Name geom3d projeção 3d para 2d após um esboço 3d xygeom3dx1y1z1 Parâmetros x1y1z1 vetores reais de mesmo tamanho pontos em 3d xy vetores reais de mesmos tamanhos que x1 y1 e z1 Descrição Após o uso de uma função de esboço 3d como plot3d plot3d1 ou param3d geom3d gives the mapping between a point in 3D space x1iy1iz1i e o ponto correspondente xiyi no plano 2d projetado Então todas as primitivas de gráficos 2d que funcionam em xy podem ser usadas para superposição no esboço 3d Exemplos deffzsurfacexyzsinxcosy tpi101010 esboço 3d da superfície fplot3dttsurface3545XYZ agora ttsintcost é uma curva na superfície que pode ser desenhada utilizandose geom3d e xpoly xygeom3dpi20surfacepi20 Autor JPhC 643 Name get Recupera um valor de propriedade de uma entidade de gráficos ou um objeto Interface do Usuário hgetprop valgethprop valhprop Parâmetros h manipulador da entidade da qual se deseja recuperar uma propriedade h pode ser um vetor de manipuladores e neste caso get retorna os valores da propriedade definidos para todos os objetos identificados por h h também pode ser 0 para se retornar as propriedades do objeto raiz prop string com o nome da propriedade val objeto Scilab o valor da propriedade Descrição Esta rotina pode ser utilizada para se recuperar o valor de uma propriedade especificada de uma en tidade de gráficos ou objeto GUI Neste caso é equivalente a se usar o operador ponto em um manipulador Por exemplo gethbackground é equivalente a hbackground Nomes de propriedades são strings Para obter a lista de todas as propriedade existentes ver graphicsentities ou uicontrol para objetos de Interface do Usuário get também pode ser chamado com apenas uma propriedade como argumento Neste caso a pro priedade deve ser uma das seguintes currententity or hdl retorna o manipulador da última e ainda existente entidade criada getcurrententity e gethdl equivalem a gce currentfigure retorna o manipulador da figura Figure corrente getcurrentfigure equivale a gcf currentaxes retorna o manipulador da entidade de eixos Axes corrente getcurrentaxes equivale a gca defaultfigure retorna o manipulador da figura padrão getdefaultfigure equivale a gdf defaultaxes retorna o manipulador dos eixos padrões getdefaultaxesequivale a gda figuresid retorna um vetor contendo os ids de todas as figuras gráficas abertas getfiguresid equivale a winsid Exemplos get 644 para entidades gráficas clf objetos gráficos simples subplot121 x2012pi plot2dx2x2 subplot122 xrect2752 xrect3832 xfarc2555115064360 xfarc5555115064360 xstring029Exemplo ltltUM CARROgtgt hgetcurrententity obtendo o novo objeto criado hfontsize3 fgetcurrentfigure obtendo a figura corrente ffiguresize ffiguresize700 500 fchildren fchildren2type fchildren2children fchildren2childrenchildrenthickness4 agetcurrentaxes obtendo os eixos correntes achildrentype achildrenforeground obtendo a cor de primeiro plano de um conjunto de objetos gráficos achildrenforeground9 para objetos de Interface do Usuário huicontrolstring Button Abrindo uma janela com um botão pgethposition obtendo o aspecto geométrico do botão dispLargura do botão stringp3 imprimindo a largura do botão close fechando a figura Ver Também uicontrol rootproperties graphicsentities set Autor Djalel ABDEMOUCHE 645 Name getfigurehandle Retorna o manipulador de uma figura a partir de seu id f getfigurehandlefigureid Parâmetros figureid inteiro o id da figura a ser recuperada f o manipulador da figura correspondente Descrição getfigurehandle permite recuperar o manipulador de uma figura gráfica desde que se conheça o seu identificador Se uma figura com o id especificado existir ela é retornada Em caso contrário uma matriz vazia é retornada Exemplos criando algumas figuras scf0 scf5 scf12 obtendo o manipulador da figura com id 5 f5 getfigurehandle5 a figura corrente ainda é aquela com id 12 gcf obtendo uma figura inexistente f42 getfigurehandle42 Ver Também set get gcf scf graphicsentities Autor JeanBaptiste Silvy INRIA 646 Name getcolor abre um diálogo que exibe as cores no mapa de cores corrente cgetcolortitlecini cgetcolor Parâmetros title string o título do diálogo cini identificador da cor selecionada inicial O valor padrão é 1 c identificador da cor selecionada ou se o usuário tiver clicado no botão Cancel cancelar Descrição getcolor abre uma janela que exibe o palete do mapa de cores corrente O usuário pode clicar numa cor para exibir seu identificador e valores RGB getcolor retorna o identificador da cor selecionada ou se o usuário clicar no botão Cancel Ver Também color colormap getmark getfont 647 Name getfont Diálogo para selecionar fonte da letra Função obsoleta fIdfSizegetfont fIdfSizegetfontstr fntgetfont fntgetfontstr fntgetfontSstrfontfIdfSize Parâmetros str caractere por exemplo a fId inteiro o número da fonte selecionada fSize inteiro o tamanho da fonte selecionada fnt vetor fIdfSize Descrição Esta função que foi projetada para trabalhar com a função xset também está obsoleta Utilize o editor de propriedade ged ao invés getfont abre uma janela gráfica para seleção de uma fonte O usuário deve escolher uma fonte e um tamanho clicando no caractere exibido correspondente Apertar uma tecla faz com que o caractere exibido mude Exemplos fIdfSizegetfont xsetfontfIdfSize plot2d00rect0 0 10 10axesflag0 xstring55string Ver Também ged textproperties 648 Name getlinestyle Diálogo para seleção de estilo de linha Função obsoleta kgetlinestyle Parâmetros k inteiro o estilo de linha selecionado ou se o botão Cancel cancelar for clicado Descrição Esta função que foi projetada para trabalhar com a função xset também está obsoleta Utilize o editor de propriedades ged getlinestyle abre uma janela de gráfico para selecionar um estilo de linha Exemplos x00110 plot2dxsinx egce armazenando o Compound contendo o esboço echildren1linestyle getlinestyle Ver Também ged set segsproperties segsproperties 649 Name getmark Diálogo para selecionar marcas símbolos Função obsoleta markmrkSizegetmark Parâmetros mark inteiro o número da marca selecionada mrkSize inteiro o tamanho da marca selecionada Descrição Esta função que foi projetada para funcionar com a função xset também está obsoleta Utilize o editor de propriedades ged ao invés getmark abre uma janela de gráficos para selecionar uma marca símbolo Exemplos x00110 markmrkSizegetmark plot2dxsinxstylemark clf plot2dxsinx egce armazenando o Compound contendo o esboço markmrkSizegetmark echildren1markstyle mark Ver Também ged set segsproperties segsproperties 650 Name getsymbol diálogo para a seleção de um símbolo e seu tamanho Função obsoleta cgetsymboltitle Parâmetros title string título do diálogo c vetor de tamanho 2 nsz Descrição Esta função que foi projetada para trabalhar com a função xset também está obsoleta Utilize o editor de propriedades ged ao invés getsymbol abre uma caixa de diálogo de escolha com título title se fornecido onde o usuário pode selecionar um símbolo e seu tamanho getsymbol retorna o identificador do símbolo n e o identificador de seu tamanho sz Ver Também ged set segsproperties segsproperties 651 Name glue Cola um conjunto de entidades gráficas em um Compound composto glueH hagregglueH Parâmetros H um vetor de manipuladores hagreg manipulador da entidade Compound Descrição Dado um vetor de manipuladores esta função cola as entidades correspondentes em um único Com pound e retorna o manipulador desta nova entidade Exemplos Ver Também get set move unglue graphicsentities Autor Djalel ABDEMOUCHE 652 Name graduate graduação de eixos xixanpgraduate xmi xman1n2 xixanpgraduate xmi xma Parâmetros xmixma escalares reais n1 n2 inteiros com valores padrões 310 xi xa escalares reais np inteiro Descrição graduate procura pelo intervalo mínimo xixa e um número de tiques np tais que xi xmi xma xa xa xi np k10nk em 1 3 5 para um inteiro n n1 np n2 Exemplos y003314578 xbascplot2d1enn0y ymnymxnpgraduateminiymaxiy rect1ymnprodsizeyymx xbascplot2d1enn0y1011 rect10310np Ver Também xsetech plot2d Autor S Steer 1992 653 Name graphicsentities Descrição das estruturas de dados de entidades gráficas Descrição No Scilab uma janela de gráficos e os desenhos contidos nela são representados por entidades hierárquicas O topo do nível hierárquico é a Figure figura cada Figure define pelo menos um galho do tipo Axes eixos Cada entidade Axes contém um conjunto de folhas que são objetos gráficos básicos como Polylines Rectangles Arcs Segs poligonais retângulos arcos e segmen tos Também pode ser do tipo Compound composto que são conjuntos recursivos de entidades O interesse principal no novo modo de gráficos é facilitar a mudança de propriedades O novo modo de gráficos fornece um conjunto de rotinas gráficas de altonível ver set get utilizadas para controlar propriedades dos objetos como dados cores coordenadas e escalas cores e aparências sem que seja necessário entrar novamente os comandos de gráficos iniciais Entidades gráficas do Scilab estão associadas a variáveis do tipo handle manipuladores O ma nipulador é um identificador único que é associado a cada instância de uma entidade gráfica criada Utilizandose manipuladores é possível tanger propriedades de entidades através das rotinas set e get Os manipuladores também são utilizados para manipular objetos gráficos para movêlos para fazer cópias ou deletálos Figure a entidade figura é o topo da hierarquia de entidades gráficas Esta entidade define os parâmetros para a figura em si tanto quanto os valores padrões dos parâmetros para criação de galhos Os galhos das figuras são as entidades de eixos O manipulador da figura corrente a figura para onde os desenhos foram enviados pode ser obtido utilizandose getcurrentfigure e pode ser ajustado utilizandose setcurrentfigureh onde h pode ser tanto um manipulador da figura ou um iden ficador da figura figureid neste último caso se não existir um é automaticamente criado Veja figureproperties para detalhes Axes a entidade de eixos está no segundo nível da hierarquia de entidades gráficas Esta entidade define parâmetros para a mudança de coordenadas dos eixos e o desenho dos eixos tanto quanto os parâmetros padrões para criação de seus galhos Ver axesproperties for details para detalhes O manipulador dos eixos correntes pode ser obtido utilizandose getcurrentaxes Compound a entidade composta é simplesmente um vetor de galhos com uma única propriedade propriedade de visibilidade É usada para colar um conjunto de entidades Ver as documentações glue unglue e Compoundproperties Axis a entidade eixo é uma folha da hierarquia de entidades gráficas Esta entidade define os parâmetros de escala de um eixo e aparência Ver axisproperties para detalhes Polyline a entidade poligonal é uma folha na hierarquia de entidades gráficas define propriedades de de senho de poligonais e extensões poligonais 2d e 3d Ver polylineproperties para detalhes Arc a entidade arco é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para elipses e partes de elipses graphicsentities 654 Ver arcproperties para detalhes Rectangle a entidade retângulo é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para retângulos e retângulos preenchidos Ver rectangleproperties para detalhes Surface a entidade superfície é uma folha na hierarquia de entidades gráficas possui subtipos Fac3d ou Plot3d Esta entidade define parâmetros para esboço de superfícies 3d Ver surfaceproperties para detalhes Fec a entidade Fec é uma folha na hierarquia de entidades gráficas Representa esboços de elementos 2d finitos Ver fecproperties para detalhes Grayplot a entidade Grayplot é uma folha na hierarquia de entidades gráficas Representa esboços 2d de superfícies utilizando cores e imagens Ver grayplotproperties para detalhes Matplot a entidade Matplot é uma folha na hierarquia de entidades gráficas Representa esboços 2d uti lizando matrizes de inteiros Ver Matplotproperties para detalhes Segs a entidade de segmentos é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros um conjunto de flechas ou segmentos coloridos Ver segsproperties para detalhes Champ a entidade Champ é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para esboços 2d de campos vetoriais Ver champproperties para detalhes Text a entidade texto é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para impressão de strings Ver textproperties para detalhes Label a entidade rótulo é um galho da entidade gráfica Axes de eixos Esta entidade define parâmetros para os rótulos dos 3 eixos x y e z desenhados em uma janela de gráficos Ver labelproperties para detalhes Legend a legenda é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para legendas desenhadas impressas sob gráficos plot2dx Esta entidade requer futuros desenvolvi mentos Ver legendproperties para detalhes graphicsentities 655 Exemplos execute este exemplo linha por linha scf criando figura no modo de entidade obtendo o manipulador da entidade Figure e exibindo suas propriedades fgetcurrentfigure afchildren o manipulador da galho Axes x110 plot2dxx2 x15 eachildren Compound de duas poligonais p1echildren1 as propriedades das últimas poligonais desenhadas p1foreground5 mudando a cor da poligonal echildrenthickness5 mudando a espessura das poligonais deleteechildren2 moveechildren030 transladando a poligonal aaxesbounds0 0 05 05 subplot222 criando uma nova entidade Axes plot110 a1fchildren1 obtendo seu manipulador copyechildrena1 copiando a poligonal do primeiro esboço nos novos eixos a1databounds1 010 100 mudando os limites dos eixos setcurrentfigure10 criando uma nova figura com figureid10 plot3d os desenhos são enviados à nova figura com figureid10 setcurrentfiguref torna a figura anterior a corrente plot2dxx3 os desenhos são enviados à figura inicial Ver Também set get move draw delete objecteditor plot surf 656 Name graphicsfonts Descrição de fontes utilizadas em figuras gráficas Descrição Algumas entidades gráficas como Text Axes Label ou Legend exibem um ou mais strings em suas figuras gráficas A aparência dos strings exibidos pode ser modificada especificando diferentes fontes e tamanhos de caracteres Mudando a fonte Fontes utilizadas em figuras gráficas são selecionadas de um conjunto de fontes chamado fontes carregadas Em outras palavras as fontes carregadas são aquelas correntemente disponíveis em figuras gráficas Uma lista destas fontes pode ser obtida utilizandose a função xlfont sem ar gumento Por padrão o Scilab possui um conjunto de 11 fontes carregadas Este conjunto pode ser modificado e estendido utilizandose a função xlfont com um nome de fonte como argumento A fonte carregada pode ser de um arquivo ou mesmo uma uma do sistema Para conhecer a lista de fontes disponíveis no sistema utilize o comando xlfontAVAILABLEFONTS Para mais informações sobre como manipular fontes veja xlfont Aqui está a lista das 11 fontes padrões Número da fonte Família de Fontes Negrito Itálico 0 Monospaced Não Não 1 ScilabSymbols Não Não 2 Serif Não Não 3 Serif Não Sim 4 Serif Sim Não 5 Serif Sim Sim 6 SansSerif Não Não 7 SansSerif Não Sim 8 SansSerif Sim Não 9 SansSerif Sim Sim 10 SansSerif Sim Sim A fonte utilizada por uma entidade gráfica pode ser alterada através da propriedade fontstyle Esta é um inteiro positivo fazendo referência a uma das fontes Seu valor deve estar entre 0 fazendo referência à primeira fonte e o número de fontes carregadas menos um fazendo referência à última fonte A propriedade fractionalfont controla o antiserrilhamento da fonte Seu valor pode ser on ou off Se for ona fonte é suavizada em caso contrário ela não é Mudando o tamanho dos caracteres O tamanho do texto de uma entidade gráfica é modificado através da propriedade fontsize É um escalar especificando o tamanho dos caracteres exibidos O tamanho do caractere do Scilab é diferente do tamanho do caractere Java Aqui está uma equivalência entre as duas escalas Tamanho Scilab Tamanho Java 0 8 graphicsfonts 657 1 10 2 12 3 14 4 18 5 24 6 30 7 36 8 42 9 48 10 54 O tamanho do caractere pode não ser um inteiro Neste caso o resultado depende da propriedade fractionalfont da entidade Se a propriedade fractionalfont for on então o tamanho da fonte é interpolado entre os dois inteiros mais próximos Por exemplo um tamanho de fonte 25 exibe caracteres com tamanho Java 13 Se a propriedade fractionalfont for off então a fonte exibida é truncada para a sua parte inteira Por exemplo um tamanho de fonte 25 exibe caracteres Java de tamanho 12 Ver Também xlfont graphicsentities 658 Name graycolormap mapa de cores linear cinza cmapgraycolormapn Parâmetros n inteiro 1 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição graycolormap computa um mapa de cores com n cores cinzas variando linearmente do preto para o branco Exemplos f scf plot3d1 fcolormap graycolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap xset 659 Name grayplot esboço 2d de uma superfície utilizandose cores grayplotxyzstrfrectnax grayplotxyzoptargs Parâmetros xy vetores de reais de tamanhos n1 e n2 z matriz de reais de tamanho n1n2 zij é o valor da superfície no pontoxiyj optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes rect nax strf ou axesflag e frameflag ver plot2d e plot2doldversion strfrectnax ver plot2d Descrição grayplot faz um esboço 2d de uma superfície dada por z em um grid definido por x e y Cada retângulo no grid é preenchido com um nível de cinza ou de cor dependendo do valor médio de z nas quinas do retângulo Entre com o comando grayplot para visualizar uma demonstração Exemplos x1010 y1010m rand2121 grayplotxymrect20202020 tpi01pi msintcost clf grayplotttm Ver Também fgrayplot plot2d Sgrayplot Sfgrayplot Autor JPhC 660 Name grayplotproperties description of the grayplot entities properties Descrição A entidade Grayplot é uma folha na hierarquia de entidades gráficas Representa esboços 2d de superfícies utilizando cores e imagens ver grayplot Sgrayplot fgrayplot e Sfgray plot parent esta propriedade contém o manipulador para a raiz A raiz de uma entidade grayplot deve ser do tipo Axes children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores gray plot não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o grayplot é visível a propriedade é on Se off o grayplot não é exibido na tela data este campo define uma estrutura de dados do tipo tlist de tipo grayplotdata composto de uma linha e índices de colunas de cada elemento as coordenadas do grid x e y estão contidas respectivamente em datax e datay O campo complementar chamado dataz é o valor da superfície no ponto xiyj modo escalado ou o valor centrado da superfície definido entre dois pontos consecutivos xi e yj modo direto Se datamapping ver abaixo for ajustado para scaled todo o dado z é utilizado para realizar uma interpolação de cores enquanto que se o valor de datamapping for direct a última linha e coluna dos índices de dados z são ignoradas e a cor é determinada diretamente no mapa de cores através dos índices da submatriz dataz1111 datamapping por padrão o valor desta propriedade é scaled os índices das cores utilizadas para colorir são proporcionais ao valor das coordenadas z Em outro caso a propriedade possui valor di rect onde o esboço é um grayplot e os índices das cores de pintura são fornecidos pelos dados ver acima clipstate este campo contém o valor da propriedade clipstate para o grayplot o valor de clipstate pode ser off significa que o grayplot não é recortado clipgrf significa que o grayplot é recortado fora da caixa dos eixos on significa que o grayplot é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquer do largura altura define as porções do retângulo a ser exibido contudo o valor da propriedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade grayplot e recuperála grayplotproperties 661 Exemplos m5n5 Mround32randmn grayplot1m1nM agetcurrentaxes adatabounds 1177 hachildren hdatamappingdirect um esboço 2D de uma matriz utilizando cores xbasc agetcurrentaxes adatabounds 0044 b5ones1111 b2102104 b57572 Matplot1b1133 hachildren for i17 xclick um click ajusta os dados do Matplot hdatahdata4 end Ver Também set get delete grayplot Matplot Matplot1 graphicsentities Matplotproperties Autores Djalel ABDEMOUCHE FLeray 662 Name graypolarplot Esboço polar 2d de uma superfície utilizandose cores graypolarplotthetarhozstrfrect Parâmetros theta vetor de tamanho n1 a discretização do ângulo em radianos rho vetor de tamanho n2 a discretização do raio z matriz de reais de tamanho n1n2 zij é o valor da superfície no ponto thetairhoj strf string de comprimento 3 xy0 default o padrão é 030 x controla a exibição de legendas x0 sem legendas x1 com legendas Elas são fornecidas pelo argumento opcional leg y controla a computação da moldura y0 as molduras correntes definidas por uma chamada anterior a uma função de esboço de altonível são utilizadas Útil ao se superpor esboços múltiplos y1 o argumento opcional rect é utilizado para se especificar as fronteiras do esboço y2 as fronteiras do esboço são computadas utilizandose os valores mínimo e máximo de x e y y3 como y1 mas produz escala de isovisualização y4 como y2 mas produz escala de isovisualização y5 como y1 mas plot2d pode mudar as fronteiras do esboço e os tiques dos eixos para se obter boas graduações Quando o botão de zoom é ativado este modo é usado y6 como y2 mas plot2d pode mudar as fronteiras do esboço e os tiques dos eixos para se obter boas graduações Quando o botão de zoom é ativado este modo é usado graypolarplot 663 y7 como y5 mas a escala do novo esboço é misturada à escala corrente y8 como y6 mas a escala do novo esboço é misturada à escala corrente leg string É usado quando o primeiro caractere x do argumento strf é 1 leg possui a forma leg1leg2 onde leg1 leg2 etc são respectivamente as legendas das primeira segunda etc curvas O padrão é rect É usado quando o segundo caractere y do argumento strf é 1 3 ou 5 É um vetor linha de tamanho 4 e fornece as dimensões da moldura rectxminyminxmaxymax Descrição Toma um esboço 2d de uma superfície dada por z em um grid de coordenadas polares definido por rho e theta Cada região é preenchida com um nível de cinza ou de cor dependendo do valor médio de z nas quinas do grid Exemplos rho1014theta000212pi z30roundtheta1rho2 fgcf fcolormap hotcolormap128 clfgraypolarplotthetarhoz 664 Name havewindow Retorna o modo de janela do Scilab havewindow Descrição Retorna t se o Scilab possui a sua própria janela e f se não ie se o Scilab foi chamado com scilab nw nw significa sem janela 665 Name hist3d representação 3d de um histograma hist3dfthetaalphalegflagebox hist3dlistfxythetaalphalegflagebox Parâmetros mtx matriz de tamanho mn definindo o histograma mtxijFxiyj onde x e y asão tomados como 0m e 0n listmtxxy onde f é uma matriz de tamanho mn definindo o histograma mtxijFxiyj com vetores x e y de tamanho 1n1 e 1m1 thetaalphalegflagebox ver plot3d Descrição hist3d representa um histograma 2d como um esboço 3d Os valores são associados aos intervalos xi xi1 X yi yi1 Entre com o comando hist3d para visualizar uma demonstração Exemplos hist3d10rand1010 Z zeros1005 A absrand405 Z140 A scf hist3dZ Index findZ0 ZIndex nan scf hist3dZ A absrand105 Z91100 A scf hist3dZ Ver Também histplot plot3d Autores Steer S JPhilippe C 666 Name histplot esboça um histograma histplotn data optargs histplotx data optargs Parâmetros n inteiro positivo número de classes x vetor crescente definindo as classes x pode ter pelo menos dois componentes data vetor dados a serem analisados optargs representa uma seqüência de declarações key1value1key2value2 onde key1 key2 pode ser qualquer normalização ou parâmetro de plot2d opcional stylestrfleg rectnax logflagframeflag axesflag No caso de normalização o valor correspondente deve ser um escalar booleano valor padrão t Descrição Esta função esboça um histograma do vetor data utilizando classes x Quando o número n de classes é fornecido ao invés de x as classes são escolhidas de modo igualmente espaçado e x1 mindata x2 x1 dx xn1 maxdata com dx xn1x1n As classes são definidas por C1 x1 x2 e Ci xi xi1 para i 2 Notando Nmax o número total de data Nmax comprimento de data e Ni o número de componentes de data em Ci o valor do histograma para x em Ci é igual a NiNmax xi1xi quando normalization normalização for verdadeiro caso padrão senão é simplesmente igual a Ni Quando a normalização ocorre o histograma verifica xn1 hx dx 1 when x1mindata e maxdata xn1 x1 Qualquer plot2d parâmetro opcional pode ser fornecido por exemplo para esboçar um his tograma com a cor número 2 azul se o mapa de cores padrão for utilizado e para restringir o esboço ao retângulo 33x005 você pode utilizar histplotndata style2 rect30305 Entre com o comando histplot para visualizar uma demonstração Exemplos exemplo 1 variações ao redor de um histograma de uma amostra gaussiana aleatória drand110000normal a amostra gaussiana aleatória clfhistplot20d clfhistplot20dnormalizationf histplot 667 clfhistplot20dlegrand110000normalstyle5 clfhistplot20dlegrand110000normalstyle16 rect30305 exemplo 2 histograma de uma amsostra binomial B605 aleatória d grand10001bin 6 05 c linspace05658 xbasc subplot211 histplotc d style2 xtitlehistograma normalizado subplot212 histplotc d normalizationf style5 xtitlehistograma não normalizado exemplo 3 histograma de uma amostra exponencial aleatória lambda 2 X grand1000001exp 1lambda Xmax maxX xbasc histplot40 X style2 x linspace0maxXmax100 plot2dxlambdaexplambdaxstrf000style5 legendhistograma de amostra exponencial aleatória curva de densidade exata Ver Também hist3d plot2d dsearch 668 Name hotcolormap mapa de cores de vermelho para amarelo cmaphotcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição hotcolormap computa um mapa de cores com n cores quentes que variam do vermelho para o amarelo Exemplos f scf plot3d1 fcolormap hotcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 669 Name hsv2rgb Converte cores HSV para RGB rgb hsv2rgbhsv rgb hsv2rgbhsv rgb hsv2rgbhsv rgb hsv2rgbhsv Parâmetros h um vetor de tamanho n Os valores hue de matiz s um vetor de tamanho n Os valores saturation de saturação v um vetor de tamanho n Os valores value de valor hsv uma matriz n x 3 Cada linha contém uma tripla hue saturation value r um vetor coluna de tamanho n Os valores red de vermelho g um vetor coluna de tamanho n Os valores green de verde b um vetor coluna de tamanho n Os valores blue de azul rgb uma matriz n x 3 Cada linha contém uma tripla red green blue Descrição A função hsv2rgb converte mapas de cores entre os espaços de cores RGB e HSV Como a matiz varia de 0 a 10 as cores correspondentes podem variar partindo do vermelho entre amarelo verde ciano azul magenta e preto até vermelho novamente de modo que há na verdade valores de vermelho tanto em 0 quanto em 10 À medida em que a saturação varia de 0 a 10 as cores correspondentes matizes variam de insaturadas gradações de cinza a completamente saturadas nenhum componente branco à medida em que o valor ou brilho varia de 0 a 10 as cores correspondentes vão se tornando mais brilhantes Exemplos t0032pi zsintcost plot3d1ttz fgcffpixmapon for h0011 hsvhones321 linspace0132 07ones321 fcolormaphsv2rgbhsv showpixmap xpause10000 end for v0011 hsv2rgb 670 hsvones321 linspace0132 vones321 fcolormaphsv2rgbhsv showpixmap xpause10000 end Autor Serge Steer INRIA 671 Name hsvcolormap Mapa de cores de matizsaturaçãovalor huesaturationvalue cmap hsvcolormapn Parâmetros n inteiro 1 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição hsvcolormap computa um mapa de cores com n cores Este mapa de cores varia o componente de matiz do modelo de cor hsv huesaturationvalue matizsaturaçãovalor As cores começam do vermelho passando por amarelo verde azul celeste azul magenta e retornam para o vermelho O mapa é particularmente útil para exibir funções periódicas Exemplos t0012pi zsintcost fgcffcolormaphsvcolormap64 plot3d1ttz3545XYZ222 Autor Serge Steer INRIA Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 672 Name ishandlevalid Verifica se um conjunto de manipuladores gráficos ainda é válido isValid ishandlevalidh Parâmetros h matriz de manipuladores gráficos isValid matriz de booleanos com o mesmo tamanho que h Descriçãp ishandlevalid testa se um conjunto de manipuladores ainda é válido Um manipulador válido é um que ainda não foi deletado O resultado isValid é uma matriz de booleanos tal que isValidij é verdadeiro se hij é válido e falso em caso contrário Exemplos verificando se os objetos correntes são válidos ishandlevalidgcf gca gce criando 11 poligonais plot010 010 010 010 0055 0220 verificando a validade das poligonais axes gca polylines axeschildren1children ishandlevalidpolylines deletando algumas poligonais deletepolylines37 imprimindo a validade ishandlevalidpolylines Ver Também delete graphicsentities Autor JeanBaptiste Silvy INRIA 673 Name isoview ajusta escalas para esboço isométrico não muda o tamanho da janela isoviewxminxmaxyminymax Parâmetros xminxmaxyminymax quatro valores reais Descrição Esta função está obsoleta use a opção de plot2d frameflag4 que permite redimensionamento da janela ao invés isoview é usado para obter escalas isométricas nos eixos x e y O tamanho da janela de gráficos não é alterado O retângulo xmin xmax ymin ymax será contido no quadro computado da janela de gráficos isoview ajusta as escalas gráficas correntes e pode ser usado em conjunção com rotinas que requerem escalas gráficas correntes por exemplo strfx0z em plot2d Exemplos t0012pi plot2dsintcost xbasc isoview1111 plot2dsintcost1001 xsetdefault plot2dsintcostframeflag4 Ver Também square xsetech Autor Steer S 674 Name jetcolormap Mapa de cores de gradação do azul para o vermelho cmapjetcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com três colunas RGB Descrição jetcolormap computa o mapa de cores com n cores variando do azul passando por azul claro verde amarelo laranja e então vermelho Exemplos f scf plot3d1 fcolormap jetcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 675 Name labelproperties Descrição de propriedades da entidade Label rótulo Descrição A entidade Label é um galho da entidade Axes de eixos Quando uma entidade Axes é construída os manipuladores das entidades Title e Label são criados juntos e são parte das propriedade da entidade Axes Logo as propriedades destes subobjetos são editáveis via o manipulador da entidade Axes ver gca e gda Esta entidade define os parâmetros para impressão de rótulos parent esta propriedade contém o manipulador para a raiz A raiz de uma entidade Label deve ser do tipo Axes Note que por ora a entidade Label é exclusivamente utilizada na construção de title xlabel ylabel e zlabel visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o rótulo é visível o valor da propriedade é on Se off o rótulo não é impresso na tela text a matriz contendo os strings do objeto As linhas da matriz são exibidas horizontalmente e as colunas verticalmente fontforeground este campo contém o índice de cor utilizado para exibir o rótulo text Seu valor deve ser um índice de cor relativo ao mapa de cores corrente foreground este campo contém a cor utilizada para exibir o rótulo e a linha ao redor da caixa se houver Deve ser um índice de cor relativo ao mapa de cores corrente background este campo contém a cor a ser usada para preencher a caixa se houver Deve ser um índice de cor relativo ao mapa de cores corrente fillmode este campo toma valores on ou off Se on uma caixa é desenhada ao redor do texto com uma linha em sua borda e um plano de fundo fontstyle especifica a fonte a ser utilizada para exibir o rótulo É um inteiro positivo fazendo referência uma das fontes carregadas Seu valor deve estar entre 0 fazendo referência à primeira fonte e o número de fontes carregadas menos um fazendo referência à última fonte Para mais informações veja graphicsfonts fontsize é um escalar especificando o tamanho dos caracteres exibidos Se a propriedade fractionalfont for off apenas a parte inteira é utilizada Para mais informações veja graphicsfonts fractionalfont esta propriedade especifica se o texto será utilizado utilizandose tamanhos de fonte fracionários Seu valor deve ser on ou off Se on o valor em ponto flutuante de fontsize é utilizado para a exibição e evitase o serrilhamento da fonte Se off apenas a parte inteira é utilizada e a fonte não é suavizada labelproperties 676 fontangle um escalar que permite girar o rótulo A fonte é girada em sentido horário em um ângulo dado em graus Note que mudar fontangle desabilitará automaticamente a propriedade autorotation autorotation se on o Scilab computa automaticamente o melhor ângulo de rotação para a exibição do rótulo Se off o rótulo pode ser girado manualmente através da propriedade fontangle position este vetor 2d permite posicionar o rótulo na tela A posição é armazenada em unidades de dados dos eixos Note que mudar fontangle desabilitará automaticamente a propriedade autoposition autoposition se on o Scilab computa automticamente a melhor posição para a exibição do rótulo na janela de gráficos Se off o rótulo pode ser posicionado manualmente através da propriedade po sition Exemplos agetcurrentaxes atitle typeatitle plot3d axlabel aylabel azlabel xtitleMeu títulomeu rótulo de eixo x VolumeMês tatitle tforeground9 tfontsize5 tfontstyle5 ttextSCILAB xlabelaxlabel xlabeltext Peso xlabelfontstyle 5 aylabelforeground 12 Ver Também set get delete xtitle graphicsentities axesproperties textproperties Autor Djalel ABDEMOUCHE 677 Name legend Imprime uma legenda para o gráfico hllegendh string1string2 pos boxed hllegendh strings pos boxed Parâmetros h manipulador gráfico de uma entidade de eixos ou vetor de manipuladores de entidades poligonais O valor padrão é o manipulador dos eixos correntes string1string2 strings stringsi é a legenda da iésima curva strings vetor de strings de dimensão n stringsi é a legenda da iésima curva pos opcional especifica onde imprimir as legendas este parâmetro pode ser um flag inteiro ou de modo equivalente um string ou um vetor xy que fornece as coordenadas da quina superior esquerda da caixa de legenda No primeiro caso os valores possíveis são 1 as legendas são impressas no canto superior direito 2 as legendas são impressas no canto superior esquerdo 3 as legendas são impressas no canto inferior esquerdo 4 as legendas são impressas no canto inferior direito 5 localização interativa com o mouse 1 as legendas são impressas à direita do canto superior direito 2 as legendas são impressas à esquerda do canto superior esquerdo 3 as legendas são impressas à esquerda do canto inferior esquerdo 4 as legendas são impressas à direita do canto inferior direito 5 as legendas são impressas acima do canto superior esquerdo 6 as legendas são impressas abaixo do canto inferior esquerdo boxed um booleano valor padrão t que ajusta se a caixa será desenhada ou não legend 678 hl um manipulador pontos no Compound contendo todas as legendas Descrição Põe uma legenda no esboço corrente utilizando os strings especificados como rótulos legend pre anexa rótulos por uma rechamada à linha correspondente ou remendo A rechamada é de tipo e propriedades são recobradas dos dados manipuladores Quando chamada sem o argumento manipulador ou com manipulador de uma entidade Axes a função procura vetores de manipuladores de entidades poligonais construídos primeiro que são galhos dos eixos dados Na localização interativa opt 5 movese a caixa de legenda com o mouse e apertase o botão es querdo para liberála Exemplos tlinspace0pi20 agcaadataboundst1 18t 18 plot2dtcostcos2tcos3t52 3 egce e1echildren1e1thickness2e1polylinestyle4e1arrowsizefactor 12 echildren2linestyle4 e3echildren3e3linemodeone3markbackground5 hllegendcostcos2tcos3t Ver Também plot2d xstring captions polylineproperties 679 Name legendproperties Descrição das propriedades da entidade Legend legenda Descrição A entidade Legend é uma folha na hierarquia de entidade gráficas Esta entidade define parâmetros para legendas impressas abaixo de gráficos plot2dx ou criadas pela função captions Para cada linha esboçada a legenda exibe uma amostra do tipo da linha de sua marca e de sua cor parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Legends deve ser do tipo Compound Este Compound contém também o restante das entidade gráficas children esta propriedade contém um vetor com os galhos do manipulador contudo manipuladores leg end não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Se on a legenda é impressa se off a legenda não é exibida na tela text este campo é um vetor de strings que contém as legendas para cada objeto anotado fontsize um escalar especificando o tamanho da fonte Se a propriedade fractionalfont for off apenas a parte inteira é utilizada Para mais informações veja graphicsfonts fontstyle especifica a fonte utilizada para exibir os rótulos da legenda É um inteiro positivo fazendo referência a uma das fontes carregadas Seu valor deve estar entre 0 fazendo referência à primeira fonte e o número de fontes caregadas menos um fazendo referência à última fonte Para mais informações veja graphicsfonts fontcolor um índice de cor esta propriedade determina a cor do texto fractionalfont esta propriedade especifica se os textos são exibidos utilizandose tamanhos de fonte fracionários Seu valor deve ser on ou off Se on o valor em ponto flutuante de fontsize é utilizado para a exibição e evitase o serrilhamento da fonte Se off apenas a parte inteira é utilizada e a fonte não é suavizada links um array linha de manipuladores Eles se referem às poligonais associadas legendlocation um string especifica a localização da legenda inupperright as legendas são exibidas no canto superior direito da caixa de eixos inupperleft as legendas são exibidas no canto superior esquerdo da caixa de eixos inlowerright as legendas são exibidas no canto inferior direito da caixa de eixos inlowerleft as legendas são exibidas no canto inferior esquerdo da caixa de eixos outupperright as legendas são exibidas à direita do canto superior direito da caixa de eixos legendproperties 680 outupperleft as legendas são exibidas à esquerda do canto superior esquerdo da caixa de eixos outlowerright as legendas são exibidas à direita do canto inferior direito da caixa de eixos outlowerleft as legendas são exibidas à esquerda do canto inferior esquerdo da caixa de eixos uppercaption as legendas são exibidas acima do canto superior esquerdo da caixa de eixos lowercaption as legendas são exibidas abaixo do canto inferior esquerdo da caixa de eixos Esta opção corresponde ao argumento leg de plot2d bycoordinates o canto superior esquerdo da caixa de legendas é fornecido pelo cam po position da estrutura de dados associada As posições x e y são fornecidas como frações dos axesbounds position as coordenadas do canto superior esquerdo da legenda As posições x e y são dadas como frações dos tamanhos axesbounds Este campo pode ser ajustado se legendlocationbycoordinates ou obtido de outros ajustes de legendlocation linemode este campo especifica se um retângulo é desenhado ao redor da legenda ou não Deve ser on ou off Se on o retângulo é desenhado utilizandose as seguintes propriedades thickness este campo fornece a espessura da linha utilizada para desenhar o retângulo foreground este campo contém o índice de cor da linha utilizada para desenhar o contorno do retângulo fillmode este campo especifica se o plano de fundo da legenda será pintado ou não Deve ser on ou off Se on o plano de fundo é pintado utilizandose a cor definida no campo back ground background este campo contém o índice de cor da linha utilizada para pintar a área do retângulo clipstate este campo contém o valor da propriedade clipstate para todos os objetos O valor de clipstate pode ser off significa que todos os objetos criados posteriormente não são recortados valor padrão clipgrf significa que todos os objetos criados posteriormente são recortados fora da caixa dos eixos on significa que todos os objetos criados posteriormente são recortados fora do retângulo dado pela propriedade clipbox clipbox este campo contém o valor padrão da propriedade clipbox para todos os objetos O seu valor é uma matriz vazia se clipstate é off Em outros casos o recorte é dado por xywh ponto superior esquerdo largura altura legendproperties 681 userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados do texto e recuperála Exemplos inicialização de x x0012pi plot2dxsinx sin2x sin3x123legL1L2L3 agetcurrentaxes lachildren2 llinks ltextsinxsin2xsin3x lvisibleoff invisível lfontsize 2 lfontstyle 5 lvisibleon Ver Também plot2d graphicsentities Autor Djalel ABDEMOUCHE 682 Name legends Imprime uma legenda para o gráfico legendsstringsstyleoptargs Parâmetros strings vetor de strings de dimensão n stringsi é a legenda da iésima curva style vetor linha de inteiros de dimensão n os estilos de esboço terceiro parâmetro de plot2d ou uma matriz 2 x n style1k contém o estilo de esboço para a késima curva e style2k contém o estilo de linha se style1k0 ou cor da marca se style1k0 optargs representa uma seqüência de declarações key1value1key2value2 onde key1 key2 podem ser um dos seguintes opt opcional especifica onde imprimir as legendas este parâmetro pode ser um flag inteiro ou de modo equivalente um string ou um vetor xy que fornece as coordenadas da quina superior esquerda da caixa de legenda No primeiro caso os valores possíveis são 1 ou ur as legendas são impressas no canto superior direito 2 ou ul as legendas são impressas no canto superior esquerdo 3 ou ll as legendas são impressas no canto inferior esquerdo 4 ou lr as legendas são impressas no canto inferior direito 5 ou localização interativa com o mouse padrão 6 ou below as legendas são impressas abaixo do gráfico que é redimensionado de acordo withbox um booleano valor padrão t que ajusta se a caixa será desenhada ou não fontsize um inteiro valor padrão 1 que ajusta o tamanho da fonte para os nomes na legenda Descrição Põe uma legenda no esboço corrente utilizando strings especificados como rótulos Na localização interativa opt5 ou opt movese a caixa de legenda com o mouse e apertase o botão esquerdo para liberála Esta função permite uma localização mais flexível de legendas que o argumento de plot2d leg Exemplos legends 683 Exemplo 1 t0012pi plot2dtcostcos2tcos3t12 3 legendscostcos2tcos3t12 3optlr scf xsetline style2plot2dtcoststyle5 xsetline style4plot2dtsintstyle3 legendssintcost5234 withboxf opt Exemplo 2 scf subplot221 t0012pi plot2dtcostcos2tcos3t12 3 legendscostcos2tcos3t12 3 opt3 subplot222 xsetline style2plot2dtcoststyle5 xsetline style4plot2dtsintstyle3 legendssintcost5234 withboxf opt6 subplot223 xsetline style2plot2dtcoststyle5 xsetline style4plot2dtsintstyle3 legendssintcost5234 withboxf opt1 fontsize2 subplot224 t0012pi plot2dtcostcos2tcos3t12 3 legendscostcos2tcos3t12 3 opt2 fontsize1 Ver Também plot2d xstring xtitle legend 684 Name locate seleção pelo mouse de um conjunto de pontos xlocatenflag Parâmetros x matriz de tamanho 2n1 n1n se o parâmetro n for dado nflag valores inteiros Descrição locate é usado para obter as coordenadas de um ou mais pontos selecionados com o mouse em uma janela de gráficos As coordenadas são fornecidas usandose a escala de gráficos corrente Se n0 n pontos são selecionados e suas coordenadas são retornadas na matriz x Se n0 os pontos são selecionados até que o usuário clique com o botão esquerdo do mouse que significa parar O último ponto clicado com o botão esquerdo não é retornado xlocate é o mesmo que xlocate1 Se flag1 uma cruz é desenhada nos pontos onde o mouse foi clicado Ver Também xclick xgetmouse Autores SS JPhC 685 Name mesh Esboço 3d de uma malha meshZ meshXYZ meshGlobalProperty meshcolorGlobalProperty meshaxeshandle Parâmetros Z matriz de reais definindo a altura da superfície Não pode ser omitida O dado Z é uma matriz mxn XY duas matrizes de reais sempre ajustadas juntas esses dados definem um novo grid padrão Estes novos componentes X e Y do grid devem coincidir com as dimensões de Z ver descrição abaixo color uma matriz de reais opcional definindo a cor para cada ponto XjYi do grid ver descrição abaixo GlobalProperty este argumento opcional representa uma seqüência de pares de declarações PropertyNamePropertyValue que definem propriedades globais dos objetos apli cadas a todas as curvas criadas neste esboço Para uma completa visualização das propriedades disponíveis veja GlobalProperty axeshandle este argumento opcional força o esboço a aparecer dentro dos eixos selecionados por axeshandle ao invés dos eixos correntes ver gca Descrição mesh desenha uma superfície parametrizada utilizando um grid retangular definido pelas coordenadas X e Y se XY não são especificados este grid é determinado utilizandose as dimensões da matriz Z em cada ponto deste grid uma coordenada Z é dada utilizandose a matriz Z mesh é baseado no comando surf com a opção padrão colormode índice de branco dentro do mapa de cores corrente e colorflag 0 Especificação de dados de entrada Neste parágrafo para sermos mais claros não mencionaremos os argumentos opcionais Global Property já que eles não interferem na entrada de dados exceto pelas propriedades Xdata Ydata e Zdata ver GlobalProperty Assumese que todos estes argumentos opcionais pode riam estar presentes também Se Z é a única matriz especificada Z esboça a matriz Z versus o grid definido por 1sizeZ2 ao longo do eixo x e 1sizeZ1 ao longo do eixo y Observação Para habilitarse o modo de transparência você deve ajustar a opção colormode para 0 Exemplo mesh 686 XYmeshgrid111111 ZX2Y2 xtitlezx2y 2 meshXYZ Ver Também surf meshgrid plot2d LineSpec GlobalProperty Autor FBelahcene 687 Name milkdrop Função 3d gota de leite zmilkdropxy Parâmetros xy dois vetores linhas de tamanhos n1 e n2 z matriz de tamanho n1n2 Descrição milkdrop é uma função que representa uma gota de leite caindo no leite Pode ser usada para testar funções eval3d e plot3d Exemplos x2012 yx zeval3dmilkdropxy plot3dxyz Ver Também eval3d plot3d Autor Steer S 688 Name move Move uma entidade gráfica e seus galhos movehxy movehxyalone Parâmetros h manipulador da entidade a ser movida xy um array dxdy que fornece o vetor translação a ser aplicado alone palavrachave string opcional Descrição Esta rotina pode ser usada para aplicar uma translação em uma entidade de gráficos Se a entidade tiver galhos unidades de dependência hierárquica elas também serão transladadas Dada a palavra chave alone apenas a unidade especificada precisa ser redesenhada Deve ser especialmente usada com a propriedade pixeldrawingmode da entidade de figura ver como desenhar objetos no modo de desenho xor Exemplos Ver Também get set draw figureproperties graphicsentities Autor Djalel ABDEMOUCHE 689 Name name2rgb Retorna valores RGB correspondentes ao nome da cor rgbname2rgbname Parâmetros name nome da cor rgb vetor de valores RGB inteiros de uma cor Descrição name2rgb retorna os valores RGB vermelho verde azul inteiros de uma cor dado o seu nome O resultado é um vetor rgb onde r g e b são inteiros entre 0 e 255 correspondentes aos compo nentes de cor vermelho verde e azul Como de uso 0 significa nenhuma intensidade e 255 significa intensidade total da cor Se uma cor não for encontrada é retornado A lista de todas as cores conhecidas é dada por colorlist Exemplos rgbname2rgbgold rgb2namergb Ver Também color colorlist rgb2name 690 Name newaxes Cria uma nova entidade Axes de eixos anewaxes Parâmetros a o manipulador para a nova entidade Axes criada Descrição newaxes é usado para criar uma nova entidade Axes ver graphicsentities na figura corrente As propriedades dessa entidade são herdadas da entidade defaultaxes ver gda Exemplos clf a1newaxes a1axesbounds001005 t00120 plottacoshtr a2newaxes a2axesbounds0051005 x0014 plotxsinhx legendsinh scaa1 tornando os primeiros eixos os eixos correntes plottasinhtg legendacoshasinh Ver Também subplot gda sca Autor S Steer INRIA 691 Name nf3d Facetas retangulares para parâmetros da função plot3d xxyyzznf3dxyz Parâmetros xyxxxyyzz 6 matrizes de reais Descrição Função utilitária Usada para transformar facetas retangulares codificadas em três matrizes xy e z para o código Scilab para facetas aceito por plot3d Exemplos Uma esfera u linspacepi2pi240 v linspace02pi20 x cosucosv y cosusinv z sinuonesv plot3d2xyz é equivalente a xxyyzznf3dxyz plot3dxxyyzz Ver Também plot3d plot3d2 692 Name objecteditor Descrição das capacidades do editor de objetos gráficos graphic Descrição das capacidades do editor de objetos gráficos menus Descrição das capacidades do editor de objetos gráficos Descrição Os gráficos do Scilab permitem que o usuário interaja com os gráficos antes e depois de têlos desen hado Cada janela gráfica e seus conteúdos são representados por entidades hierárquicas O topo da hierarquia é a figura entidade Figure Cada figura define pelo menos uma entidade galho do tipo Axes eixos Cada entidade Axes contém entidades folhas que são objetos gráficos básicos como Rectangles Arcs Segs retângulos arcos segmentos Também contém o tipo Compound que são conjuntos recursivos de entidades O principal interesse do novo modo gráfico é tornar mudanças de propriedades mais fáceis Este novo modo de gráficos fornece um conjunto de rotinas gráficas de altonível ver set get utilizadas para controlar propriedades dos objetos tais como dados coordenadas e escalas cores e aparências sem que seja necessário entrar com os comandos gráficos iniciais novamente Entidades gráficas são associadas a variáveis Scilab do tipo handle a qual chamaremos manipulador Um manipulador é um identificador único que é associado a cada instância de uma entidade gráfica criada Utilizando manipuladores é possível alcançar propriedades de entidade através das rotinas set e get Os manipuladores também são utilizados para manipular objetos gráficos para movê los para fazer copiálos ou deletálos Para completar e utilizar a capacidade de um manipulador gráfico ao seu máximo um editor de objetos gráficos também foi criado É um conjunto de interfaces TclTk disponíveis para cada tipo de objeto gráfico ver graphicsentities para mais detalhes que pode ser habilitado para cada janela de gráficos Para fazêlo funcionar selecione o menu Edit na janela de gráficos Sete operações de edição gráfica estão disponíveis Select figure as current permite que uma figura seja a corrente Redraw figure redesenha o conteúdo da janela de gráficos Erase figure apaga o conteúdo da janela de gráficos Sua ação corresponde a um comando clf Os últimos oito itens são especialmente dedicados ao editor gráfico Copy object utilizando o mouse permite que o usuário selecione um objeto 2d como uma curva um retângulo e coloque na área de transferência Logo por uma nova chamada a Paste object colar objeto o objeto é copiado nos eixos correntes selecionados Paste object permite que o usuário cole um objeto anterior posto na àrea de transferência nos eixos correntes selecionados objecteditor 693 Move object utilizando o mouse permite que o usuário mova um objeto 2d como uma curva um retângulo dentro dos eixos correntes selecionados Delete object utilizando o mouse permite que o usuário selecione um objeto 2dcomo uma curva um retângulo dentro dos eixos correntes selecionados e deleteo instantaneamente Figure Properties lança a interface TclTk para o objeto Figure aplicado ao manipulador da figura da janela de gráficos Current Axes Properties lança a interface TclTk para o objeto Axes aplicado ao manipulador dos eixos correntes da janela de gráficos Start Entity Picker inicia um manipulador de eventos na janela de gráficos para pegar os cliques do mouse sobre objetos gráficos e lança a interface TclTk correspondente O clique com botão esquerdo do mouse permite edição de objetos e com botão direito realiza um movimento do objeto selecionado Note que por ora este recurso só se aplica a objetos 2d Stop Entity Picker para a ação de Entity Picker terminando o manipulador de eventos na janela de gráficos Uma vez que a interface gráfica é habilitada utilizando as opções Figure Properties ou Cur rent Axes Properties duas áreas principais aparecem Um tree selector seletor de árvore posicionado à direita do editor gráfico um seletor de árvores hierárquicas especifica que objeto é correntemente editado Pode ser usado para alternar de um objeto gráfico para outro fornecido estando eles na mesma janela de gráficos objecteditor 694 Um notebook caderno a segunda área representa um caderno composto de diferentes páginas de propriedades como Style Data Clipping dependendo do objeto gráfico selecionado Utilizandose este edi tor podese editar mais facilmente todo o conjunto de propriedade gráficas de cada objeto gráfico como através dos comandos set e get Aqui está um exemplo de um caderno para a entidade Axes exibindo as suas propriedades objecteditor 695 Furthermore você poderá colocar legendasanotações em sua figura utilizando primitivas de amostra fornecidas no menu Insert na janela gráfica Utilizando o mouse e seguindo as instruções na sub janela de mensagem você poderá acrescentar Line Desenhe uma linha entre dois cliques do mouse A linha vive nos eixos onde o primeiro ponto foi selecionado objecteditor 696 Polyline Desenhe uma poligonal clicando no botão esquerdo para definir o caminho da linha e clique no botão direito para completar o desenho A poligonal vive nos eixos onde o primeiro ponto foi selecionado Arrow Desenhe uma seta entre dois cliques do mouse A seta vive nos eixos onde o primeiro ponto foi selecionado Double arrow Desenhe uma seta dupla entre dois cliques do mouse A seta dupla vive nos eixos onde o primeiro ponto foi selecionado Text Abra uma caixa de diálogo para inserir o texto então clique na janela da figura para posicionálo O texto vive nos eixos onde o primeiro ponto foi selecionado Rectangle Desenhe um retângulo dois cliques com o botão direito definem os cantos superior esquerdo e inferior direito do retângulo O retângulo vive nos eixos onde o primeiro ponto foi selecionado Circle Desenhe um círculo 2dois cliques com o botão direito definem os cantos superior esquerdo e inferior direito da caixa em que o círculo vive O retângulo vive nos eixos onde o primeiro ponto foi selecionado Ver Também graphicsentities set get clf plot Autor FLeray INRIA 697 Name oceancolormap Mapa de cores linear azul cmapoceancolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição oceancolormap computa um mapa de cores com n cores azuis que variam linearmente do preto para o azul Exemplos f scf plot3d1 fcolormap oceancolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap pinkcolormap rainbowcolormap springcolormap summercol ormap whitecolormap wintercolormap 698 Name oldplot Esboço simples versão antiga oldplotxyxcapycapcaption oldploty Parâmetros xy dois vetores de tamanhos iguais xcapycapcaption strings ou matrizes de strings Descrição Esboça y em função x xcap e ycap são legendas para os eixos x e y respectivamente e caption é a legenda do esboço IChamado com apenas um argumento oldploty esboça o vetor y ou se y for uma matriz esboça todos os vetores linhas em um mesmo esboço Isto é feito em relação ao vetor 1 número de colunas de y oldplot está obsoleto Use plot2d ou plot ao invés Exemplos x0012pi esboço simples oldplotsinx usando legendas xbasc oldplotxsinxsintempoesboço de seno esboço de duas funções xbasc oldplotsinxcosx Ver Também plot2d plot Autor JPhC 699 Name param3d esboço 3d de uma curva parametrizada param3dxyzthetaalphalegflagebox Parâmetros xyz três vetores de mesmo tamanho pontos da curva parametrizada theta alpha valores reais fornecendo em graus as coordenadas esféricas do ponto de observação os valores padrões são 35 e 45 graus leg string definindo rótulos para cada eixo com como separador de campo por exemploXYZ flagtypebox type e box possuem o mesmo significado que em plot3d type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos Este é o valor padrão type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2Note que as fronteiras dos eixos podem ser customizadas através das pro priedades da entidade de eixos ver axesproperties box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 param3d 700 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos também pode ser customizado através das propriedades da en tidade Axes ver axesproperties Este é o padrão ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag se este for ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds field que também pode ser ajustado através das propriedades da entidade de eixos ver axesproperties O valor padrão de ebox é 010101 Descrição param3d é usado para esboçar uma curva 3d definida por suas coordenadas x y e z Note que os dados também podem ser ajustados ou recebidos através das propriedades da entidade superfície ver surfaceproperties Note que propriedades como rotation angles colors e thickness da superfície esboçada também podem ser ajustadas através das propriedades de param3d ver param3dproperties Use param3d1 para realizar esboços múltiplos Entre com o comando param3d para visualizar uma demonstração Exemplos t0015pi param3dsintcostt103545XYZ23 egce o manipulador para a poligonal 3d eforegroundcolorred agca o manipulador para os eixos arotationangles10 70 Ver Também param3d1 plot3d Autor JPhC 701 Name param3d1 esboço 3d de curvas parametrizadas param3d1xyzthetaalphalegflagebox param3d1xylistzcolorsthetaalphalegflagebox Parâmetros xyz matrizes de mesmo tamanho nlnc Cada coluna i das matrizes corresponde às coordenadas da iésima curva Você pode fornecer uma cor específica para cada curva utilizando listzcolors ao invés de z onde colors é um vetor de tamanho nc Se colori for negativo a curva é esboçada utilizandose a marca com identificador absstylei se stylei for estritamente positivo uma linha simples com idenficador de cor stylei ou uma linha tracejada com identificador de tipo de tracejado stylei é utilizada thetaalpha valores reais fornecendo em graus as coordenadas esféricas do ponto de observação Os valores padrões são 35 e 45 graus leg string definindo rótulos para cada eixo com como separador de campo por exemplo XYZ flagtypebox type e box possuem o mesmo significado que em plot3d type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos Este é o valor padrão type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das pro priedades da entidade de eixos ver axesproperties param3d1 702 box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos também pode ser customizado através das propriedades da en tidade Axes ver axesproperties Este é o valor padrão ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag se este estiver ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds fque também pode ser ajustado através das propriedades da entidade de eixos ver axesproperties O valor padrão de ebox é 010101 Descrição param3d1 usado para esboçar curvas 3d definidas por suas coordenadas x y e z Note que os dados também podem ser ajustados ou recebidos através das propriedades da entidade Surface ver surfaceproperties Note que propriedades como rotation angles colors e thickness das curvas esboçadas também podem ser ajustadas através das propriedades de param3d ver param3dproperties Entre com o comando param3d1 para visualizar uma demonstração Exemplos xsetwindow20 criando janela de número 20 t0015pi param3d1sintsin2tcostcos2t listt10sint323545XYZ23 xdel20 agetcurrentaxesobtendo manipulador dos novos eixos criados t0015pi param3d1sintsin2tcostcos2tt10sint arotationangles6575 adatabounds111112 limites fornecidos por databounds athickness 2 hachildren obtendo o manipulador para a entidade Param3d um Compound composto de duas curvas hchildren1foreground 3 primeira curva curve2 hchildren2 curve2foreground 6 curve2markstyle 2 param3d1 703 Ver Também param3d plot3d plot2d gca xdel delete Autor JPhC 704 Name param3dproperties description of the 3D curves entities properties Descrição A entidade Param3d é uma folha na hierarquia de entidades gráficas visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão as curvas são visíveis a propriedade é on Se off as curvas não são desen hadas na tela data este campo contém as coordenadas de curvas 3d É a matriz XYZ tal que Xi Yi Zi contém as coordenadas 3d da iésima curva Este campo contém o valor padrão da propriedade linestyle para objetos segmentos arcos retângulos e poligonais linemode este campo contém o valor padrão da propriedade linemode para a poligonal O valor pode ser on linha desenhada ou off nenhuma linha desenhada linestyle este campo seleciona o tipo de linha a ser utilizada para desenhar linhas O valor deve ser um inteiro em 0 6 0 significa linha sólida o restante seleciona tracejados ver getlinestyle polylinestyle este campo seleciona o modo como as curvas são desenhadas modos interpolado padrão escada esboço de barras em setas e preenchido estão disponíveis por índices inteiros em 15 markmode este campo contém o valor padrão da propriedade markmode Deve ser on ou off valor padrão markstyle este campo contém o valor padrão da propriedade markstyle A propriedade markstyle seleciona o tipo de marca a ser exibida o valor deve ser um inteiro em 0 9 que significa ponto sinal de mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo trevo e círculo marksizeunit este campo contém o valor padrão da propriedade marksizeunit Se marksizeunit for ajustado para point então o valor de marksize é diretamente dado em pontos Quan do marksizeunit é ajustado para tabulated marksize é computado em relação ao array de tamanho de fonte logo seu valor deve ser um inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que param3d e funções puras do Scilab utilizam o modo tabulat ed como padrão quando se utiliza a função plot o modo point é automaticamente habilitado marksize este campo contém o valor padrão da propriedade marksize A propriedade marksize seleciona o tamanho de fonte da marca a ser exibida Deve ser um valor inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt ver getmark markforeground este campo contém o valor da propriedade markforeground que é a cor da borda das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor da propriedade markbackground que é a cor da face das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente param3dproperties 705 thickness este campo contém o valor padrão da propriedade thickness espessura das linhas utilizadas para desenhar os eixos e curvas Deve ser um inteiro positivo foreground este campo contém o índice de cor utilizado para desenhar as curvas O valor deve ser um índice de cor relativo ao mapa de cores corrente clipstate este campo contém o valor padrão da propriedade clipstate O valor pode ser off significa que todas as curvas criadas posteriormente não serão recortadasvalor padrão clipgrf significa que todas as cruvas criadas posteriormente serão recortadas fora do fora das fronteiras da entidade Axes on significa que todas as curvas criadas posteriormente serão recortadas fora do retângulo dado pela propriedade clipbox clipbox este campo contém o valor padrão da propriedade clipbox É uma matriz vazia se clipstate é off Em outros casos o recorte é dado pelo vetor xywh ponto superior esquerdo largura altura userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade Param3d e recuperála parent esta propriedade contém o manipulador para a raiz A raiz de uma entidade curvas 3d deve ser do tipo Axes ou Compound Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados t0015pi param3d1sintsin2tcostcos2tt10sint arotationangles6575 adatabounds111112 limites dados por databounds athickness 2 hachildren obtendo o manipulador da entidade param3d um Compound composto de duas curvas hchildren1foreground 3 primeira curva curve2 hchildren2 curve2foreground 6 curve2markstyle 2 Ver Também set get delete param3d param3d1 graphicsentities Autor Djalel ABDEMOUCHE 706 Name paramfplot2d Esboço animado 2d curva definida por uma função paramfplot2dfxtheta paramfplot2dfxthetaflag paramfplot2dfxthetaflagrect Parâmetros x vetor de reais f função yfxt f é uma função Scilab ou rotina dinamicamente ligada referida através de um string theta vetor de reais conjunto de parâmetros flag string no ou yes Se yes a janela é limpa entre dois esboços consecutivos rect retângulo xmin xmax ymin ymax 1 x 4 vetor de reais Descrição Esboço animado da função xfxt para t theta1 theta2 etc f pode ser uma função do Scilab ou uma rotina dinamicamente ligada desde que yfxt seja avaliado como yfevalxtf Ver feval A função f tal que xt fxt RN é avaliada em x vetor de RN e tnúmero real x é um Nvetor de valores x e para cada t em theta fxtNvetor de valores y Exemplos deffyfxtytsinx xlinspace02pi50theta00051 paramfplot2dfxtheta Ver Também plot2d feval fplot2d 707 Name pie Desenha um gráfico de torta piex piexsptxt Parâmetros x um escalar real ou vetor de reais positivos sp um escalar real ou vetor de reais txt uma célula ou vetor de strings Descrição piex se o tamanho de x é N então a função desenha um gráfico de torta de N partes a área da i ésima parte é igual a xisumx superfície do círculo unitário piexsp o vetor sp permite cortar um ou vários pedaços da torta o tamanho de sp deve ser igual a N Se o valor do iésimo índice de sp é diferente de 0 então a iésima parte é separada das outras por um espaço senão se for igual a zero então é anexada às outras piextxt o vetor txt permite escrever um texto para cada parte da torta o iésimo componente de txt corresponde à iésima parte da torta padrão são escritas as porcentagens que correspondem às partes da superfície O tamanho de txt deve ser igual a N Exemplos primeiro exemplo um argumento de entrada x1 2 5 scf0 pie1 2 5 segundo exemplo dois argumentos de entrada x5 9 4 6 3 sp0 1 0 1 0 o segundo e o quarto são separados dos demais scf1 pie5 9 4 6 30 1 0 1 0 terceiro exemplo três argumentos de entrada x3 4 6 2 sp0 1 0 0 txtparte 1parte 2parte 3parte 4 scf2 pie3 4 6 20 1 0 0parte 1parte 2parte 3parte 4 Ver Também xfpolys Autor Farid Belahcene 708 Name pinkcolormap Coloração de tons em sépia de imagens em preto e branco cmappinkcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição pinkcolormap computa um mapa de cores que fornece uma coloração de tons em sépia de imagens em preto e branco Exemplos f scf plot3d1 fcolormap pinkcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap rainbowcolormap springcolormap summercol ormap whitecolormap wintercolormap 709 Name plot Esboço 2d plotyLineSpecGlobalProperty plotxyLineSpecGlobalProperty plotx1y1LineSpec1x2y2LineSpec2xNyNLineSpecNGlobalProperty1GlobalProperty2GlobalPropertyM plotaxeshandle Parâmetros x uma matriz ou vetor de reais Se omitido é assumido como sendo o vetor 1n onde n é o número de pontos de curva dado pelo parâmetro y y uma matriz de reais ou um vetor y também pode ser uma função definida como um macro ou uma primitiva LineSpec este argumento opcional deve ser usado como um atalho para especificar um modo de desen har uma linha Podemos ter um LineSpec por y ou xy previamente entrados As opções LineSpec lidam com os especificadores LineStyle Marker e Color ver LineSpec Estes es pecificadores determinam o estilo de linha de marcas e a cor das linhas esboçadas GlobalProperty este argumento opcional representa uma seqüência de pares de declarações PropertyNamePropertyValue tque define propriedades globais de objetos a serem aplicadas a todas as curvas criadas pelo esboço Para uma visualização completa de das pro priedades disponíveis veja GlobalProperty axeshandle este argumento opcional força o esboço a aparecer dentro dos eixos selecionados fornecidos por axeshandle ao invés dos eixos correntes ver gca Descrição plot esboça um conjunto de curvas 2d plot foi reconstruído para lidar melhor com a sintaxe do Matlab Para melhorar a compatibilidade gráfica com o Matlab utilize plot ao invés de plot2d Especificação de entrada de dados Neste parágrafo para sermos mais claros não mencionaremos os argumentos opcionais LineSpec ou GlobalProperty já que eles não interferem na entrada de dados exceto pelas propriedades Xdata Ydata e Zdata ver GlobalProperty É assumido que todos estes argumentos po dem estar presentes também Se y é um vetor ploty esboça um vetor y versus o vetor 1sizey Se y é uma matriz ploty esboça cada coluna de y versus o vetor 1sizey1 Se x e y são vetores plotxy esboça o vetor y versus o vetor x Os vetores x e y devem ter o mesmo número de entradas Se x é um vetor e y uma matriz plotxy esboça cada coluna de y versus o vetor x Neste caso o número de colunas de y deve ser igual ao número de entradas de x Se x e y são matrizes plotxy esboça cada coluna de y versus a coluna correspondente de x Neste caso os tamanhos x e y devem ser os mesmos plot 710 Finalmente se apenas x ou y é uma matriz o vetor é esboçado versus cada linha ou cada coluna da matriz A escolha é feita dependendo se a dimensão de linha ou coluna do vetor coincide com a dimensão de linha ou coluna da matriz No caso de uma matriz quadrada apenas x ou penas y a prioridade é dada a colunas ao invés de linhas ver exemplos abaixo y também pode ser uma função definida como um macro ou uma primitiva Neste caso os dados x devem ser fornecidos como um vetor ou uma matriz e a computação correspondente de yx é feita implicitamente Os argumentos LineSpec e GlobalProperty devem ser utilizados para customizar o esboço Aqui está uma lista completa das opções disponíveis LineSpec esta opção pode ser utilizada para se especificar de um modo curto e fácil como as curvas são de senhadas Deve sempre ser um string contendo referências aos especificadores LineStyle Marker e Color Essas referências devem ser ajustadas denro do string a ordem não é importante de modo a não ter ambigüidades Por exemplo para especificar uma linha vermelha de traço longo com marcas de rombos podese escrever rd ou dire ou reddiam ou outra sentença sem ambigüidade ou de modo completo diamondred ver LineSpec Note que os estilos de linha e marcas e tamanhos e as cores podem ser reajustados através das propriedades da entidade poligonal ver polylineproperties GlobalProperty esta opção pode ser utilizada para especificar como as linhas serão desenhadas com mais opções que via LineSpec Deve sempre ser um par de declarações constituidos de um string definindo PropertyName nome da propriedade e seu valor associado PropertyValue que pode ser um string um inteiro ou qualquer outra coisa dependendo do tipo de PropertyName Utilizandose GlobalProperty podese ajustar várias propriedades todas as propriedades disponíveis via LineSpec e mais a cor da marca plano de fundo e primeiro plano a visibilidade o recorte e a espessura das curvas ver GlobalProperty Note que todas as propriedades podem ser reajustadas através das propriedades de entidades poligonais ver polylineproperties Observações Por padrão esboços sucessivos são superpostos Para limpar o esboço anterior use clf Para ha bilitar o modo autoclear limpeza automática como modo padrão edite seus eixos fazendo o seguinte dagda daautoclear on Para uma melhor exibição a função plot pode modificar a propriedade box de seu Axes eixos raíze Isto acontece quando uma entidade Axes é criada por uma chamada a plot ou é vazia antes da chamada Se um dos eixos é centrado na origem box é desabilitado Em caso contrário box é habilitado Para mais informações sobre a propriedade box e sobre o posicionamento dos eixos veja axesproperties Uma tabela de cores padrão é utilizada para colorir as curvas esboçadas quando você não especifica as cores Ao desenhar linhas múltiplas o comando plot automaticamente atribui as cores abaixo de modo cíclico Aqui estão as cores utilizadas R G B 0 0 1 plot 711 0 05 0 1 0 0 0 075 075 075 0 075 075 075 0 025 025 025 Entre com o comando plot para visualizar uma demonstração Exemplos inicialização de x x0012pi esboço simples plotsinx clf plotxsinx esboços múltiplos clf plotxsinx sin2x sin3x clf eixo à direita plotxsinx agca manipulador da entidade Axes aylocation right clf eixo centrado em 00 plotx4sinxx2cosx agca manipulador da entidade Axes axlocation middle aylocation middle algumas operações em entidades criadas por plot agca aisoviewon achildren listando os galhos da entidade Axes aqui é um galho Compound composto por duas entidades poly1 achildrenchildren2 armazenando um manipulador Polyline em poly1 poly1foreground 4 outro modo de se mudar o estilo poly1thickness 3 e a espessura de uma curva poly1clipstateoff controle de recorte aisoviewoff exemplos com LineSpec e GlobalProperty clf t0pi202pi plottsintrotcostcyatabssintmo scf2 plott tsint costxdat12 scf3 axfig3 gca scf4 deveria permanecer em branco plotaxfig3t tsint costzdat12markerdmarkerfacgreenmarkeredgyel plot 712 xdelwinsid especificação de dados tpi01pi sizet plott esboços simples de y versus tamanho do vetor t clf limpando figura plottsint esboça sint versus t clf t1 1 1 1 2 3 4 5 3 4 5 6 4 5 6 7 plott esboça cada coluna t column versus tamanho de linha clf subplot221 plottsint esboça sint versus t coluna por coluna desta vez xtitlesint versus t subplot222 plottsint xtitlesint versus t subplot223 plottsint agca adatabounds0 17 1 para ver a linha vertical escondida pelo eixo y xtitlesint versus t subplot224 plottsint xtitlesint versus t clf caso especial 1 x vector 5 6 7 8 and y matrix t x5 6 7 8 plotxt plotxt idem x é automaiticamente transposto para corresponder a t aqui as colunas clf apenas um caso de possibilidade de correspondência como realizar quatro esboços idênticos 4 de quatro maneiras 4 x é um vetor 1x4 vector y is uma matriz nãoquadrada 4x5 subplot221 plotxt 891012 subplot222 plotxt 891012 subplot223 plotxt 891012 subplot224 plotxt 891012 clf caso especial 2 caso onde apenas x ou y é uma matriz quadrada x matrix t e y vetor 1 2 3 4 plot 713 plott1 2 3 4 equivalente a plott1 1 1 12 2 2 23 3 3 34 4 4 4 plott1234 o mesmo esboço clf t é transposto note a prioridade dada ao tratamento das colunas plott1 2 3 4 equivalente a plott1 1 1 12 2 2 23 3 3 34 4 4 4 plott1 2 3 4 o mesmo esboço clf y é uma função definida por uma primitiva plot10110sin equivalente a plot10110sin10110 clf uma macro deffytotoxyxx plot110toto Ver Também plot2d surf scf clf xdel delete LineSpec GlobalProperty Autor FLeray 714 Name plot2d esboço 2d plot2dxy plot2dxyoptargs Parâmetros x uma matriz ou vetor de reais Se omitido é assumido como sendo o vetor 1n onde n é o número de pontos da curva dados pelo parâmetro y y uma matriz ou vetor de reais optargs representa uma seqüência de sentenças key1value1key2value2 onde key1 key2 podem ser um dos seguintes style ajusta o estilo da curva O valor associado deve ser um vetor de reais com valores inteiros positivos ou negativos rect as fronteiras mínimas requeridas para o esboço O valor associado deve ser um vetor de reais com quatro entradas xminyminxmaxymax logflag ajusta a escala linear ou logaritmica ao longo dos eixos O valor associado deve ser um string com um dos possíveis valores nn nl ln e ll frameflag controla a computação dos intervalos de coordenadas reais a partir dos valores mínimos re queridos O valor associado deve ser um inteiro entre 0 e 8 axesflag especifica como os eixos são desenhados O valor associado deve ser um inteiro entre 0 e 5 nax ajusta os rótulos dos eixos e a definição de tiques O valor associado deve ser um vetor de quatro entradas inteiras nxNxnyNy leg ajusta a legenda das curvas O valor associado deve ser um string Descrição plot2d esboça um conjunto de curvas 2d Se você está familiarizado com a sintaxe do Matlab da função plot você deve usar plot Se x e y são vetores plot2dxyoptargs esboça o vetor y versus o vetor x Os vetores x e y vectors devem ter o mesmo número de entradas Se x é um vetor e y uma matriz plot2dxyoptargs esboça cada coluna de y versus o vetor x Neste caso o número de colunas de y deve ser igual ao número de entradas de x Se x e y são matrizes plot2dxyoptargs esboça cada coluna de y versus a coluna correspondente de x Neste caso x e y devem ter o mesmo tamanho plot2d 715 Se y é um vetor plot2dyoptargs esboça o vetor y versus o vetor 1sizey Se y é uma matriz plot2dyoptargs esboça cada coluna de y versus o vetor 1sizey1 Os argumentos optargs devem ser usados para customizar o esboço style esta opção deve ser usada para especificar como as curvas são desenhadas Se esta opção for especificada o valor associado deve ser um vetor com tantas entradas quanto as curvas Se stylei é estritamente crescente a curva é desenhada como uma linha simples e stylei define o índice da cor para utilizada para desenhar a curva ver getcolor Note que o estilo de linha e a espessura podem ser ajustados através das propriedades da entidade poligonal ver polylineproperties Interpolação linear é feita entre os dados pontos da curva Se stylei é negativo ou zero os pontos dados são desenhados utilizandose marcas absstylei define a marca com identificador utilizada Note que as cores das mar cas e seus tamanhos podem ser ajustados através das propriedades da entidade poligonal ver polylineproperties logflag esta opção é usada para ajustar a escala linear ou logarítmica ao longo dos eixos O valor asso ciado é um string com um dos seguintes valores nn nl ln e ll l significa escala e graduação logarítimica e n escala normal rect esta opção pode ser usada para ajustar as fronteiras mínimas requeridas para o esboço Se esta opção for especificada o valor associado deve ser um vetor real de quatro entradas xminyminxmaxymax xmin e xmax definem os limites para as abscissas enquanto ymin e ymax definem os limites para as ordenadas Este argumento pode ser utilizado junto com a opção frameflag para especificar como os limites dos eixos derivam do argumento dado rect Se a opção frameflag não for fornecida é suposta como sendo frameflag7 As fronteiras dos eixos também podem ser customizadas através das propriedades da entidade de eixos Axes ver axesproperties frameflag esta opção pode ser usada para controlar a computação dos intervalos de coordenadas reais a partir de valores mínimos requeridos Mudanças reais podem ser maiores que os requerimentos mínimos frameflag0 não há computação o esboço usa a escala anterior ou padrão frameflag1 os intervalos reais são dados pela opção rect frameflag2 os intervalos reais são computados a partir dos valores máximos e mínimos dos dados x e y frameflag3 os intevalo reais são os intervalos fornecidos pela opção rect e aumentados para se obter uma escala isométrica frameflag4 os intervalos reais são computados a partir dos valores máximos e mínimos de x e y e au mentados para se obter uma escala isométrica plot2d 716 frameflag5 os intervalos reais são os intervalos fornecidos pela opção rect e aumentados para se obter rótulos de eixos embelezados frameflag6 os intervalos reais são computados a partir dos valores mínimos dos dados x e y e então aumentados para se obter rótulos de eixos embelezados frameflag7 é como frameflag1 mas os esboços anteriores são redesenhados em uma nova escala É utilizado para adicionar o gráfico corrente a um anterior frameflag8 é como frameflag2 mas os esboços anteriores são redesenhados em uma nova escala É utilizado para adicionar o gráfico corrente a um anterior frameflag9 é como frameflag8 mas a imagem é aumentada enlarged to para se obter rótulos de eixos embelezados Este é o alor padrão Os limites dos eixos também podem ser customizados através das propriedades da entidade de eixos ver axesproperties axesflag esta opção pode ser utilizada para especificar como os eixos são desenhados O valor associado deve ser um inteiro entre 0 e 5 axesflag0 nada é desenhado ao redor do esboço axesvisibleoff offboxoff axesflag1 os eixos são desenhados o eixo y é exibido à esquerda axesvisibleon onboxonylocationleft axesflag2 o esboço é cercado por uma caixa sem tiques axesvisibleoff offboxon axesflag3 os eixos são desenhados o eixo y é exibido à direita axesvisibleon onboxoffylocationright axesflag4 os eixos são desenhados centrados no meio da caixa de moldura axesflag5 os eixos são desenhados para se cruzarem no ponto 00 Se o ponto 00 não estiver dentro da moldura os eixos não aparecerão no gráfico axesvisibleon onboxonylocationmiddle axesflag9 os eixos são desenhados o eixo y é exibido à esquerda axesvisibleon onboxoffylocationleft Este é o valor padrão O aspecto dos eixos também pode ser customizado através das propriedades da entidade de eixos ver axesproperties nax esta opção pode ser utilizada para se especificar os rótulos dos eixos e a definição de tiques quando a opção axesflag1 é utilizada O valor associado deve ser um vetor de inteiros com quatro entradas nxNxnyNy plot2d 717 Nx fornece o número de tiques principais utilizados no eixo x não mais levado em conta nx fornece o número de subtiques entre dois tiques principais no eixo x Ny e ny fornecem as informações similares para o eixo y Se a opção axesflag não for ajustada a opção nax supõe que a opção axesflag foi ajustada para 1 leg esta opção pode ser usada para se ajustar as legendas das curvas deve ser um string com a forma leg1leg2 onde leg1 leg2 etc São respectivamente as legendas para a primeira curva segunda curva etc o padrão é As legendas de curvas são desenhadas abaixo do eixo x Esta opção não é tão flexível use as funções captions ou legend preferivelmente Mais Informações Para obter mais informações sobre a sintaxe antiga de plot 2d veja a documentação plot2doldversion Por padrão esboços sucessivos são superpostos para limpar o esboço anterior use clf Entre com o comando plot2d para uma demonstração Outras funções plot2d de alto nível existem plot2d2 é o mesmo que plot2d mas as curvas são supostas seccionalmente constantes plot2d3 é o mesmo que plot2d mas a curva é esboçada com barras verticais plot2d4 é o mesmo que plot2d mas a curva é esboçada com flechas Exemplos inicialização de x x0012pi esboço simples plot2dsinx clf plot2dxsinx múltiplos esboços clf plot2dxsinx sin2x sin3x múltiplos esboços sem fornecer as dimensões da moldura clf plot2dxsinx sin2x sin3xrect00605 múltiplos esboços com legendas dados tiques estilo clf plot2dxsinx sin2x sin3x 123legL1L2L3nax210210rect022pi2 isovisualização clf plot2dxsinx1frameflag 4 escala clf plot2dxsinx1frameflag 6 autoescala com esboços anteriores estilo plot2d 718 clf plot2dxsinx1 plot2dx2sinx12 plot2d2xcosx3 eixo à direita clf plot2dxsinxlegsinx agca manipulador da entidade Axes aylocation right eixo centrado em 00 clf plot2dx4sinx1legsinx agca manipulador da entidade Axes axlocation middle aylocation middle algumas operações sobre entidades criadas por plot2d agca aisoviewon achildren lista dos galhos dos eixos há um Compound formado por duas poligonais e uma legenda poly1 achildren1children1 armazena um manipulador de poligonal em poly1 poly1foreground 4 outra maneira de se mudar o estilo poly1thickness 3 e a espessura de uma curva poly1clipstateoff controle de recorte leg achildren2 armazena manipulador de legenda em leg legfontstyle 9 leglinemode on aisoviewoff Ver Também plot plot2d1 plot2d2 plot2d3 plot2d4 clf xdel delete 719 Name plot2d1 Esboço 2d em escala logarítmica obsoleto plot2d1strxystylestrflegrectnax Parâmetros str string de comprimento 3 abc a pode ter um dos seguintes valores e o ou g e significa vazio Especifica que o valor de x não é utilizado os valores de x são supostos regularmente espaçados ie 1número de linhas de y De qualquer forma o usuário deve fornecer o valor de x 1 por exemplo plot2d1enn1y o significa um Se há várias curvas todas possuem o mesmo valor x x é um vetor col una de tamanho n1 e y é uma matriz de tamanhonlnc Por exemplo x0012 piplot2d1onnxsinx cosx g significageral x e y devem ter o mesmo tamanho nlnc Cada coluna de y é esboçada em relação à coluna correspondente de x nc curvas são esboçadas utilizandose nl pontos b c pode possuir valores n normal ou l logarítmico bl um eixo logarítmico é utilizado em x cl um eixo logarítmico é utilizado em y xystylestrflegrectnax estes argumentos possuem o mesmo significado que na função plot2d optargs estes argumentos possuem o mesmo significado que na função plot2d Descrição Esta função está obsoleta Utilize plot2d ao invés plot2d1 esboça um conjunto de curvas 2d É o mesmo que plot2d mas com mais um argumento str que habilita escala logarítmica Ainda permite especificar apenas um vetor coluna para x quando é o mesmo para todas as curvas Por padrão esboços sucessivos são superpostos Para limpar o esboço anterior use clf Entre com o comando plot2d1 para visualizar uma demonstração Exemplos plot2d1 720 esboços múltiplos sem fornecer x x0012pi plot2d1enn1sinx sin2x sin3x esboços múltiplos fornecendo apenas x clf plot2d1onnxsinx sin2x sin3x esboço logarítmico x01013 clf plot2d1ollxexpx expx2 expx3 Ver Também plot2d plot2d2 plot2d3 plot2d4 clf Autor JPhC 721 Name plot2d2 esboço 2d funções de degraus plot2d2xy plot2d2xyoptargs plot2d2logflagxystylestrflegrectnax Parâmetros args ver plot2d para uma descrição dos parâmetros Descrição plot2d2 é o mesmo que plot2d mas as funções dadas por xy são supostas seccionalmente constantes Por padrão esboços sucessivos são superpostos Para limpar os esboços anteriores use clf Entre com o comando plot2d2 para visualizar uma demonstração Note que todos os modos propostos por plot2dxx xx 1 a 4 podem ser habilitados utilizandose plot2d e ajustando a opção polylinestyle para o número correspondente Exemplos esboçando uma função de degrau de valor i no segmento ii1 o último segmento não é desenhado plot2d214141111função de degrau0055 compare o seguinte com plot2d x0012pi clf plot2d2xsinx sin2x sin3x apenas no novo modo gráfico clf plot2dxsinx sin2x sin3x egce echildren1polylinestyle2 echildren2polylinestyle2 echildren3polylinestyle2 Ver Também plot2d plot2d3 plot2d4 subplot clf polylineproperties Autor JPhC 722 Name plot2d3 esboço 2d barras veticais plot2d3logflags xystylestrflegrectnax plot232y plot2d3xy optargs Parâmetros args ver plot2d para uma descrição dos parâmetros Descrição plot2d3 é o mesmo que plot2d mas as curvas são esboçadas utilizandose barras verticais Por padrão esboços sucessivos são superpostos Para limpar esboços anteriores use clf Entre com o comando plot2d3 para visualizar uma demonstração Note que todos os modos pro postos por plot2dxx xx 1 a 4 podem ser habilitados utilizandose plot2d podem ser habilita dos utilizandose polylinestyle para o número correspondente Exemplos compare o seguinte com plot2d1 x0012pi plot2d3xsinx sin2x sin3x no novo modo de gráficos apenas clf plot2dxsinx sin2x sin3x egce echildren1polylinestyle3 echildren2polylinestyle3 echildren3polylinestyle3 Ver Também plot2d plot2d2 plot2d4 clf polylineproperties Autor JPhC 723 Name plot2d4 esboço 2d setas plot2d4logflag xystylestrflegrectnax plot2d4y plot2d4xy optargs Parâmetros args ver plot2d para uma descrição dos parâmetrosfor a description of parameters Descrição plot2d4 é o mesmo que plot2d mas as curvas são esboçadas utilizandose setas Isto pode ser útil para se esboçar solulções de uma EDO equação diferencial ordinária em um espaço fásico Por padrão esboços sucessivos são superpostos Para limpar o esboço anterior use clf Entre com o comando plot2d4 para visualizar uma demonstração Note que todos os modos propostos por plot2dxx xx 1 a 4 podem ser habilitados utilizandose plot2d e ajustandose a opção polylinestyle para o número correspondente Exemplos compare o seguinte com plot2d1 x0012pi plot2d4xsinx sin2x sin3x apenas no novo modo gráfico clf plot2dxsinx sin2x sin3x egce echildren1polylinestyle4 echildren2polylinestyle4 echildren3polylinestyle4 Ver Também fchamp plot2d plot2d2 plot2d3 subplot clf polylineproperties Autor JPhC 724 Name plot2doldversion As sintaxes descritas abaixo estão obsoletas plot2dlogflagxystylestrflegrectnax Parâmetros xy duas matrizes ou vetores colunas De maneira usual x é uma matriz de mesmo tamanho que y a coluna j de y é esboçada em relação à coluna j de x Se todas as colunas de x são iguais ie as abscissas de todas as curvas são as mesmas x pode ser simplesmente o vetor coluna destas abscissas x é então um vetor coluna de comprimento igual a dimensão de linha de y Quando x não é fornecido é suposto como sendo o vetor 1 2 dimensão de linha de y style é um vetor real de tamanho nc O estilo a ser utilizado na curva i é definido por stylei O estilo padrão é 1nc 1 para a primeira curva 2 para a segunda etc Se stylei é negativo ou zero a curva é esboçada com marca de identificador absstylei use xset para ajustar o identificador de marca e xgetmark para obter o identificador de marca corrente Se stylei for estritamente positivo uma linha simples de identificador de cor stylei ou uma linha tracejada com identificador de tracejado stylei é utilizada use xset para vizualizar os identificadores de cor Quando apenas uma curva é desenhada style pode ser um vetor linha de tamanho stypos onde sty é utilizado para especificar o estilo e pos é um inteiro entre 1 e 6 que especifica uma posição a ser utilizada para a legenda Pode ser útil quando o usuário dese ja desenhar múltiplas curvas em um esboço chamando a função plot2d várias vezes e quer fornecer uma legenda para cada curva Esta opção não possui mais efeito no modo gráfico novo Utilize a função captions para ajustar as legendas quando todas as curvas forem desenhadas strf string de comprimento 3 xyz por padrão strf 081 x controla a exibição de legendas x0 sem legendas x1 legendas são exibidas Elas são dadas pelo argumento opcional leg y controla a computação dos intervalos de coordenadas reais a partir dos valores mínimos re queridos Intervalos reais podem ser maiores que os requerimentos mínimos y0 sem computação o esboço utiliza a escala anterior ou padrão plot2doldversion 725 y1 a partir do argumento rect y2 a partir dos valores mínimomáximo dos dados x e y y3 constrói uma escala isométrica a partir do argumento rect y4 constrói um esboço isométrico a partir dos valores mínimomáximo dos dados x e y y5 aumentados para obtenção de bons eixos a partir do argumento rect y6 aumentados para obtenção de bons eixos a partir dos valores mínimomáximo dos dados x e y y7 como y 1 mas os anteriores são redesenhados para se utilizar a nova escala y8 como y 2 mas os anteriores são redesenhados para se utilizar a nova escala z controla a exibição de informação na moldura ao redor do esboço Se eixos são requeridos o número de tiques pode ser especificado pelo argumento opcional nax z0 nada é desenhado ao redor do esboço z1 eixos são desenhados o eixo y é exibido à esquerda z2 o esboço é cercado por uma caixa sem tiques z3 eixos são desenhados o eixo y é exibido à direita z4 eixos são desenhados centrados no meio da caixa de moldura z5 eixos são desenhados cruzandose no ponto 00 Se o ponto 00 não estiver den tro da moldura os eixos não aparecerão no gráfico leg um string É utilizado quando o primeiro caractere x do argumento strf é 1 leg tem a forma leg1leg2 onde leg1 leg2 etc são respectivamente as legendas para a primeira segunda etc curvas O padrão é rect este argumento é utilizado quando o segundo caractere y do argumento strf is 1 3 ou 5 é 1 3 ou 5 É um vetor linha de tamanho quatro e fornece a dimensão da moldura rectxminyminxmaxymax nax este argumento opcional é utilizado quando o terceiro caractere z do argumento strf é 1 É um vetor linha de quatro entradas nxNxnyNy onde nx ny é o número de subgraduações no eixo x y axis e Nx Ny é o número de graduações no eixo x y plot2doldversion 726 logflag um string formado por dois caracteres h para eixo horizontal e v for para eixo vertical cada um desses caracteres pode assumir valores n ou l l corresponde à graduação logarítmica e n à graduação normal Por exemplo ll corresponde a um esboço com ambos os eixos x e y em graduação logarítmica O valor padrão é nn Descrição plot2d esboça um conjunto de curvas 2d Esboço linear seccional é utilizado Por padrão esboços sucessivos são superpostos Para limpar o esboço anterior use xbasc Veja o significado dos parâmetros acima para uma completa descrição Entre com o comando plot2d para uma demonstração Outras funções plot2d de altonível existem plot2d2 é o mesmo que plot2d mas as curvas são supostas seccionalmente constantes plot2d3 é o mesmo que plot2d mas a curva é esboçada com barras verticais plot2d4 é o mesmo que plot2d mas a curva é esboçada com flechas Exemplos esboço simples x0012pi plot2dsinx xbasc plot2dxsinx esboços múltiplos xbasc plot2dxsinx sin2x sin3x esboços múltiplos fornecendo as dimensões da moldura sintaxe antiga e sintaxe nova xbasc plot2dxsinx sin2x sin3x1301100605 xbasc plot2dxsinx sin2x sin3xrect00605 esboços múltiplos com legendas e tiques dados velha sintaxe e nova sintaxe xbasc plot2dxsinx sin2x sin3x 123111L1L2L3022pi2210210 xbasc plot2dxsinx sin2x sin3x 123legL1L2L3nax210210rect022pi2 isovisualização xbasc plot2dxsinx1041 escala xbasc plot2dxsinx1061 autoescala com esboços anteriores xbasc plot2dxsinx1 plot2dx2sinx2 plot2d2xcosx3 plot2doldversion 727 eixo à direita xbasc plot2dxsinx1183sinx eixo centrado xbasc plot2dxsinx1184sinx eixo centrado em00 xbasc plot2dx4sinx1185sinx Ver Também plot2d1 plot2d2 plot2d3 plot2d4 xbasc xset Autor JPhC 728 Name plot3d esboço 3d de uma superfície plot3dxyzthetaalphalegflagebox plot3dxyzoptargs plot3dxfyfzfthetaalphalegflagebox plot3dxfyfzfoptargs plot3dxfyflistzfcolorsthetaalphalegflagebox plot3dxfyflistzfcolorsoptargs Parâmetros xy vetores linhas de tamanhos n1 e n2 coordenadas dos eixos x e y Estas coordenadas devem ser monótonas z matriz de tamanho n1n2 zij é o valor da superfície no ponto xiyj xfyfzf matrizes de tamanho nfn Elas definem as facetas usadas para desenhar a superfície Há n fac etas Cada faceta i é definida por um polígono com nf pontos As coordenadas dos eixos x y e z dos pontos da iésima faceta são dados respectivamente por xfi yfi e zfi colors um vetor de tamanho n fornecendo as cores de cada faceta ou uma matriz de tamanho nfn fornecendo a cor próxima a cada borda da faceta a cor da faceta é interpolada optargs representa uma seqüência de sentenças key1value1 key2value2 onde key1 key2 pode ser um dos seguintes theta alpha leg flag ebox ver definições abaixo theta alpha valores reais de dados em graus as coordenadas esféricas de observação do ponto leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho três flagmodetypebox mode um inteiro cor da superfície mode0 a superfície é pintada com a cor mode a borda da faceta é desenhada com o estilo e linha e cor correntes mode0 uma malha da superfície é desenhada mode0 a superfície é pintada com a cor mode a borda da faceta não é desenhada Note que o tratamento de cor da superfície pode ser feito utilizandose as opções colormode e colorflag através das propriedades da entidade superfície ver surfaceproperties plot3d 729 type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relção de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relção de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das propriedades da entidade de eixos ver axesproperties box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos pode ser customizado através das propriedades da entidade de eixos ver axesproperties ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag se este for ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds que também pode ser ajustado através das propriedades da entidade de eixos ver axesproperties plot3d 730 Descrição plot3dxyzthetaalphalegflagebox desenha a superfície parametrizada zfxy plot3dxfyfzfthetaalphaleg flagebox desenha uma superfície defini da por um conjunto de facetas Você pode desenhar esboços multiplos substituindo xf yf e zf por múltiplas matrizes montadas por linhas como xf1 xf2 yf1 yf2 e zf1 zf2 Note que os dados também podem ser ajustados ou recebidos através das propriedades da entidade superfície ver surfaceproperties Você pode fornecer uma cor específica para cada faceta utilizando listzfcolors ao invés de zf onde colors é um vetor de tamanho n Se colorsi for positivo fornece a cor da faceta i e a borda da faceta é desenhada utilizandose o estilo de linha e cor correntes Se colorsi for negativo o identificador de cor colorsi é utilizado e a borda da faceta não é desenhada Também é possível obter cores interpoladas para as facetas Para este tipo de cor o argumento deve ser uma matriz nf x n fornecendo as cores próximas a cada borda da faceta de cada faceta Neste caso valores positivos para cores significam que as bordas não seram desenhadas Note que as cores também podem ser ajustadas através das propriedades da entidade Surface superfície via tlist affectations e editadas utilizandose a opção colorflag ver surfaceproperties Os arugumentos opcionais theta alpha leg flag ebox podem ser passados por uma seqüência de argumentos key1value1 key2value2 Neste caso a ordem não tem sig nificado especial Note que todos estes argumentos exceto flag podem ser customizados através de propriedades da entidade de eixos ver axesproperties Como descrito anteriormente a opção flag lida com as propriedades da entidade superfície para mode ver surfaceproperties e as propriedades de eixos Axes para type e box ver axesproperties Você pode utilizar a função genfac3d para computar facetas de quatro lados da superfície zfxy eval3dp também pode ser utilizado Entre com o comando plot3d para visualizar uma demonstração Exemplos esboço simples utilizando zfxy t0032pi zsintcost plot3dttz o mesmo esboço utilizando facetas computadas por genfac3d xxyyzzgenfac3dttz clf plot3dxxyyzz esboços múltiplos clf plot3dxx xxyy yyzz 4zz esboços múltiplos utilizandose cores clf plot3dxx xxyy yylistzz zz44ones1400 5ones1400 esboço simples utilizando ponto de observação e legendas clf plot3d11012010rand1020alpha35theta45flag223 plot3d 731 esboço de uma esfera utilizando utilizando facetas computadas por eval3dp deffxyzsphalptetxrcosalpcostetorig1onestet yrcosalpsintetorig2onestet zrsinalporig3onestet r1 orig0 0 0 xxyyzzeval3dpsphlinspacepi2pi240linspace0pi220 clfplot3dxxyyzz clf fgcf fcolormap hotcolormap128 r03orig15 0 0 xx1yy1zz1eval3dpsphlinspacepi2pi240linspace0pi220 ccxxzz232cc1xx1orig1zz1r232 clfplot3d1xx xx1yy yy1listzzzz1cc cc1theta70alpha80flag563 operações disponíveis apenas no novo modo de gráficos deletegcf t0032pi zsintcost xxyyzzgenfac3dttz plot3dxx xxyy yylistzz zz44ones1400 5ones1400 egce fedata TL tlist3d x y z colorfxfyfz6randfz matriz de cores aleatória edata TL TL2 tlist3d x y z colorfxfyfz4rand1800 vetor de cores aleatório edata TL2 TL3 tlist3d x y z colorfxfyfz20ones1400 6ones1400 edata TL3 TL4 tlist3d x y zfxfyfz nenhuma cor edata TL4 ecolorflag1 índice de cor proporcional à altitude coordenada z ecolorflag2 de volta ao modo padrão ecolorflag 3 modo de gradação interpolada baseada na cor azul padrão clf plot3dxx xxyy yylistzz zz44ones1400 5ones1400 hgce obtendo manipulador da entidade corrente aqui é a superfície agca obtendo eixos correntes arotationangles4070 agrid1 1 1 criando grides adatabounds601665 aaxesvisibleoff os eixo estão escondidos aaxesbounds2 0 1 1 hcolorflag1 colorindo de acordo com z hcolormode2 removendo as bordas das facetas ajustando colormode para a cor branca hcolorflag2 colorindo de acordo com as cores fornecidas hcolormode 1 colocando de volta as bordas das facetas ajustando colormode de volta para preto fgcfobtendo o manipulador da figura raiz fcolormaphotcolormap512 c14001400 TLcolor cc1c2c3 hdata TL hcolorflag3 modo de gradação interpolada We can use the plot3d function to plot a set of patches triangular quadrangular etc The plot3d function to draw patches plot3d 732 patchxyz patchxylistzc The size of x number of points in the patches x number of patches y and z have the same sizes as x c a vector of size number of patches the color of the patches a matrix of size number of points in the patches x number of patches the color of each points of each patches Example 1 a set of triangular patches x 0 0 0 1 1 1 y 1 1 2 2 2 1 z 1 1 1 1 1 1 tcolor 2 3 subplot221 plot3dxylistztcolor xtitleA triangle set of patches Example 2 a mixture of triangular and quadrangular patches xquad 5 0 100 155 105 yquad 150 2010 1515 105 zquad ones42 xtri 01010 5 0 102020 5 0 2020151010 ytri 01020 510 1020201520 0 0151020 ztri zeros35 subplot223 plot3dxquadyquadzquad plot3dxtriytriztri xtitleMixing triangle and quadrangle set of patches plot3d 733 Example 3 some rabbits rabxtri 5 5 25 75 10 5 15 5 10 10 15 15 5 10 15 rabytri 10 10 95 25 0 20 10 12 5 5 10 0 7 0 0 rabztri 00000 00000 00000 rabtricolorbyface 2 2 2 2 2 rabtricolor 22222 33333 44444 rabxquad 0 1 0 6 511 5 6 rabyquad 1823 2328 2328 1823 rabzquad 11 11 11 11 rabquadcolorbyface 2 2 rabquadcolor 22 33 44 55 subplot222 plot3drabxtri rabytri listrabztrirabtricolor plot3drabxquadrabyquadlistrabzquadrabquadcolor h gcf hchildren1background 1 xtitleA psychedelic rabbit set of patches subplot224 plot3drabxtri rabytri listrabztrirabtricolorbyface plot3drabxquadrabyquadlistrabzquadrabquadcolorbyface h gcf hchildren1background 1 xtitleA standard rabbit set of patches The result of the preceding example plot3d 734 We can also use the plot3d function to plot a set of patches using vertex and faces Vertex Faces example 3D example The vertex list contains the list of unique points composing each patch The points common to 2 patches are not repeated in the vertex list vertex 0 1 1 0 2 2 1 2 3 1 1 4 The face list indicates which points are composing the patch face 1 2 3 1 3 4 tcolor 2 3 plot3d 735 The formula used to translate the vertex face representation into x y z lists xvf matrixvertexface1sizeface1lengthvertexface1sizeface1 yvf matrixvertexface2sizeface1lengthvertexface1sizeface1 zvf matrixvertexface3sizeface1lengthvertexface1sizeface1 scf subplot211 plot3dxvfyvflistzvftcolor xtitleA triangle set of patches vertex face mode 3d 2D test We use the 3D representation with a 0 Z values and then switch to 2D representation Vertex Faces example 3D example The vertex list contains the list of unique points composing each patch The points common to 2 patches are not repeated in the vertex list vertex 0 1 0 2 1 2 1 1 The face list indicates which points are composing the patch face 1 2 3 1 3 4 The formula used to translate the vertex face representation into x y z lists xvf matrixvertexface1sizeface1lengthvertexface1sizeface1 yvf matrixvertexface2sizeface1lengthvertexface1sizeface1 zvf matrixzerosvertexface2sizeface1lengthvertexface1sizeface1 subplot212 plot3dxvfyvflistzvftcolor xtitleA triangle set of patches vertex face mode 2D a gca aview 2d The result of the preceding example plot3d 736 How to set manually some ticks plot3d h gca hxticks tlisttickslocationslabels2101221012 hyticks tlisttickslocationslabels432101234432101234 hzticks tlisttickslocationslabels101Point 1Point 2Point 3 Ver Também eval3dp genfac3d geom3d param3d plot3d1 clf gca gcf xdel delete axesproperties Autor JPhC 737 Name plot3d1 Esboço 3d em níveis de cinza ou de cores de uma superfície plot3d1xyzthetaalphalegflagebox plot3d1xfyfzfthetaalphalegflagebox plot3d1xyzoptsargs plot3d1xfyfzfoptsargs Parâmetros xy vetores linhas de tamanhos n1 e n2 coordenadas dos eixos x e y Estas coordenadas devem ser monótonas z matriz de tamanho n1n2 zij é o valor da superfície no ponto xiyj xfyfzf matrizes de tamanho nfn Elas definem as facetas usadas para desenhar a superfície Há n fac etas Cada faceta i é definida por um polígono com nf pontos As coordenadas dos eixos x y e z dos pontos da iésima faceta são dados respectivamente por xfi yfi e zfi optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 pode ser um dos seguintes theta alpha leg flag ebox ver definições abaixo theta alpha valores reais de dados em graus as coordenadas esféricas do ponto de observação leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho três flagmodetypebox mode um inteiro cor da superfície mode0 a superfície é pintada com a cor mode a borda da faceta é desenhada com o estilo e linha e cor correntes mode0 uma malha da superfície é desenhada mode0 a superfície é pintada com a cor mode a borda da faceta não é desenhada Note que o tratamento de cor da superfície pode ser feito utilizandose as opções colormode e colorflag através das propriedades da entidade Surface ver surfaceproperties type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 plot3d1 738 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das propriedades da entidade Axes ver axesproperties box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos pode ser customizado através das propriedades da entidade Axes ver axesproperties ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag é ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds que também pode ser ajustado através das propriedades da entidade de eixos ver axesproperties Descrição plot3d1 esboça uma superfície com cores dependendo do nível z da superfície Esta função de esboço especial também pode ser habilitada ajustando colorflag1 após um plot3d ver surfaceproperties plot3d1 739 Entre com o comando plot3d1 para visualizar uma demonstração Exemplos esboço simples utilizando zfxy t0032pi zsintcost plot3d1ttz mesmo esboço utilizando facetas computadas por genfac3d xxyyzzgenfac3dttz clf plot3d1xxyyzz esboços múltiplos clf plot3d1xx xxyy yyzz 4zz esboço simples com ponto de vista e legendas clf plot3d111012010rand10203545XYZ223 mesmo esboço sem grid clf plot3d111012010rand10203545XYZ223 esboço de uma esfera utilizando facetas computadas por eval3dp deffxyzsphalptetxrcosalpcostetorig1onestet yrcosalpsintetorig2onestet zrsinalporig3onestet r1 orig0 0 0 xxyyzzeval3dpsphlinspacepi2pi240linspace0pi220 clf plot3dxxyyzz egce ecolorflag1 scf2 plot3d1xxyyzz os dois gráficos são similares Ver Também plot3d gca gce scf clf Autor JPhC 740 Name plot3d2 Esboço de superfície definida por facetas retangulares plot3d2XYZ vectthetaalphalegflagebox plot3d2XYZ optargs Parâmetros X Y Z três matrizes de reais definindo uma estrutura de dados vect vetor de reais optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes theta alpha legflagebox ver definições abaixo theta alpha valores reais de dados em graus as coordenadas esféricas do ponto de observação leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho três flagmodetypebox mode um inteiro cor da superfície mode0 a superfície é pintada com a cor mode a borda da faceta é desenhada com os estilos correntes de linha e cor mode0 uma malha da superfície é desenhada mode0 a superfície é pintada com a cor mode a borda da faceta não é desenhada Note que o tratamento de cor da superfície pode ser feito utilizandose as opções colormode e colorflag através das propriedades da entidade superfície ver surfaceproperties type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos plot3d2 741 type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das propriedades da entidade Axes ver axesproperties box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos pode ser customizado através das propriedades da entidade Axes ver axesproperties ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag se for ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds que também pode ser ajustado através das propriedades da entidade Axes ver axesproperties Descrição plot3d2 esboça uma superfície definida por facetas retangulares XYZ são três matrizes que descrevem uma superfície A superfície é composta de polígonos de quatro lados As coordenadas x de uma faceta são dadas por XijXi1jXij1Xi1j1 De modo semel hante Y e Z são coordenadas Y e Z O vetor vect é usado quando múltiplas superfícies são codificadas nas mesmas matrizes XYZ vectj fornece a linha na qual a codificação da jésima superfície começa Como em plot3d as mesmas propriedades são editáveis ver surfaceproperties e axesproperties plot3d2 742 Exemplos u linspacepi2pi240 v linspace02pi20 X cosucosv Y cosusinv Z sinuonesv plot3d2XYZ apenas no novo modo de gráficos egce ecolormode4 mudando a cor fedata TL tlist3d x y z colorfxfyfz10fz1 edataTL ecolorflag2 Ver Também plot3d genfac3d 743 Name plot3d3 Esboço de malha de uma superfície definida por facetas retangulares plot3d3XYZ vectthetaalphalegflagebox plot3d3XYZ optargs Parâmetros X Y Z 3 três matrizes de reais definindo uma estrutura de dados vect vetor de reais optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes theta alpha legflagebox ver definições abaixo theta alpha valores reais de dados em graus as coordenadas esféricas do ponto de observação leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho quatro flagverticalcolor horizontalcolortypebox verticalcolor um inteiro cor da superfície o padrão é 3 Índice do mapa de cores definindo a cor a ser utilizada para se desenhar as bordas verticais horizontalcolor um inteiro cor da superfície o padrão é 4 Índice do mapa de cores definindo a cor a ser utilizada para se desenhar as bordas horizontais type um inteiro escala o padrão é 2 type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 plot3d3 744 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das propriedades da entidade de eixos ver axesproperties box um inteiro moldura ao redor do esboço o padrão é 4 box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos pode ser customizado através das propriedades da entidade Axes ver axesproperties ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax TEste argumento é utilizado junto com type em flag se for ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds que também pode ser ajustado através das propriedades da entidade Axes ver axesproperties Descrição plot3d3 realiza um esboço de malha de uma superfície definida por facetas retangulares XYZ são três matrizes que descrevem uma superfície A superfície é composta por polígonos de quatro lados As coordenadas X de uma faceta são dadas por XijXi1jXij1Xi1j1 De modo semel hante Y e Z são coordenadas Y e Z O vetor vect é usado quando múltiplas superfícies são codificadas nas mesmas matrizes XYZ vectj fornece a linha na qual a codificação da jésima superfície começa Ver plot3d2 para uma descrição completa Como um esboço de malha a única propriedade disponível que você pode editar é a opção visible ver axesproperties Exemplos u linspacepi2pi240 v linspace02pi20 X cosucosv plot3d3 745 Y cosusinv Z sinuonesv plot3d3XYZ apenas no novo modo de gráficos egce obtendo a entidade corrente evisibleoff evisibleon de volta à visão da malha Ver Também plot3d2 plot3d param3d 746 Name plotframe esboça uma moldura com escalas e grides Esta função está obsoleta plotframerectticsargopt1argopt2argopt3 plotframerectoptsargs Parameters rect vetor xminyminxmaxymax tics vetor nxmxnymy onde mx nx resp my ny são o número de intervalos e subinter valos do eixo x resp eixo y argoptX até três argumentos opcionais escolhidos entre flags vetor wantgridsfindbounds onde wantgrids é uma variável booleana t ou f que indica o gridding findbounds é uma variável booleana Se findbounds for t os limites dados em rect podem ser ligeiramente modificados na verdade sempre au mentados a fim de se obter graduações mais simples então tics2 e tics4 são ig norados Captions vetor de três strings titlexlegyleg correspondentes respectivamente ao título do esboço e às legendas dos eixos x e y Aviso o C maiúsculo é importante subwin um vetor de tamanho 4 definindo a subjanela A subjanela é especificada através do parâmetro subwinxywh ponto superior esquerdo largura altura Os valores em subwin são especificados utilizandose a proporção de largura ou altura da janela de gráficos corrente ver xsetech optsargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 po dem ser um dos seguintes tics flags captions ou subwin Estes argumentos têm o mesmo sig nificado que aqueles utilizados na primeira forma da rotina Descrição plotframe é utilizado com funções de esboço 2d plot2d plot2d1 para ajustar uma moldura gráfica Deve ser usado antes de plot2d que deve ser chamado com o modo de superposição 000 Esta função está obsoleta Exemplos x0308273 yrandx rectminxminymaxxmaxy tics41025 4 xintervalos e 2 yintervalos plotframerectticsffMeu esboçoxy000505 plot2dxy2000 plotframerectticsticsflagstfCaptionsMeu esboço com gridesxysubwin0500505 plotframe 747 plot2dxy3000 plotframerectticstt Meu esboço com grides e fronteiras automáticasxy0050505 plot2dxy4000 plotframerectflagsftticstics CaptionsMeu esboço sem grides mas com fronteiras automáticas xy subwin05050505 plot2dxy5000 Ver Também plot2d graduate xsetech 748 Name plzr Esboço de pólozero plzrsl Parâmetros sl lista syslin Descrição Produz um esboço de pólozero do sistema linear sl lista syslin Exemplos spoly0s n1s 23s4s2 5 0 1s s d13s 5s3 s11s 1ss2 3s1 hsyslincnd plzrh Ver Também trzeros roots syslin 749 Name polarplot Esboço de coordenadas polares polarplotthetarhostylestrflegrect polarplotthetarhooptargs Parâmetros rho vetor valores dos raio theta vetor de mesmo tamanho que rho valores dos ângulos optargs uma seqüência de declarações key1value1 key2value2 onde keys podem ser stylelegrectstrf ou frameflag style vetor de reais de tamanho nc O estilo a ser usado pela curva i é definido por stylei O valor padrão é 1nc 1 para a primeira curva 2 para a segunda etc Se stylei for negativo a curva é esboçada utilizandose a marca com idenfiticador absstylei1 use xset para ver os identificadores das marcas Se stylei for estritamente positivo uma linha simples com identificador de cor stylei ou linha tracejada com identificador de estilo de tracejado stylei é usada use xset para ver os identificadores de cor Quando apenas uma curva é desenhada style pode ser um vetor linha de tamanho 2 stypos onde sty é utilizado para se especificar o estilo e pos é um inteiro entre 1 e 6 que especifica a posição para a legenda Isto pode ser útil quando o usuário deseja desenhar curvas múltiplas em um esboço chamando a função plot2d várias vezes e quer fornecer uma legenda para cada curva strf istring de comprimento 3 xy0 default o padrão é 030 x controla a exibição de legendas x0 sem legendas x1 com legendas Elas são fornecidas pelo argumento opcional leg y controla a computação da moldura É o mesmo que frameflag y0 as fronteiras correntes definidas por uma chamada anterior a uma função de esboço de altonível são utilizadas Útil ao se superpor esboços múltiplos polarplot 750 y1 o argumento opcional rect é utilizado para se especificar as fronteiras do esboço y2 as fronteiras do esboço são computadas utilizandose os valores mínimo e máximo de x e y y3 como y1 mas produz escala de isovisualização y4 como y2 mas produz escala de isovisualização y5 como y1 mas plot2d pode mudar as fronteiras do esboço e os tiques dos eixos para se obter boas graduações Quando o botão de zoom é ativado este modo é usado y6 como y2 mas plot2d pode mudar as fronteiras do esboço e os tiques dos eixos para se obter boas graduações Quando o botão de zoom é ativado este modo é usado y7 como y5 mas a escala do novo esboço é misturada à escala corrente y8 como y6 mas a escala do novo esboço é misturada à escala corrente leg string É usado quando o primeiro caractere x do argumento strf é 1 leg possui a forma leg1leg2 onde leg1 leg2 etc são respectivamente as legendas das primeira segunda etc curvas O padrão é rect é usado quando o segundo caractere y do argumento strf é 1 3 ou 5 É um vetor linha de tamanho 4 e fornece as dimensões da moldura rectxminyminxmaxymax Descrição polarplot cria um esboço de coordenadas polares do ângulo theta versus o raio rho theta é o ângulo do eixo x ao vetor raio especificado em radianos rho é o comprimento do vetor raio especificado em unidades de espaçodedados Exemplos t 0012pi clfpolarplotsin7tcos8t clfpolarplotsin7t sin6tcos8t cos8t12 751 Name polylineproperties Descrição das propriedades da entidade Polyline poligonal Descrição A entidade Polyline uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para poligonais parent esta propriedade contém o manipulador para a raiz A raiz de uma entidade Polyline deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores polig onais não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão a poligonal é visível o valor da propriedade é on Se off a poligonal não é impressa na tela data esta propriedade contém o valor os valores para as coordenadas x e y O componente z deve ser adicionado no caso de eixos 3d é uma matriz de duas três colunas xyz determinando os pontos closed este valor determina se a poligonal é fechada ou não o valor pode ser on ou off o valor padrão depende da primitiva utilizada para criar a poligonal linemode este campo contém o valor padrão da propriedade linemode para a poligonal O valor pode ser on linha desenhada ou off nenhuma linha desenhada fillmode se o campo polylinestyle é diferente de 5 preenche o plano de fundo da curva com a cor definida pela propriedade background linestyle o valor da propriedade linestyle deve ser um inteiro em 1 6 1 significa linha sólida e os demais valores tipos diferentes de tracejados ver getlinestyle thickness este campo contém a propriedade de linha thickness espessura Deve ser um inteiro positivo arrowsizefactor este inteiro permite ajustar o tamanho das flechas desenhadas na poligonal O tamanho real das flechas é o produto entre a propriedade thickness e o fator de tamanho size factor polylinestyle esta propriedade ajusta vários modos de desenho de poligonais Se o valor é 0 ou 1 linhas são desenhadas utilizandose dois pontos consecutivos Se o valor é 2 a poligonal produz um esboço escada Dois pontos consecutivos são ligados por uma linha horizontal seguida de uma vertical Se o valor é 3 a poligonal produz um esboço de barras Para cada ponto xy dado uma linha vertical é desenhada de xy a x0 polylineproperties 752 Se o valor é 4 flechas são desenhadas entre dois pontos consecutivos Se o valor é 5 a poligonal é preenchida remendos Se o valor é 6 a poligonal é um objeto barra como no Matlab As propriedades barshift e barwidth comandam sua aparência foreground este campo contém o valor padrão da propriedade foreground primeiro plano utilizada para desenhar a poligonal O valor deve ser um índice de cor realtivo ao mapa de cores corrente background este campo contém a cor usada para preencher o plano de fundo da poligonal Deve ser um índice de cor relativo ao mapa de cores corrente interpcolorvector este campo contém os índices das cores utilizadas para preencher a poligonal quando a pro priedade interpcolormode é ajustada para on Define os intervalos dos índices do ma pa de cores a serem utilizados para preencher cada segmento Por exemplo o primeiro segmento será preenchido por todas as cores cujo índice está entre os dois primeiros elementos do vetor Só é aplicável se a poligonal é definida por 3 ou 4 pontos Logo o tamanho do vetor deve coincidir com esta dimensão interpcolormode este modo determina se é utilizada gradação interpolada par preencher a poligonal o valor pode ser on ou off Note que interpcolorvector deve ser definido antes e ajustar esta propriedade para on ver acima markmode este campo contém o valor padrão da propriedade markmode Deve ser on marcas desen hadas ou off nenhuma marca desenhada markstyle A propriedade markstyle é utilizada para selecionar o tipo de marca utilizada quando a pro priedade markmode é on O valor é um inteiro em 0 14 que significa ponto sinal de mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo rombo mais círculo asterísco quadrado triângulo para direita triângulo para esquerda e pentagrama marksizeunit este campo contém o valor padrão da propriedade marksizeunit property value Se marksizeunit for ajustado para point então o valor de marksize é diretamente dado em pontos Quando marksizeunit é ajustado para tabulated marksize é computado em relação ao array de tamanho de fonte logo seu valor deve ser um inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que plot2d e funções puras do Scilab utilizam o modo tabulated como padrão quando se utiliza a função plot o modo point é automaticamente habilitado marksize a propriedade marksize é utilizada para selecionar o tipo de tamanho das marcas quando a propriedade markmode é on O valor deve ser um inteiro entre 0 e 5 signficando 8pt 10pt 12pt 14pt 18pt e 24pt markforeground este campo contém o valor da propriedade markforeground que é a cor da borda das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor da propriedade markbackground que é a cor da face das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente polylineproperties 753 xshift este campo contém a compensação computada por uma chamada à função bar ou recomputa da por uma chamada à função barhomogenize e é usada para realizar uma boa representação de barras verticais Note que esta compensação é levada em conta para todos os outros polylinestyle A unidade é expressa nas coordenadas do usuário yshift este campo contém a compensação computada por uma chamada à função bar ou recomputa da por uma chamada à função barhomogenize e é usada para realizar uma boa representação de barras verticais Note que esta compensação é levada em conta para todos os outros polylinestyle TA unidade é expressa nas coordenadas do usuário zshift este campo contém a compensação que o usuário pode especificar Note que esta compensação é levada em conta para todos os polylinestyle A unidade é expressa nas coordenadas do usuário barwidth este campo determina a largura da poligonal selecionada quando sua propriedade polylinestyle é ajustada para modo de barra caso 6 a unidade é expressa nas coorde nadas do usuário clipstate este campo contém o valor da propriedade clipstate para a poligonal O valor de clipstate pode ser off significa que a poligonal não é recortada clipgrf significa que a poligonal é recortada fora da caixa dos eixos on significa que a poligonal é recortada fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções da poligonal a serem exibidas contudo o valor da propriedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade poligonal e recuperála Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds2222 xpolysin2pi055cos2pi055lines0 pgethdl obtendo o manipulador da entidade corrente aqui é a entidade poligonal pforeground2 pthickness3 pmarkstyle9 dpdatad10 0pdatad arotationangles0 45 pdata2012 sin2012pi pmarkmodeoff ppolylinestyle3 polylineproperties 754 plinestyle4 Ver Também set get delete xpoly xfpoly xpolys xfpolys graphicsentities Autor Djalel ABDEMOUCHE 755 Name rainbowcolormap Mapa de cores que varia como um de arcoíris cmaprainbowcolormapn Parâmetros n inteiro 1 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição rainbowcolormap computa um mapa de cores com n cores variando como um arcoíris Exemplos f scf plot3d1 fcolormap rainbowcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap springcolormap summercolormap whitecolormap wintercolormap 756 Name rectangleproperties Descrição de propriedades da entidade Rectangle retângulo Descrição A entidade Rectangle é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para retângulos preenchidos ou não parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Rectangle deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores rect angle não possuem galhos correntemente markmode este campo contém o valor padrão da propriedade markmode para a poligonal Deve ser on marcas desenhadas ou off nenhuma marca desenhada markstyle a propriedade markstyle é utilizada para selecionar o tipo de marca utilizada quando a pro priedade markmode é on O valor é um inteiro em 0 14 que significa ponto sinal de mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo rombo mais círculo asterísco quadrado triângulo para direita triângulo para esquerda e pentagrama marksizeunit este campo contém o valor padrão da propriedade marksizeunit property value Se marksizeunit for ajustado para point então o valor de marksize é diretamente dado em pontos Quando marksizeunit é ajustado para tabulated marksize é computado em relação ao array de tamanho de fonte logo seu valor deve ser um inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que xrect como padrão quando se utiliza a função tabulated como padrão quando se utiliza a função plot o modo point é automati camente habilitado marksize A propriedade marksize é utilizada para escolher o tamanho das marcas quando a propriedade markmode é on Deve ser um valor inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt markforeground este campo contém o valor da propriedade markforeground que é a cor da borda das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor da propriedade markbackground que é a cor da face das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente linemode este campo contém o valor padrão da propriedade linemode para a poligonal O valor pode ser on linha desenhada ou off nenhuma linha desenhada fillmode Se o valor da propriedade fillmode é on o retângulo é preenchido com a cor de primeiro plano markmode também deve ter valor off Senão o valor da propriedade é off apenas a forma o contorno do retângulo é desenhado utilizandose a cor de primeiro plano linestyle a propriedade linestyle deve ser um inteiro em 1 6 1 stands significa linha sólida o restante seleciona tracejados rectangleproperties 757 thickness este campo contém o valor padrão da propriedade thickness espessura da linha Deve ser um inteiro positivo foreground este campo contém a cor utilizada para desenhar a linha de contorno do retângulo Seu valor deve ser um índice de cor relativo ao mapa de cores corrente background este campo contém a cor utilizada para preencher a parte interna do retângulo Seu valor deve ser um índice de cor relativo ao mapa de cores corrente data esta propriedade retorna as coordenadas do ponto superior esquerdo do retângulo sua al tura e largura em unidades de dados dos eixos O resultado é uma matriz xleftyup zupwidthheight visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o retângulo é visível a propriedade é on Se off o retângulo não é exibido na tela clipstate este campo contém o valor da propriedade clipstate para o retângulo o valor de clipstate pode ser off ignifica que o retângulo não é recortado clipgrf significa que o retângulo é recortado fora da caixa dos eixos on significa que o retângulo é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox property Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções do retângulo a ser exibido contudo o valor da pro priedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade retângulo e recuperála Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds2222 xrect1122 rgethdlobtendo o manipulador da entidade corrente aqui a entidade Rectangle rtype rparenttype rforeground13 rlinestyle2 rfillmodeon rbackgroundcolorred rclipbox1 11 1 rdata3 412 12 rectangleproperties 758 rdata1 212 12 rclipstateoff Ver Também set get delete xrect xfrect xrects graphicsentities Autor Djalel ABDEMOUCHE 759 Name relocatehandle Movimentação de manipuladores dentro da hierarquia gráfica relocatehandle movedHandles parent Parâmetros movedHandles vetor de manipuladores realocados parent nova raiz dos manipuladores Descrição A função relocatehandle permite mover manipuladores das suas localizações em uma hierarquia gráfica para outra localização Todas as entidades são realocadas sob o mesmo manipulador raiz es pecificado pelo parâmetro parent Já que não são todos os manipuladores que são compatíveis com todos os outros existem algu mas restrições ao se realocar manipuladores Por exemplo não é permitido mover um manipulador Axes sob um manipulador Polyline Para mais informações sobre compatibilidade veja a página graphicsentities Esta rotina é particularmente útil para se mover um objeto de uma entidade Axes para outra ou para se move objetos Axes de uma entidade Figure para outra Exemplos x 010 esboçando uma primeira poligonal plotxx2 axes1 gca poly1 gce esboçando uma segunda em outra janela scf plot xx axes2 gca poly2 gce poly2bis copy poly2 criando uma cópia da poligonal pondo ambas as poligonais na mesma janela relocatehandle poly2bis axes1 Ver Também graphicsentities copy delete swaphandles Autor JeanBaptiste Silvy 760 Name replot redesenha a janela de gráficos corrente com novas fronteiras replotrecthandle Parâmetros rect vetor linha de tamanho 4 handle argumento opcional Manipuladores do tipo Axes para selecionar uma ou várias entidades Axes válidas Disponível apenas no novo modo de gráficos Descrição replot é utilizado para redesenhar o conteúdo da janela de gráficos atual com novas fronteiras definidas por rectxminyminxmaxymax Sob a sintaxe de gráficos antiga funciona ape nas com o driver Rec Sob o novo modo de gráficos esta transformação pode ser aplicada a eixos específicos fornecidos por manipuladores gráficos Axes via o argumento handle Se handle não for especificado as novas fronteiras são aplicadas aos eixos correntes da figura corrente A transformação muda os valores de databounds para estes eixos Note que a propriedade de eixos tightlimits também deve ser ajustada para on para selecionar estritamente estas fronteiras ver axesproperties Exemplos backupstyle primeiro exemplo x0012pi plot2dxsinx replot11102 segundo exemplo xdelwinsid plot esboçando demonstração fgcf replot11102fchildren1 especificando o valor do manipulador dos eixos replot3284fchildren2 Ver Também xbasr xbasc clf Autor JPhC 761 Name rgb2name Retorna o nome de uma cor namesrgb2namergb namesrgb2namergb Parâmetros rgb RGB vermelho verde azul valores inteiros de uma cor rgb vetor RGB de valores inteiros de uma cor names nomes da cor Descrição rgb2name retorna o nome da cor correspondente aos valores RGB dados pelo seu argumento Um vetor de nomes de cores pode ser retornado se a cor possui mais de um nome r g e b devem ser inteiros entre 0 e 255 correspondentes aos componentes das cores vermelho verde e azul Como de uso 0 significa intensidade nenhuma e 255 significa intensidade total da cor Os valores RGB também podem ser fornecidos pelo vetor rgb Se não for encontrada nenhuma cor é retornado A lista de todas as cores conhecidas é dada por colorlist Exemplos rgb2name255128128 rgb2name255 215 0 retorna a cor de número 10 do mapa de cores corrente acha seu nome cmapgetgcfcolormap rgb2namecmap10255 Ver Também color colorlist name2rgb 762 Name rotate rotação de um conjunto de pontos xy1rotatexythetaorig Parâmetros xy matriz de tamanho 2 xy1 matriz de tamanho 2 theta real ângulo em radianos o valor padrão é 0 orig centro de rotação o valor padrão é 00 Descrição rotate executa a rotação com o ângulo theta xy1i Mtheta xy i orig onde M é a matriz de rotação correspondente Exemplos xsetech00111111 xy00110sin0011010 for i2pi01010 xy1rotatexyi xpolyxy11xy12lines end 763 Name rotateaxes Rotação interativa de um manipulador Axes rotateaxes rotateaxesh Parâmetros h manipulador Axes ou Figure Especifica sobre qual eixo se efetuará a rotação Descrição rotateaxes é utilizado para realizar uma rotação interativa sobre um objeto Axes Quando a função é chamada pedese ao usuário que clique duas vezes na janela gráfica O primeiro clique inicializa uma rotação e o segundo termina Se um manipulador Axes for especificado como argumento de entrada a rotação será aplicada sobre ele Se um manipulador Figure for especificado o primeiro clique determina qual objeto Axes rota cionar Se a função for chamada sem argumento a rotação se aplicará sobre a Figura corrente Exemplos clf criando dois pares de eixos em uma figura subplot2 1 1 plot2d subplot2 1 2 plot3d girando apenas o segundo axes2 gca rotateaxesaxes2 girando o selecionado rotateaxes ou rotateaxesgcf Ver Também zoomrect axesproperties Autor JeanBaptiste Silvy INRIA 764 Name rubberbox Caixa tipo liga de borracha para seleção de um retângulo finalrectbtnrubberbox finalrectbtnrubberboxinitialrect finalrectbtnrubberboxeditionmode finalrectbtnrubberboxinitialrect editionmode Parâmetros initialrect vetor de duas a quatro entradas Com quatro entradas fornece o retângulo inicial definido por xesquerdo ytopo largura altura Com duas entradas largura e altura são supostas 0 editionmode um booleano se editionmodet um aperto de botão seleciona a primeira quina soltar se leciona a quina oposta Se editionmode f aperto de botão ou clique seleciona a primeira quina um clique é requerido para selecionar a quina oposta O valor padrão é editionmodef finalrect um retângulo definido por xesquerdo ytopo largura altura btn um inteiro o número do botão do mouse clicado Descrição rubberboxinitialrect trilha uma caixa liga de borracha na janela de gráficos corrente seguindo o mouse Quando um botão é clicado rubberbox retorna a definição dos retângulos finais finalRect Se o argumento initialrect estiver presente o usuário deve clicar para fixar a posição da quina inicial Exemplos xsetechfrect00100100 xyxclickrrubberboxxy3010 xrectr rrubberbox Ver Também xrect xrects xclick xgetmouse dragrect 765 Name sca Ajusta a entidade de eixos corrente ascaa Parâmetros a o manipulador da entidade Axes de eixos Descrição scaa é usado para ajustar a entidade Axes corrente ver graphicsentities como sendo aquela apontada pelo manipulador a As funções de esboço geralmente utilizam a entidade de eixos corrente Exemplos clf a1newaxes a1axesbounds001005 t00120 plottacoshtr a2newaxes a2axesbounds0051005 x0014 plotxsinhx scaa1 tornando os primeiros eixos correntes plottasinhtg legendacoshasinh scaa2 tornando os segundos eixos correntes legendsinh Ver Também subplot gda newaxes Autor S Steer INRIA 766 Name scaling transformação afim de um conjunto de pontos xy1scalingxyfactororig Parâmetros xy1 matriz de tamanho 2 xy matriz de tamanho 2 factor escalar real coeficiente da transformação linear orig vetor de deslocamento o valor padrão é 00 Descrição scaling executa uma transformação afim de um conjunto de pontos definidos pelas coordenadas xy xy1i factor xyi orig 767 Name scf Ajusta a janela de figura gráfica corrente f scf f scfh f scfnum Parâmetros h o manipulador da figura num identificador da figura f manipulador da figura corrente Descrição A figura corrente é o destino do desenho gráfico A função scf permite modificar esta figura corrente ou criar uma caso ainda não exista scfnum ajusta a figura com figureidnum como figura corrente Se ainda não existir ela é criada scfh ajusta a figura apontada pelo manipulador h ajusta a figura apontada pelo manipulador scf é equivalente a scfmaxwinsid1 Pode ser utilizado para criar uma nova janela de gráficos Exemplos f4scf4 criando figura com id4 e a torna a figura corrente f0scf0 criando figura com id0 e a torna a figura corrente plot2d desenhando na figura corrente id0 scff4 ajustando a primeira figura criada como sendo a corrente plot3d desenhando na figura corrente id4 Ver Também set get gcf clf getfigurehandle graphicsentities Autor S Steer INRIA 768 Name sd2sci estrutura grmenu para conversor de instrução Scilab txtsd2scisd sz orig Parâmetros sd estrutura de dados construída por grmenu sz vetor de números ou strings com dois componentes fornece os fatores de zoom x e y orig vetor de números ou strings fornece o vetor translação da origem Descrição Dada uma estrutura de dados sd gerada por grmenu sd2sci forma um vetor de instruções do Scilab correspondente ao gráfico editado por grmenu Os parâmetros opcionais sz e orig permitem ampliar e deslocar o gráfico inicial Se sz ou orig são fornecidos por strings as instruções geradas são relativas a expressões formais Ver Também execstr Autor Serge Steer INRIA 1988 769 Name sda Ajusta eixos padrões sda a gda setadefaultvalues1 Parâmetros a manipulador dos eixos padrões Descrição Esta rotina reajusta o os eixos modelos para valores padrões Exemplos x0012pi fgetdefaultfigure obtendo o manipulador da figura modelo agetdefaultaxes obtendo o manipulador dos eixos modelo ajustando suas propriedades ffiguresize1200 900 ffigureposition0 0 abackground4 aboxoff a ticscolor5 alabelsfontcolor25 alabelsfontsize4 asubtics7 3 axlocationmiddle aylocationmiddle atightlimitson athickness2 agrid1 24 subplot221 plot2dx2sinx subplot222 plot2dx62cosx7 2cosx9 cos2x 2sin3x123 4 sda obtendo os valores padrões do modelo dos eixos subplot223 plot2dx2sinx subplot224 plot2dx62cosx7 2cosx9 cos2x 2sin3x123 4 xdel0 plot2dx2sinx Ver Também sdf gda gdf set graphicsentities Autor Djalel ABDEMOUCHE 770 Name sdf Ajusta figura padrão sdf f gdf setfdefaultvalues1 Parâmetros f manipulador da figura padrão Descrição Esta rotina reajusta a figura modelo para valores padrões Exemplos x0012pi fgetdefaultfigure obtendo o manipulador da figura modelo agetdefaultaxes obtendo o manipulador dos eixos modelos ajustando suas propriedades fbackground4 fautoresizeoff ffiguresize400 300 faxessize600 400 ffigureposition0 1 axlocationtop aylocationleft for i16 xsetwindowi criando figura com identificador i plot2dxsinx cosxi i xclick if i 4 sdf end obtendo os valores padrões da figura modelo end Ver Também sda gdf gda set graphicsentities Autor Djalel ABDEMOUCHE 771 Name secto3d Conversão de superfícies 3d mxsecto3dseclistnpas msecto3dseclist x Parâmetros seclist uma lista cujos elementos são matrizes 2 npas um inteiro m uma matriz x um vetor Descrição Considerando uma superfície dada através de uma lista seclist de secções no plano xz m xsecto3dseclist npas retorna uma matriz m que contém a discretização regular da superfície A iésima linha da matriz m corresponde à iésima secção A jésima coluna da matriz m corresponde ao xj Cada secção seclisti é descrita por uma matriz 2 que fornece respectivamente as coorde nadas x e z de pontos msecto3dseclist xneste caso o vetor x fornece a discretização do eixo x para todas as secções Ver Também plot3d Autor Steer S 772 Name segsproperties Descrição das propriedades da entidade Segments de segmentos Descrição A entidade Segments é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para um conjunto de segmentos ou setas coloridas parent esta propriedade contém o manipulador da raiz A raiz de uma entidade de Segments deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores Segs não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o os segmentos são visíveis a propriedade é on Se off os segmentos não são exibidos na tela data este campo é uma matriz de duas três xyz que fornece as coordenadas das extremi dades dos segmentos Se xvmatrixx21 e yvmatrixy21 então xvk e yvk são as extremidades dos segmentos de número k linemode este campo contém o valor padrão da propriedade linemode para os segmentos O valor pode ser on linha desenhada ou off nenhuma linha desenhada linestyle O valor da propriedade linestyle deve ser um inteiro em 0 6 0 significa linha sólida o restante seleciona tracejados Esta propriedade se aplica a todos os segmentos thickness este campo contém o valor da propriedade thickness espessura para todos os segmentos Seu valor deve ser um inteiro nãonegativo arrowsize fator que especifica o tamanho das cabeças das setas Com um valor negativo o tamanho também depende do comprimento da seta Para desenhar um segmento o valor deve ser ajustado para 0 segscolor este campo especifica a cor a ser utilizada para desenhar cada segmento Cada elemento é um índice de cor relativo ao mapa de cores corrente markmode este campo contém o valor padrão da propriedade markmode para a poligonal Deve ser on marcas desenhadas ou off nenhuma marca desenhada markstyle a propriedade markstyle é utilizada para selecionar o tipo de marca utilizada quando a pro priedade markmode é on O valor é um inteiro em 0 14 que significa ponto sinal de mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo rombo mais círculo asterísco quadrado triângulo para direita triângulo para esquerda e pentagrama marksizeunit este campo contém o valor padrão da propriedade marksizeunit Se marksizeunit for ajustado para point então o valor de marksize é diretamente dado em pontos Quando segsproperties 773 marksizeunit é ajustado para tabulated marksize é computado em relação ao array de tamanho de fonte logo seu valor deve ser um inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que plot2d e funções puras do Scilab utilizam o modo tabulated como padrão quando se utiliza a função plot o modo point é automaticamente habilitado marksize a propriedade marksize é utilizada para selecionar o tipo de tamanho das marcas quando a propriedade markmode é on O valor deve ser um inteiro entre 0 e 5 signficando 8pt 10pt 12pt 14pt 18pt e 24pt markforeground este campo contém o valor da propriedade markforeground que é a cor da borda das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor da propriedade markbackground que é a cor da face das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente clipstate este campo contém o valor da propriedade clipstate para os segmentos O valor de clipstate pode ser off significa que os segmentos não são recortados clipgrf significa que os segmentos são recortados fora da caixa dos eixos on significa que os sementos são recortada fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções dos segmentos a serem exibidas contudo o valor da propriedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade de segmentos e recuperála Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds10101010 x2pi078 xv2sinx9sinx yv2cosx9cosx xsegsxvyv18 sachildren sarrowsize1 ssegscolor1522 for j12 for i18 hsdatai2j sdatai2jsdatai21j sdatai21j h end end segsproperties 774 ssegscolor5 ajustando todas as cores para 5 sclipbox4488 athickness4 xrectsclipbox Ver Também set get delete xsegs graphicsentities Autor Djalel ABDMOUCHE 775 Name set Ajusta um valor de propriedade de uma objeto entidade gráfica ou de um objeto Interface do Usuário User Interface setpropval sethprop sethpropval hpropval Parâmetros h manipulador da entidade da qual a propriedade nomeada se deseja ajustar h pode ser um vetor de manipuladores em tal caso serão ajustados valores de propriedades para todos os objetos identificados por h prop string nome da propriedade a ser ajustada val valor a ser dado à propriedade Descrição Esta rotina pode ser utilizada para se recuperar o valor de uma propriedade especificada de uma en tidade de gráficos ou objeto GUI Neste caso é equivalente a se usar o operador ponto em um manipulador Por exemplo sethbackground5 é equivalente a hbackground 5 Nomes de propriedades são strings O tipo do valor ajustado dependo do tipo do manipulador e da propriedade Para obter a lista de todas as propriedade existentes ver graphicsentities ou uicontrol para objetos de Interface do Usuário set também pode ser chamado com apenas uma propriedade como argumento Neste caso a pro priedade deve ser uma das seguintes currententity or hdl setcurrententityh ou sethdlh ajusta uma nova entidade como a cor rente Neste caso o valor deve ser um manipulador gráfico currentfigure setcurrentfigurefig ajusta uma nova figura como a corrente É equivalente a scf Neste caso o valor deve ser um manipulador FIgure currentaxes setcurrentaxesaxes ajusta novos eixos como os correntes É equivalente a sca Neste caso o valor deve ser um manipulador Axes set também pode ser chamado com manipuladores gráficos e com propriedades como argumen tos O manipulador deve ser de uma figura padrão ou de eixos padrões A propriedade deve ser defaultvalues Neste caso a entidade padrão é reajustada para os valores que possuía na inicialização do Scilab setdefaultvaluesh equivale a sda ou sdf Exemplos set 776 clf setautoclearoff Exemple of a Plot 2D x2012pi plot2dx3sinx1 cos2x1 2 agetcurrentaxes p1achildrenchildren1 p2achildrenchildren2 ajustando as propriedades nomeadas para os valores especificados nos objetos setp2foreground13 setp2polylinestyle2 setatightlimitson setaboxoff setasubtics 7 0 setaylocationmiddle setp2thickness2 setp1markmodeon setp1markstyle3 plot2dx2x220 p3 achildren1children seta p1 p2 p3foreground5 Ver Também get delete copy move graphicsentities uicontrol Autor Djalel ABDEMOUCHE 777 Name seteventhandler Define um gerenciador de eventos para uma janela gráfica seteventhandlersfunname seteventhandler Parâmetros sfunname string O nome da função do Scilab com a qual se pretende gerenciar os eventos Descrição A função permite que o usuário defina um gerenciador de eventos particular para janela gráfica cor rente seteventhandler remove o gerenciador Para mais informações sobre o gerenciador de eventos veja a página event handler functions Exemplos function myeventhandlerwinxyibut if ibut1000 then returnend xyxchangexyi2f xinfomsprintfEvento de código d na posição do mouse é ffibutxy endfunction plot2d seteventhandlermyeventhandler agora mova o mouse sobre a janela gráfica pressione e libere as teclas com shift pressionado ou não e com Ctrl pressionado ou não pressione um botão espere um pouco e libere pressione e libere um botão clique duas vezes em um botão seteventhandler suprimindo o gerenciador de eventos Ver Também addmenu xgetmouse xclick xchange event handler functions figureproperties 778 Name showpixmap Envia o buffer de pixmap à tela showpixmap Descrição Se a propriedade pixmap de uma janela gráfica é on os desenhos são enviados à memória pixmap ao invés da tela de exibição A instrução showpixmap envia o pixmap à tela O modo pixmap pode ser usado para se obter animações suaves Esta propriedade pode ser encontrada entre os campos de entidades da figura ver figureproperties Exemplos fgcffpixmapon ajustando o modo pixmap agcaadatabounds0 0 10 10 construindo dois retângulos xrects010115r1gcer1r1children xrects011113r2gcer2r2children laço de animação for k11000 desenhando os retângulos no buffer pixmap mover1001001mover2001001 exibindo o buffer pixmap showpixmap end Ver Também figureproperties clearpixmap Autor Serge Steer INRIA 779 Name showwindow Restaura uma janela de gráficos showwindowfigure Parâmetros figure número ou manipulador da figura a ser exibida Descrição Sem parâmetros showwindow restaura a janela de gráficos corrente mesmo se estiver iconificada Em caso contrário restaura a janela especificada por seu número ou por seu manipulador Se nenhuma janela existir uma é criada Autor JPhC 780 Name springcolormap Mapa de cores com tons da primavera magenta amarelo cmapspringcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição springcolormap computa um mapa de cores com n cores variando de magenta a amarelo Exemplos f scf plot3d1 fcolormap springcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap summercol ormap whitecolormap wintercolormap 781 Name square ajusta escalas para esboço isométrico muda o tamanho da janela squarexminyminxmaxymax Parâmetros xminxmaxyminymax quatro valores reais Descrição square é usado para definir escalas isométricas nos eixos x e y Os valores requeridos xmin xmax ymin ymax são os limites da moldura de gráficos e square muda as dimensões da janela de gráficos para se obter um esboço isométrico square ajusta as escalas gráficas correntes e pode ser usado em conjunção com rotinas de gráfico que requerem a escala de gráficos corrente por exemplo fstrfx0z em plot2d Exemplos t0012pi plot2dsintcost xbasc square1111 plot2dsintcost xsetdefault Ver Também isoview xsetech Autor Steer S 782 Name stringbox Computa o retângulo de fronteira de um texto ou rótulo rect stringbox string x y angle fontStyle fontSize rect stringbox Handle Parâmetros rect uma matriz 2x4 contendo as quatro coordenadas dos vértices do retângulo de fronteira string matriz de strings a ser encerrada xy escalares reais coordenadas do ponto inferior esquerdo dos strings angle ângulo de rotação dos strings em sentido horário e em graus ao redor do ponto xy fonStyle inteiro especificando o tipo da fonte fontSize inteiro especificando o tamanho da fonte Handle um manipulador gráfico do tipo Text ou Label Descrição stringbox retorna os vértices de um retângulo de fronteira de um texto ou rótulo ou um string que será exibido de certo modo As coordenadas são dadas com a escala gráfica corrente O primeiro vértice corresponde às coordenadas do texto xy ponto superior esquerdo sem rotação os vértices seguintes são dados em sentido horário na matriz resultante O resultado pode ser impreciso com um driver Postscript Exemplos exibindo eixos axes gca axesaxesvisible on axesdatabounds 1 1 10 10 exibindo rótulos para eixos xtitle stringbox X Y obtendo a caixa de fronteixa do rótulo X stringbox axesxlabel imprimindo um string str Scilab não é Skylab xstring 4 9 str modificando o texto stringbox 783 e gce efontangle 90 efontsize 6 efontstyle 7 ebox on obtendo sua caixa de fronteira stringbox e ou rect stringbox str 4 9 90 7 6 clicando e descobrindo se o texto foi acertado hit xclick hit hit 2 3 if hit1 rect11 hit1 rect12 hit2 rect22 hit2 rect23 then dispVocê acertou o texto else dispVocê errou end Ver Também xstring xstringl xstringb Autor JeanBaptiste Silvy 784 Name subplot divide uma janela de gráficos em uma matriz de subjanelas subplotmnp subplotmnp Parâmetros mnp inteiros positivos mnp um inteiro com notação decimal mnp Descrição subplotmnp ou subplotmnp parte a janela de gráficos em uma matriz mporn de subjanelas e seleciona a pésima subjanela para esboçar o gráfico corrente O número uma subjanela nas matrizes é contado linha por linha ie a subjanela correspondente ao elemento ij da matriz tem número i1n j Exemplos subplot221 plot2d subplot222 plot3d subplot223 param3d subplot224 hist3d Ver Também plot2d plot3d xstring xtitle 785 Name summercolormap Mapa de cores com tons do verão verde amarelo cmapsummercolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição summercolormap computa um mapa de cores com n cores variando do verde para o amarelo Exemplos f scf plot3d1 fcolormap summercolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap whitecolormap wintercolormap 786 Name surf Esboço de superfície 3d surfZGlobalProperty surfZcolorGlobalProperty surfXYZcolorGlobalProperty surfaxeshandle Parâmetros Z uma matriz real definindo as alturas da superfície Não pode ser omitida O dado Z é uma matriz mxn XY dois vetores ou matrizes reais sempre ajustados juntos estes dados definem um novo grid padrão Estes novos componentes X e Y do grid devem coincidir com as dimensões de Z ver a descrição abaixo color um matriz de reais opcional definindo valores de cores para cada ponto XjYi do grid ver descrição abaixo GlobalProperty esta propriedade rerpresenta uma seqüência de pares de sentenças PropertyNamePropertyValue que definem propriedades globais de objetos apli cadas a todas as curvas criadas neste esboço Para uma completa visualização das propriedades disponíveis veja GlobalProperty axeshandle este argumento opcional força os eixos a aparecerem dentro dos eixos selecionados dados por axeshandle ao invés dos eixos correntes ver gca Descrição surf desenha uma superfície parametrizada colorida utilizando um grid retangular definido pelas coordenadas X e Y se XY não forem especificados este grid é determinado utilizandose as dimensões da matriz Z em cada ponto deste grid uma coordenada Z é dada utilizandose uma ma triz Z apenas dados obrigatórios surf foi criada para lidar melhor com a sintaxe do Matlab Para melhorar a compatibilidade gráfica usuários do Matlab devem utilizar surf ao invés de plot3d Especificação de entrada de dados Neste parágrafo e para sermos mais claros não mencionaremos os argumentos opcionais de Glob alProperty ojá que eles não interferem na entrada de dados exceto pelas propriedades Xdata Ydata e Zdata ver GlobalProperty É assumido que todos estes argumentos opcionais po dem estar presentes também Se Z é a única matriz especificada surfZ esboça a matriz Z versus o grid definido por 1sizeZ2 ao longo do eixo x e 1sizeZ1 ao longo do eixo Se uma tripla XYZ for fornecida Z deve ser uma matriz de sizeZ mxn X or Y can be a um vetor se X for um vetor lengthXn Respectivamente se Y for um vetor lengthYm b uma matriz neste caso sizeX ou sizeY deve ser igual a sizeZ Especificação de entrada de cores surf 787 Como citado acima a superfície é criada sobre um gride retangular de apoio Consideremos duas variáveis independentes i e j tais que Este grid retangular imaginário é utilizado para se contruir o suporte da superfície real sobre o plano XY De fato os dados XY e Z possuem o mesmo tamanho mesmo se X ou Y for um vetor ver abaixo e podem ser considerados como três funções xij yij e zij especificando a superficie desejada Se X ou Y forem vetores eles são internamente tratados para produzir boas matrizes de dimensões correspondentes às dimensões da matriz Z e o grid é forçosamente uma região retangular Considerando as três funções xij yij e zij a porção da superfície definida entre dois i e j consecutivos é chamada remendo Por padrão quando nenhuma matriz de cores é adicionada a uma chamada a surf o parâmetro de cor é ligado o dado Z Quando uma matriz de cores color é dada pode ser aplicada aos remendos de duas formas diferentes nos vértices ou no centro de cada remendo É por isto que se Z é uma matriz mxn a dimensão da matriz color C pode ser mxn uma cor definida por vértice ou m1xn1 uma cor definida por remendo A representação de cores também varia quando se especifica algumas GlobalProperties propriedades globais A propriedade FaceColor ajusta o padrão de gradação pode ser interp ou flat mo do padrão Quando interp é selecionado é realizado uma interpolação bilinear de cores no re mendo Se sizeC é igual a sizeZ1 ie for fornecida apenas uma cor ao remendo então a cor dos vértices definindo o remendo é ajustada para a dada cor do remendo Quando flat modo padrão é habilitado é utilizada uma representação de cores de facetadas uma cor por remendo Se sizeC é igual a sizeZ ie foi fornecida apenas uma cor por os vértices as últimas linha e coluna de C são ignoradas Os argumentos GlobalProperty devem ser usados para customizar a superfície Aqui está uma breve descrição de como funcionam GlobalProperty esta opção pode ser utilizada para especificar como todas as superfícies serão desenhadas Deve sempre ser um par de sentenças constituidos de um string definindo PropertyName nome da propriedade e seu valor associado PropertyValue que pode ser um inteiro ou outra coisa dependendo do tipo de PropertyName Note que você pode ajustar múltiplas propriedades a cor da face e da borda dados de cores mapeamento de dados de cores cor do marcador plano surf 788 de fundo e primeiro plano visibilidade recorte espessura das bordas da superfície ver Glob alProperty Note que todas essas propriedades podem ser reajustadas através das propriedades da entidade superfície ver surfaceproperties Observações Por padrão esboços sucessivos de superfície são superpostos Para limpar o esboço anteirior use clf Para habilitar o modo autoclear limpeza automática como modo padrão edite seus eixos padrões fazendo dagda daautoclear on Entre com o comando surf para visualizar uma demonstração Exemplos inicialização de Z Z 00001 00013 00053 00299 01809 02465 01100 00168 00008 00000 00005 00089 00259 03673 18670 24736 10866 01602 00067 00000 00004 00214 01739 03147 40919 64101 27589 02779 00131 00020 00088 00871 00364 18559 14995 22171 02729 08368 02016 00130 00308 04313 17334 01148 30731 04444 26145 24410 04877 00301 00336 04990 23552 21722 08856 00531 26416 24064 04771 00294 00137 01967 08083 02289 33983 31955 24338 12129 02108 00125 00014 00017 03189 27414 71622 71361 31242 06633 00674 00030 00002 00104 01733 10852 26741 26725 11119 01973 00152 00005 00000 00012 00183 01099 02684 02683 01107 00190 00014 00000 superfície simples surfZ note que X e Y são determinados pelas dimensões de Z a mesma superfície com faces vermelhas e bordas azuis scf2 nova figura de número 2 surfZfacecolrededgecolblu inicialização de X e Y NB aqui X tem as mesmas linhas e Y tem as mesmas colunas X 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 Y 30000 30000 30000 30000 30000 30000 30000 30000 30000 30000 23333 23333 23333 23333 23333 23333 23333 23333 23333 23333 16667 16667 16667 16667 16667 16667 16667 16667 16667 16667 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 surf 789 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 16667 16667 16667 16667 16667 16667 16667 16667 16667 16667 23333 23333 23333 23333 23333 23333 23333 23333 23333 23333 30000 30000 30000 30000 30000 30000 30000 30000 30000 30000 exemplo 1 scf3 surfXYZ exemplo 2 como você pode ver o grid não é necessariamente retangular scf4 X14 15 Y14 35 Z14 2 surfXYZ exemplo 3 X e Y são vetores mesmo comportamento que a amostra 1 com vetores o grid é inevitavelmente retangular scf5 nova figura de número 5 X 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 YX surfXYZ exemplos com LineSpec e GlobalProperty xdelwinsid destruindo todas as figuras existentes surfZZ5 array de cores especificado egce ecdatamappingdirect o padrão é scaled relativo ao mapa de cores colormap ecolorflag3 modo de gradação interpolada O padrão é 4 modo flat para surf scf2 surfXYZcolordaones1010edgecocyamarkerpentamarkersiz20markeredgyelydata5665 scf3 surfZcdatamappingdirect scf4 surfZfacecolinterp interpolated shading mode colorflag 3 scf10 axfig10gca scf11 surfaxfig10Zydat100109markerdmarkerfacgreenmarkeredgyel draw onto the axe of figure 10 xdelwinsid Ver Também plot2d clf xdel delete LineSpec GlobalProperty Autor FLeray 790 Name surfaceproperties Descrição das propriedades da entidade Surface superfície Descrição A entidade Surface é uma folha das hierarquia de entidades gráficas Duas classes aparecem sob este tipo de entidade Plot3d e Fac3d de acordo com a função de esboço ou com o modo como os dados foram inseridos As entidades Fac3d e Plo3d são semelhantes mas Fac3d é mais completa e aceita mais opções que Plot3d Para sempre ter entidades Fac3d simplesmente use genfac3d para préconstruir matrizes antes de usar os comandos plot3d ou use o comando surf Aqui estão as propriedades contidas em uma entidade superfície parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Surface pode ser Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores de superfície não possuem galhos correntemente visible este campo contém o valor padrão da propriedade visible para a entidade Pode ser on ou off Por padrão superfícies são visíveis o valor da propriedade é on Se for off os gráficos 3d não são exibidos na tela surfacemode este campo contém o valor padrão da propriedade surfacemode para a superfície Pode ser on superfície desenhada ou off nenhuma superfície desenhada foreground se colormode 0 contém o índice da cor a ser usada nas bordas Se não foreground não é usado O valor foreground deve ser um índice inteiro de cor relativo ao mapa de cores corrente thickness este campo contém o valor de thickness espessura das linhas usadas para desenhar facetas ou contornos Deve ser um inteiro positivo markmode este campo contém o valor padrão da propriedade markmode para a superfície Seu valor pode ser on marcas desenhadas ou off marcas não desenhadas markstyle o valor da propriedade markstyle é usado para selecionar o tipo de marca usada quando a propriedade markmode é on O valor deve ser um inteiro no intervalo 0 14 que significa ponto mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo rombo mais círculo asterísco quadrado trângulo para direita triângulo para esquerda e penta grama marksizeunit este campo contém o valor padrão da propriedade marksizeunit Se marksizeunit é ajustado para point então o valor de marksize é dado diretamente em pontos Quando marksizeunit é ajustado para tabulated marksize é computado de acordo com o array de tamanho de fonte logo seu valor deve ser um inteiro no intervalo 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que plot3d e funções puras do Scilab usam o modo tab ulated como padrão quando se utiliza as funções surf ou plot para linhas 2d o modo point é automaticamente habilitado surfaceproperties 791 marksize a propriedade marksize é utilizada para selecionar o tamanho de fonte das marcas quando a propriedade markmode está on O valor deve ser um inteiro entre 0 e 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt markforeground este campo contém o valor padrão da propriedade markforeground que é a cor da borda das marcas Seu valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor padrão da propriedade markbackground que é a cor da face das marcas Seu valor deve ser um índice de cor relativo ao mapa de cores corrente data este campo define uma estrutura de dados tlist do tipo 3d composto de índices de uma linha e uma coluna de cada elemento como as coordenadas x y e z contidas respectivamente em dataxdatay e dataz O campo complementar datacolor está disponível caso um vetor ou matriz reais de cores seja especificado Se nenhum for datacolor não é listado A superfície é pintada de acordo com as propriedades colormode e colorflag colormode um inteiro no intervalo sizecolormap sizecolormap definindo a cor da faceta quando o valor de colorflag é 0 Como dito antes se colormode 0 as bordas são desenhadas usando a cor foreground Se colormode é ajustado para 0 uma malha das superfície é desenhada faces da frente não têm cores Finalmente quando colormode 0 as faces da frente são pintadas com a cor colormode mas nenhuma borda é exibida colorflag este campo é usado para definir o algoritimo usado para ajustar as cores das facetas Note que as regras em colormode foreground e hiddencolor ainda são aplicadas nesse caso colorflag 0 Todas as facetas são pintadas usandose o índice de cores e o método definido por colormode ver acima colorflag 1 Todas as facetas são pintadas utilizandose um índice de cor por faceta proporcional a z O valor mínimo de z é pintado utilizandose o índice 1 enquanto o valor máximo de z é pintado utilizandose o índice mais alto As bordas das facetas pode ser adicionalmente desenhadas dependendo do valor de colormode ver acima Os três casos restantes colorflag 23 or 4 só estão disponíveis para a entidade Fac3d Então o valor de datacolor é usado para ajustar cores para as facetas índices do mapa de cores corrente se existirem Se não o colormode corrente é utilizado para pintar as facetas colorflag 2 flat shading Todas as facetas são pintadas utilizandose o índice de cor dado na propriedade datacolor uma cor por faceta é necessária Dois são os casos possíveis datacolor contém um vetor color vector se colori for positivo fornece a cor da faceta i e a borda da faceta é desenhada com o estilo de linha e cor correntes Se colori for negativo o a cor de identificador colori é usado e a borda da faceta não é desen hada datacolor contém uma matriz de cores de tamanho nfn onde n significa o número de facetas e nf o número de pontos definindo a faceta poligonal Para os vértices nf definindo surfaceproperties 792 cada faceta o algoritmo computa o valor médio do índice de cores da matriz de índices de cores os nf vértices da mesma faceta terão o mesmo valor de índice de cor colorflag 3 interpolated shading Pinta as facetas por interpolação das cores dos vértices Os índices das cores dos vértices são dados pela propriedade datacolor uma cor por vértice é necessária Dois são os casos possíveis datacolor contém um vetor colors então há poucos dados para completar o modo de gradação interpolada De fato uma matriz de cores de tamanho nfn onde n é o número de facetas e nf o número de pontos definindo a faceta poligonal é necessária para realizar esta operação Para cada faceta o algoritmo copia o único valor de índice de cor da faceta nos nf vértices de índices de cores definindo a borda da faceta datacolor contém uma matriz de cores de tamanho nfn ver acima para definições de nf e n o modo de gradação interpolada pode ser completado normalmente utilizandose estes índices de cores colorflag 4 Matlablike flat shading É o mesmo que colorflag2 com uma pequena diferença quando datacolor é uma matriz Todas as facetas são pintadas com o índice de cor fornecido pela propriedade datacolor uma cor por faceta é necessária Dois casos são então possíveis datacolor contém um vetor color vector se colori é positivo fornece a cor da faceta i e a borda da faceta é desenhada com o estilo de linha e cor correntes Se colori é negativo a cor de identificador colori é utilizado e a borda da faceta não é desenhada datacolor contém uma matriz de cores de tamanho nfn onde n é o número de facetas e nf o número de pontos definindo a faceta poligonal Para os nf vértices definindo cada faceta o algoritimo toma a cor do primeiro vértice definindo o retículo faceta cdatamapping específico para manipuladores Fac3d Um string definindo um valor scaled ou direct Se um datacolor é definido cada dado de índice de cor especifica um valor único para vértice cdatamapping determina se estes índices estão em escala para serem mapeados linearmente no mapa de cores corrente modo scaled ou aponta diretamente para o mapa de cores modo direct Esta propriedade é útil quando colorflag é igual a 23 ou 4 hiddencolor esta propriedade contém o índice de cor usado para desenhar as faces atrás de uma superfície Seu valor deve ser um inteiro positivo índice de cores relativo ao mapa de cores corrente Se for um inteiro negativo a mesma cor que a face visível é aplicada para a parte traseira clipstate este campo contém o valor da propriedade clipstate para a superfície O valor de clipstate pode ser off significa que a superfície não é recortada clipgrf significa que a superfície é recortada fora da caixa dos eixos on significa que a superfície é recortada fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções da poligonal a serem exibidas contudo o valor da propriedade clipstate será alterado surfaceproperties 793 userdata este campo pode ser usado para armazenar qualquer variável Scilab na estrutura de dados da superfície e recuperála Exemplos criando uma figura t0032pi zsintcost xxyyzzgenfac3dttz plot3dxx xxyy yylistzz zz44ones1400 5ones1400 hgethdl obtendo manipulador da entidade corrente aqui é a superfície agca obtendo eixos correntes arotationangles4070 agrid1 1 1 criando grides adatabounds601665 aaxesvisibleoff os eixos estão escondidos aaxesbounds2 0 1 1 fgetcurrentfigure obtendo o manipulador da figura raiz fcolormaphotcolormap64 mudando o mapa de cores da figura hcolorflag1 colorindo de acordo com z hcolormode2 removendo as bordas das facetas hcolorflag2 colorindo de acordo com as dadas cores hdatacolor1modulo1400641modulo140064 gradação hcolorflag3 scf2 criando segunda janela e utilizando o comando surf subplot211 surfzcdatamappingdirectfacecolinterp subplot212 surfttzedgecobmarkerdmarkersiz9markeredgredmarkerfack egce ecolorflag1 índice de cor proporcional à altitude coordenada z ecolorflag2 de volta ao modo padrão ecolorflag 3 modo de gradação interpolada baseada na cor azul padrão porque o campo datacolor não está preenchido Ver Também set get delete plot3d plot3d1 plot3d2 surf graphicsentities Autores Djalel ABDEMOUCHE FLeray 794 Name swaphandles Permuta dois manipuladores em uma hierarquia gráfica swaphandle handle1 handle2 Parâmetros handle1 primeiro manipulador da permutação handle2 segundo manipulador da permutação Descrição A função swaphandles permite permutar dois manipuladores em uma hierarquia gráfica O primeiro manipulador tomará a posição do segundo e viceversa Desde que nem todos os manipuladores são compatíveis com cada um dos outros existem algumas restrições ao se trocar manipuladores Por exemplo não é permitido trocar um manipulador Polyline com um manipulador Axes já que não seriam compatíveis com suas novas raízes Mais informação sobre compatibilidade pode ser encontrada na página graphicsentities Esta rotina pode ser utilizada em galhos com uma mesma raiz para se trocar os seus índices Exemplos Primeiro Exemplo criando um retângulo xrect 05 050505 rect gce criando um círculo xarc 05 05 05 05 0 64 360 circle gce criando uma seta xpoly0101 arrow gce arrowpolylinestyle 4 arrowarrowsizefactor 4 obtendo a lista de galhos axes gca axeschildren mudando a ordem swaphandles rect arrow swaphandles arrow circle obtendo a nova ordem axeschildren swaphandles 795 Segundo Exemplo criando duas janelas plot2d axes1 gca scf fec axes2 gca trocando os seus eixos note que o mapa de cores não muda swaphandles axes1 axes2 Ver Também graphicsentities copy delete relocatehandle Autor JeanBaptiste Silvy 796 Name textproperties Descrição das propriedades da entidade Text texto Descrição A entidade Text é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para escrita de strings parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Text deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores text não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o texto é visível a propriedade é on Se off o texto não é exibido na tela text a matriz contendo os strings do objeto As linhas da matriz são exibidas horizontalmente e as colunas verticalmente alignment especifica como os strings serão alinhados em suas colunas o valor deve ser left center ou right data este campo é o vetor xyz da origem do texto na unidade de dados dos eixos box o valor deste campo pode ser on ou off Se on uma caixa é desenhada ao redor do texto com uma linha em sua borda e um plano de fundo linemode esta propriedade booleana permite desenhar apenas o plano de fundo da caixa quando a pro priedade box é on Se linemode é off a linha da caixa não é desenhada fillmode esta propriedade booleana permite desenhar ou não o plano de fundo da caixa quando a pro priedade box é on Se fillmode for off o plano de fundo da caixa não é transparente textbox um vetor bidimensional especificando o tamanho do retângulo em coordenadas do usuário O retângulo é utilizado quando a propriedade textboxmode está ajustada pára centered ou filled textboxmode Pode ter três valores diferentes off centered ou filled Se off os strings são exibidos utilizandose a dada fonte e o campo data especifica a posição do ponto inferior esquerdo do texto Se centered o texto é exibido no meio do retângulo cujo tamanho é fornecido por textbox Se filled o tamanho de fonte dos strings será expandido para se preencher o retângulo Ao se utilizar os modos off ou centered o tamanho dos textos se mantém constante sob ampliação Eles são os melhores modos para se criar anotações em um gráfico Por outro lado ao se utilizar o modo filled o tamanho do texto segue a escala gráfica É então possível ampliar objetos textos textproperties 797 fontforeground este campo contém a cor utilizada para exibir os caracteres do texto O valor deve ser um índice de cor relativo ao mapa de cores corrente foreground este campo contém a cor utilizada para exibir a linha na borda da caixa O valor deve ser um índice de cores relativo ao mapa de cores corrente background este campo contém a cor utilizada para preencher a caixa ao redor do texto O valor deve ser um índice de cor relativo ao mapa de cores corrente fontsize é um escalar especificando o tamanho dos caracteres exibidos Se a propriedade fractionalfont é off apenas a parte inteira do valor é utilzada Para mais informações veja graphicsfonts fontstyle especifica a fonte a ser utilizada para exibir os strings É um inteiro positivo fazendo referência a uma das fontes carregadas Seu valor deve estar entre 0 referência à primeira fonte e o número de fontes carregadas menos um referência à última fonte Para mais informações veja graphicsfonts fractionalfont Esta propriedade indica se o texto será exibido utilizandose tamanhos de fonte fracionários Pode ser on ou off Se on o valor em ponto flutuante de fontsize é utilizado para exibição e retirase o serrilhamento da fonte Se off apenas a parte inteira é utilizada e a fonte não é suavizada fontangle esta propriedade determina a orientação do string Especifica o valor da rotação em graus clipstate este campo contém o valor da propriedade clipstate para o texto O valor de clipstate pode ser off significa que o texto não é recortado cliprf significa que o texto é recortado fora da caixa dos eixos on significa que o texto é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo contém o valor da propriedade clipbox Seu valor deve ser uma matriz vazia se clipstate é off ou o vetor xywh ponto superior esquerdo largura altura userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade texto e recuperála Exemplos agetcurrentaxes adatabounds0011 aaxesvisible on xstring0505Scilab is not esilaB00 tgethdl obtendo o manipulador do novo objeto criado textproperties 798 tfontforeground6 alterando as propriedades da fonte tfontsize5 tfontstyle5 ttextSCILABnãoéesilaB alterando tfontangle90 virando os strings ttextbox 00 ttextboxmode centered o texto está agora centrado em 0505 talignment center tbox on desenhando uma caixa ao redor do texto Ver Também set get delete xtitle graphicsentities Autor Djalel ABDEMOUCHE JeanBaptiste SILVY 799 Name title Exibe um título em uma janela gráfica titlemytitle titlemytitleProperty titleaxeshandlemytitleProperty Parâmetros mytitle string o título a ser exibido Property argumento opcional representa um par de declarações PropertyNamePropertyValueque definem propriedades de objetos globais aplicadas o título criado axeshandle este argumento opcional força o título a parecer dentro dos eixos selecionados dados por axeshandle ao invés dos eixos correntes ver gca Descrição title exibe um título numa janela de gráficos Os argumentos Property propriedade devem ser usados para customizar o título Aqui está uma lista completa das opções disponíveis Property backgroundcolor este campo contém a cor utilizada para preencher a caixa se houver Seu valor deve ser um índice de cor relativo ao mapa de cores corrente color este campo contém a cor a ser utilizada para exibir o texto de título Seu valor deve ser um índice de cor relativo ao mapa de cores corrente edgecolor este campo contém a cor usada para exibir a linha ao redor da caixa se houver alguma Seu valor deve ser um índice de cor relativo ao mapa de cores corrente fontname sete fontes diferentes estão disponíveis Courrier Symbol Times Times Italic Times Bold Definida pelo Usuário A propriedade fontsize é um índice no intervalo 0 6 que é associado a um dos nomes anteriores fontsize a propriedade é utilizada para selecionar o tipo de tamanho do título Seu valor deve ser um inteiro entre 0 e 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt position este vetor 2d permite que você posicione manualmente o título na tela A posição é armazenada nas unidades de dados dos eixos rotation escalar que permite que você gire o título A fonte é girada em sentido antihorário com o ângulo dado em graus visible este campo contém o valor da propriedade visible para o título Pode ser on ou off Por padrão o título é visível a propriedade é on Se off o título não é exibido na tela Exemplos title 800 exibindo um título com várias propriedades titlemeu título mudando a cor de fonte do título titlemeu títulocolorblue mudando a cor ao redor da caixa titlemeu títuloedgecolorred mudando a posição do título titlemeu títuloposition03 08 mudando o tamanho da fonte titlemeu títulofontsize3 dando uma rotação titlemeu títulorotation90 podemos realizar todas essas modificações apenas pela instrução abaixo titlemeu títulocolorblueedgecolorredfontsize3rotation90position03 08 Ver Também labelproperties titlepage xtitle Autor FBelahcene 801 Name titlepage adiciona título no meio de uma janela de gráficos titlepagestr Parameters str matriz de strings Descrição titlepage exibe a matriz de strings str no meio da janela de gráficos corrente com uma fonte a maior possível Ver Também xtitle Autor S S 802 Name twinkle Faz uma entidade gráfica piscar twinklehn Parâmetros h manipulador de uma entidade gráfica n inteiro Descrição twinkle faz com que a entidade gráfica dada pelo seu manipulador h pisque Pode ser usado para encontrar o objeto gráfico correspondente a um manipulador gráfico em uma janela de gráficos Por padrão a entidade gráfica pisca 5 vezes mas você pode mudar este número através do argumento opcional n Exemplos xlinspace2pi2pi100 plot2dxsinxcosx egce p1echildren1 p2echildren2 fazendo piscar o esboço de cos twinklep1 fazendo piscar o esboço de sin piscar twinklep210 eixos piscando twinklegca Ver Também graphicsentities 803 Name unglue Descola uma objeto Compound e o substitui por um galho individual unglueh Hunglueh Parâmetros h manipulador de um Compound H um vetor de manipuladores das entidades resultantes após um unCompound Descrição Dado um manipulador de uma entidade Compound destrói o Compound e desembrulha as entidades elementares associadas à sua raiz glue retorna um vetor de manipuladores desses galhos individuais Ver Também get set copy glue graphicsentities Autor Djalel ABDEMOUCHE 804 Name unzoom Diminui a ampliação unzoom unzoomH Parâmetros H um vetor de manipuladores Figure ou Axes Descrição unzoom é usado para remover o efeito de ampliação em todos os eixos da figura gráfica corrente unzoomH é usado para remover o efeito de ampliação em todos os Figures e Axes dados pelo vetor de manipuladores H A remoção do efeito de ampliação para uma entidade Figure é o mesmo que remover o efeito de ampliação para todos os seus Axes galhos Exemplos clf x00016pi plot2dxsinx2 zoomrect161181 unzoom aplicação a subesboços clf x00016pi subplot211 plot2dxcosx a1gca subplot212 plot2dxcos2x a2gca rect3 2 7 10 um retângulo especificado nos eixos correntes os últimos zoomrectrect unzooma1 diminuição de ampliação aplicado ao primeiro esboço apenas unzooma2 diminuição de ampliação aplicado ao segundo esboço apenas zoomrectrect aplicando ampliação de novo unzoomgcf diminuição de ampliação aplicada a todos os eixos equivalente a unzoom Ver Também zoomrect axesproperties Autor Serge Steer INRIA JeanBaptiste Silvy INRIA 805 Name whitecolormap Mapa de cores completamente branco cmapwhitecolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição O mapa de cores é completamente branco Exemplos f scf plot3d1 fcolormap whitecolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap wintercolormap 806 Name winsid retorna a lista de janelas de gráficos xwinsid Parâmetros x vetor linha Descrição winsid é usado para retornar a lista de janelas de gráficos como um vetor de números das janelas 807 Name wintercolormap Mapa de cores com tons do inverno azul verde cmapwintercolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição wintercolormap computa um mapa de cores com n cores que variam do azul para o verde Exemplos f scf plot3d1 fcolormap wintercolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap 808 Name xarc esboça parte de uma elipse xarcxywha1a2 Parâmetros xywh quatro valores reais definindo um retângulo a1a2 valores reais definindo um setor Descrição xarc desenha parte de uma elipse contida no retângulo xywh ponto superior esquerdo largura altura e no setor definido pelo ângulo alpha1e o ângulo alpha1alpha2 alpha1 e alpha2 são respectivamente dados por a164 graus e a264 graus Esta função usa a cor e a escala gráfica correntes Exemplos escala de isovisualização plot2d001031 2222 xsetcolor3 xarc112209064 xarc151533036064 Ver Também xarcs xfarc xfarcs Autor JPhC 809 Name xarcs desenha partes de um conjunto de elipses xarcsarcsstyle Parâmetros arcs matriz de tamanho 6n descrevendo as elipses style vetor linha de tamanho n fornecendo o estilo a ser usado Descrição xarcs desenha parte de um conjunto de elipses descritas por arcs arcsx y w h a1 a2x y w h a1 a2 onde cada elipse é definida por 6 parâmetros xywha1a2 ver xarc x y w h são especificados nas coordenadas do usuário stylei fornece a cor utilizada para desenhar a elipse número i Exemplos plot2d001031 1111 arcs10 00 05 x superior esquerdo 10 00 05 y superior esquerdo 05 10 05 largura 05 05 10 altura 00 00 00 ângulo 1 18064 36064 9064 ângulo 2 xarcsarcs123 Ver Também xarc xfarc xfarcs Autor JPhC 810 Name xarrows desenha um conjunto de setas xarrowsnxnyarsizestyle Parâmetros nxny vetores ou matrizes de reais de mesmo tamanho arsize escalar real o tamanho da cabeça da seta O tamanho padrão pode ser obtido ajustando arsize para 1 style matriz ou escalar Se style for um escalar positivo fornece a cor a ser usada em todas as setas Se for negativo a cor corrente é utilizada Se for um vetor stylei fornece a cor a ser utilizada no vetor i Descrição xarrows desenha um conjunto de setas dadas por nx e ny Se nx e ny forem vetores a iésima seta é definida por nxinyinxi1nyi1 Se nx e ny são matrizes nxxi1 x12 xf1 xf2 nyyi1 y12 yf1 yf2 a késima seta é definida por xikyikxfkyfk xarrows utiliza a escala de gráficos corrente que pode ser ajustada através de uma chamada a uma função de esboço de altonível como plot2d Exemplos x2pi098 x1sinx9sinx y1cosx9cosx plot2d1010101011022 xsetclipgrf xarrowsx1y11110 xsetclipoff Autor JPhC 811 Name xbasc limpa uma janela de gráficos xbascwindowid Parâmetros windowid escalar inteiro ou vetor de escalares inteiros Descrição Sem argumentos esta função limpa a janela de gráficos corrente e apaga os gráficos gravados Em outro caso ela limpa as janelas de gráficos cujos números estão inclusos no vetor windowid Por exemplo xbasc13 limpa as janelas 1 2 e 3 e apaga seus gráficos gravados correspondentes Se uma dessas janelas não existir ela é automaticamente criada xbasc deleta cada galho das janelas especificadas incluindo menus e uicontrols adicionados pelo usuário Para evitar que menus e uicontrols sejam apagados o comando deletegca pode ser utilizado ao invés A função xbasc está obsoleta Para apagar uma figura por favor use ao invés clf ou delete Ver Também clf xclear 812 Name xbasr desenha novamente uma janela de gráficos xbasrwinnum Descrição xbasr é usado para exibir novamente o conteúdo de uma janela de gráficos com i winnum Fun ciona apenas com o driver Rec Ver Também driver replot Autor JPhC 813 Name xchange conversão de coordenadas reais para coordenadas pixeis x1y1rectxchangexydir Parâmetros xy duas matrizes de tamanho n1n2 coordenadas de um conjunto de pontos dir parâmetro utilizado para especificar o tipo de conversão ver Description para detalhes x1y1 duas matrizes de tamanho n1n2 coordenadas de um conjunto de pontos rect um vetor de tamanho 4 Descrição Após o uso de uma função de gráficos xchange computa coordenadas pixel a partir de coordenadas reais e viceversa de acordo com o valor de parâmetro dirf2i float para int significa real para pixel e i2f int para float significa pixel para real x1 e y1 são as coordenadas de um conjunto de pontos definidos pelas antigas coordenadas x e y rect são as coordenadas em pixel do retângulo no qual o esboço foi feito ponto superior esquerdo largura altura Exemplos t0012pi plot2dtsint xyrectxchange11f2i xyrectxchange00i2f Autor JPhC 814 Name xclear limpa janela de gráficos xclearwindowid Parâmetros windowid vetor de inteiros ou escalar inteiro Descrição Sem argumentos esta função limpa a figura corrente ajustando a sua propriedade visible para off Em caso contrário ela limpa as janelas cujos números estão inclusos no vetor windowid Por exemplo xclear13 limpa as janelas 1 2 e 3 Se uma dessas janelas não existir então ela é automatica mente criada A função xclear está obsoleta Para limpar uma figura por favor utilize a função clf ao invés ou a propriedade visible Ver Também xbasc Autor JPhC 815 Name xclick espera por um clique do mouse ibuttonxcoordyxcoordiwincbmenuxclickflag Parâmetros ibutton escalar real valor inteiro número do botão do mouse código da tecla ver descrição abaixo xcoord escalar real coordenada x do ponteiro do mouse quando ocorreu o clique na escala gráfica cor rente ycoord escalar real coordenada y do ponteiro do mouse quando ocorreu o clique na escala gráfica cor rente iwin escalar real valor inteiro número da janela onde a ação ocorreu cbmenu string callback associado a um menu se xclick retorna devido a um clique em um menu Neste caso ibutton xcoord ycoord e iwin tomam valores arbitrários flag escalar real valor inteiro se presente a fila de eventos de clique não é limpa ao se entrar xclick Descrição xclick espera pelo clique do mouse na janela de gráficos Se for chamado com 3 argumentos do lado esquerdo espera pelo clique do mouse na janela de gráficos corrente Se chamado com 4 ou 5 argumentos do lado esquerdo espera pelo clique do mouse em qualquer janela de gráficos Os valores de ibutton estão descritos abaixo ibutton0 o botão esquerdo foi pressionado ibutton1 o botão do meio foi pressionado ibutton2 o botão direito foi pressionado ibutton3 o botão esquerdo do mouse foi clicado ibutton4 o botão do meio do mouse foi clicado ibutton5 o botão direito do mouse foi clicado xclick 816 ibutton10 o botão esquerdo do mouse foi clicado duas vezes ibutton11 o botão do meio do mouse foi clicado duas vezes ibutton12 o botão direito do mouse foi clicado duas vezes ibutton 32 uma tecla com código ASCII ibutton foi pressionada ibutton 32 uma tecla com código ASCII ibutton foi liberada ibutton 100032 uma tecla com código ASCII ibutton1000 foi pressionada enquanto a tecla CTRL estava sendo pressionada ibutton1000 a janela de gráficos foi fechada Aviso ibutton era igual a 100 para fechamento de janelas gráficas até o Scilab 412 mas este código foi modificado no Scilab 50 pois também era o código retornado pela liberação da tecla d ibutton2 um menu dinâmico foi selecionado e seu callback é retornado em cbmenu Ver Também locate xgetmouse seteventhandler Autores JPhC VC 817 Name xdel deleta uma janela de gráficos xdelwinnums Parâmetros winnums inteiro ou vetor de inteiros Descrição xdel deleta a janela de gráficos winnums ou a janela de gráficos corrente se não for fornecido nenhum argumento Autor JPhC 818 Name xfarc preenche parte de uma elipse xfarcxywha1a2 Parâmetros xywh quatro valores reais definindo um retângulo a1a2 valores reais definindo um vetor Descrição xfarc preenche parte de uma elipse contida no retângulo xywh ponto superior esquerdo largura altura no setor definido pelo ângulo alpha1 e o ângulo alpha1alpha2 alpha1 e alpha2 são respectivamente a164 graus e a264 graus Esta função usa a cor e a escala gráfica corrente Exemplos escala de isovisualização plot2d001031 2222 xfarc05051109064 xsetcolor2 xfarc050511036064 Ver Também xarc xarcs xfarcs Autor JPhC 819 Name xfarcs preenche partes de um conjunto de elipses xfarcsarcsstyle Parâmetros arcs matriz de tamanho 6n descrevendo as elipses style vetor linha de tamanho n fornecendo as cores a serem utilizadas Descrição xarcs preenche parte de um conjunto de elipses descritas por arcs arcsx y w h a1 a2x y w h a1 a2 onde cada elipse é definida por 6 parâmetros xywha1a2 ver xfarc x y w h são especificados nas coordenadas do usuário stylei fornece o número da cor para preencher a elipse número i Exemplos plot2d001031 1111 arcs10 00 05 x superior esquerdo 10 00 05 y superior esquerdo 05 10 05 largura 05 05 10 altura 00 00 00 ângulo 1 18064 36064 9064 ângulo 2 xfarcsarcs123 Ver Também xarc xfarc xfarc Autor JPhC 820 Name xfpoly preenche um polígono xfpolyxvyvclose Parâmetros xvyv dois vetores de mesmo tamanho os pontos do polígono close inteiro Se close 1 a linha poligonal é fechada o valor padrão é 0 Descrição xfpoly preenche um polígono com a cor corrente Se close é igual a 1 um ponto é adicionado à poligonal xvyv para definir o polígono Exemplos xsin2pi045 ycos2pi045 plot2d001010 2222 xsetcolor5 xfpolyxy apenas para novo estilo de gráficos egce retorna a última entidade corrente a última criada aqui é a poligonal efillmodeoff eclosed off a poligonal está aberta agora xsetdefault Ver Também xfpolys xpoly xpolys Autor JPhC 821 Name xfpolys preenche um conjunto de polígonos xfpolysxpolsypolsfill Parâmetros xpolsypols matrizes de mesmo tamanho pn pontos dos polígonos fill vetor de tamanho n ou tamanho pn Descrição xfpolys preenche um conjunto de polígonos de mesmo tamanho definidos pelas matrizes xpols e ypols As coordenadas de cada polígono são armazenadas em uma coluna de xpols e ypols Os polígonos podem ser preenchidos por uma dada cor preenchimento monótono ou pintados com cores interpoladas preenchimento por graduação preenchimento monótono Neste caso fill deve ser um vetor de tamanho n O padrão para preenchimento de um polígono de número i é dado por filli se filli0 o polígono é preenchido com padrão de identificador filli se filli0 o polígono é desenhado no estilo de traço ou cor corrente e não é preenchido se filli0 o polígono é preenchido com padrão de identificador filli Então seu contorno é desenhado com o estilo de traço ou cor corrente e fechado se necessário preenchimento interpolado Neste caso fill deve ser uma matriz com o mesmo mesmo tamanho de xpols e ypols Note que p deve ser igual a 3 ou 4 fillki fornece a cor da k ésima borda do polígono i Exemplos agcaadatabounds01021040aforegroundcolorred x1010203020100 y1153030150015 xpolsx1 x1 x1 x1 xpolsxpols060120180onesx1 ypolsy1 y1 y1 y1 xfpolysxpolsypols1012 cores interpoladas clf fgcf agcaadatabounds0104030aisoviewon x10102010 y11001020 clinspace21004 xpolsx1 x120 x110 x110 ypolsy1 y1 y110 y110 xfpolys 822 cols c c11 c3 4 1 2 c fcolormapjetcolormapmaxcols xfpolysxpolsypolscols cores interpoladas clf fgcf x11020200y1110103030c1110103030 x12x11y12y1120c12202011c1230301010 x2103030022y2120203030c2120203030 x22x21y22y2110c2230302020 x3104040055y31003030c31003030 x32x31y32y3130c32303000 Xx11 x12 x21 x22 x31 x32Yy11 y12 y21 y22 y31 y32Cc11 c12 c21 c22 c31 c3215 agcaaisoviewon adataboundsminXminYmaxXmaxY fgcffcolormapgraycolormapmaxC xfpolysXYC Ver Também xfpoly xpoly xpolys Autor JPhC 823 Name xfrect preenche um retângulo xfrectxywh xfrectrect rect xywh Parâmetros xywh quatro valores reais definindo um retângulo Descrição xrect preenche um retângulo definido por xywh ponto superior esquerdo largura altura usando a escala e o estilo correntes Exemplos plot2d001010 2222 xsetcolor5 xfrect1122 xsetdefault Ver Também xrect xrects Autor JPhC 824 Name xget retorna valores correntes do contexto gráfico Esta função está obsoleta x1xgetstrflag xget Parâmetros str string flag opcional Ajustado para 1 fornece um modo verboso Descrição Aviso esta função está obsoleta Use a representação de objetos gráficos do Scilab ver as ajudas de set e get bem como a página graphicsentities Esta função é utilizada para se obter valores de um contexto de gráficos no tópico especificado pelo string str Quando chamada sem argumento um menu de escolha é criado exibindo os valores cor rentes e mudanças podem ser realizadas através de botões de alternância numberxgetalufunction recebe o número da função lógica usada para desenhar Ver xset strxgetauto clear recebe o status de autolimpeza on ou off colorxgetbackground recebe a cor de fundo da janela de gráficos corrente rectxgetclipping recebe a zona de recorte como o retângulo rectxywh ponto superior esquerdo largura al tura cxgetcolor recebe a cor padrão para funções de preenchimento desenho de linha ou texto c é um inteiro projetado no intervalo 0whiteid 0 significa preenchimento com preto e whiteid preenchimento com branco O valor de whitid xgetwhite cmapxgetcolormap recebe o mapa decores utilizado para a janela de gráficos corrente como uma matriz m x 3 RGB vermelho verde azul dashxgetdashes recebe o estilo de traço dash dashnumber onde dashnumber é o identifcador do traço Esta palavrachave está obsoleta use xgetcolor ou xgetline style ao invés fontxgetfont recebe fontfontidfontsize a fonte padrão e o tamanho padrão para fontes fontsizexgetfont size recebe o tamanho padrão para fontes colorxgetforeground recebe a cor de primeiro plano do objeto Axes corrente O resultado é um índice do mapa de cores correspondente à cor xget 825 strxgetfpf recebe o formato em ponto flutuante do número do número de exibição em funções de contorno Note que str é quando o formato padrão é utilizado colorxgethidden3d recebe o número de cor para faces escondidas em plot3d patxgetlastpattern recebe o identificador do último padrão ou cor disponível no mapa de cores da janela corrente Na verdade pat1 e pat2 também estão disponíveis e correspondem a padrões preto e branco respectivamente typexgetline mode recebe o modo de desenho de linha type1 é o modo absoluto e type0 é o modo relativo Aviso type0 tem defeitos xgetline style recebe o estilo de linhas padrão1 sólido 1 para linhas tracejadas markxgetmark recebe o identificador do estilo de marcas padrão e o tamanho de marcas padrão markmarkidmarksize marksizexgetmark size recebe o tamanho de marcas padrão patxgetpattern recebe o padrão corrente ou a cor corrente pat é um inteiro no intervalo 1last Quando se usa preto ou branco 0 é usado para preenchimento com preto e last para preenchimento com branco O valor de last pode ser obtido com xgetlastpattern valuexgetthickness recebe a espessura das linhas em pixel 0 e 1 têm o mesmo significado 1 pixel de espessura flagxgetuse color recebe o flag 0 para uso apenas de preto e branco ou 1 uso de cores Ver xset xyxgetviewport recebe a posição corrente da parte visível de gráficos dimxgetwdim recebe a largura e a altura da janela de gráficos corrente dimlarguraaltura winxgetwindow recebe o número de janela corrente win posxgetwpos recebe a posição do ponto superior esquerdo da janela de gráficos posxy Ver Também xset getcolor getsymbol ged set graphicsentities Autor JPhC 826 Name xgetech retorna a escala de gráficos corrente wrectfrectlogflagarectxgetech Parâmetros wrectfrect vetores de reais logflag string de tamanho 2 xy Descrição xgetech retorna a escala de gráficos corrente da janela corrente O retângulo xminyminxmaxymax dado por frect é o tamanho de toda a janela de gráficos O esboço será feito na região da janela de gráficos corrente especificada por wrect wrectxywh ponto superior esquerdo largura altura descreve uma região dentro de uma janela de gráficos Os valores em wrect são especificados utilizandose a proporção de largura e altura da janela de gráficos wrect0 0 1 1 significa que toda a janela de gráficos será utilizada wrect05 0 05 1 significa que a região de gráficos é a metade direita da janela de gráficos logflag é um string de tamanho 2 xy onde x e y podem ser n ou l n significa escala normal linear e l significa escala logarítmica x corresponde ao eixo x e y corresponde ao eixo y arectxleft xrightyupydown fornece o tamanho da moldura dentro da sub janela O quadro gráfico é especificado como wrect utilizandose a proporção de largura ou altura da subjanela de gráficos corrente O valor padrão é 181111 Se arect não for fornecido o valor corrente permanece inalterado Exemplos primeira subjanela xsetech001005 plot2d então xsetech é usado para ajustar a segunda subjanela xsetech0051005 grayplot obtendo as escalas gráficas da primeira subjanela xsetech001005 wrectfrectlogflagarectxgetech obtendo as escalas gráficas da segunda subjanela xsetech0051005 wrectfrectlogflagarectxgetech xbasc xsetdefault Ver Também xsetech Autor 828 Name xgetmouse retorna os eventos de mouse e posição corrente rep winxgetmousesel Parâmetros sel vetor de booleanos getmotion getrelease O valor padrão é t f rep vetor de tamanho 3 xyibutton win número da figura onde o evento ocorreu Descrição Se o cursor do mouse estiver localizado na janela de gráficos corrente xgetmouse retorna em rep a posição corrente do cursor xy e o valor ibutton O valor de ibutton indica o tipo de evento ibutton0 o botão esquerdo do mouse foi pressionado ibutton1 o botão do meio do mouse foi pressionado ibutton2 o botão direito do mouse foi pressionado ibutton3 o botão esquerdo do mouse foi clicado ibutton4 o botão do meio do mouse foi clicado ibutton5 o botão direito do mouse foi clicado ibutton10 o botão esquerdo do mouse foi clicado duas vezes ibutton11 o botão do meio do mouse foi clicado duas vezes ibutton12 o botão direito do mouse foi clicado duas vezes ibutton5 o botão esquerdo do mouse foi liberado ibutton4 o botão do meio do mouse foi liberado ibutton3 o botão direito do mouse foi liberado xgetmouse 829 ibutton1 o cursor foi movido ibutton 32 uma tecla com código ASCII asciiibutton foi pressionada ibutton 32 uma tecla com código ASCII asciiibutton foi liberada ibutton 100032 uma tecla com código ASCII asciiibutton1000 foi pressionada enquanto o botão CTRL estava sendo pressionado ibutton1000 a janela de gráficos foi fechada AVISO Em versões anteriores do Scilab 50 o usuário podia fornecer um flag indicador para precisar se a fila de eventos do mouse deveria ser limpa ao se entrar xgetmouse Está opção está obsoleta agora e será removida no Scilab 51 Exemplos seleção de retângulo clf apagandocriando janela agcaadatabounds0 0100 100ajustando cooredenadas do usuário xtitle drawing a rectangle adicionando um título xselect pondo a janela no topo bxcycxclick retornando um ponto xrectxcyc00 desenhando a entidade Rectangle rgce o manipulador do retângulo repxcyc1firstf while rep31 do movimentação do mouse repxgetmouse xc1rep1yc1rep2 oxminixcxc1 oymaxiycyc1 wabsxcxc1habsycyc1 rdataoxoywh mudando a origem largura e altura do retângulo firstf end Ver Também locate xclick seteventhandler Autor S Steer 830 Name xgraduate Graduação de eixos xixanp1np2kMinrkMaxrarxgraduatexmixma Parâmetros xmixma escalares reais xi xa kMinr kMaxr ar escalares reais np1np2 inteiro Descrição xgraduate retorna as graduações de eixos que são utilizadas pelas rotinas de esboço com o flag de embelezamento habilitado Retorna um intervalo xixa que contém o dado intervalo xmixma e tal que xi kMinr10ar xakMaxr10ar e o intervalo pode ser dividido em np2 intervalos e cada intervalo é dividido em np1 subintervalos Exemplos x1xanp1np2kMinrkMaxrarxgraduate0302 Ver Também graduate plot2d Autor JPC 831 Name xgrid adiciona um grid em um esboço 2d xgridstyle Parâmetros style inteiro Descrição xgrid adiciona um grid em um esboço 2d style é o identificador de tipo de tracejado ou de cor utilizado para o esboço do grid Use xset para o significado do identificador Exemplos x0012pi plot2dsinx xgrid2 Ver Também xset plot2d Autor JPhC 832 Name xinfo escreve um string de informação na subjanela de mensagens xinfoinfo Parâmetros info string Descrição xinfo escreve o string info na subjanela de mensagens da janela de gráficos corrente 833 Name xlfont carrega uma fonte em um contexto gráfico ou pergunta a fonte carregada xlfontfontname xlfontfontfilename xlfontreset xlfontfontnamefontid xlfontfontfilenamefontid xlfontfontnamefontidbold xlfontfontnamefontidbolditalic fontsxlfontAVAILABLEFONTS fontsxlfont Parâmetros fontname string nome da família da fonte fontfilename string nome do arquivo de uma fonte true type fontid inteiro 0 fonts um vetor coluna de nomes de fontes bold um booleano t para negrito italic um booleano t para itálico Descrição Sem argumentos xlfont retorna a lista das fontes correntemente carregadas xlfontAVAILABLEFONTS retorna a lista de fontes disponíveis no seu sistema xlfontreset reajusta para o índice de fontes inicial Com argumentos xlfont é usado para carregar uma nova fonte em tamanhos diferentes no contexto gráfico As famílias de fonte padrões são Monospaced 0 Symbol 1 Serif 2 Serif Italic 3 Serif Bold 4 Serif Bold Italic 5 SansSerif 6 SansSerif Italic 7 SansSerif Bold 8 SansSerif Bold Italic 9 Estas fontes são automaticamente carregadas quando necessário então xlfont não é necessariamente requerido para elas Na verdade xlfont é essencialmente útil para carregar uma nova fonte Exemplos xlfontreset xlfont este exemplo pode no funcionar se seu sistema no possuir a fonte Monospaced xlfont 834 xlfontMonospaced10tt xstring10A title figureentity gcf axesentity figureentitychildren titleentity axesentitychildren titleentityfontstyle 10 xlfont xlfontSCIthirdpartyfontsscilabsymbolsttf titleentityfontstyle 11 utilizando a fonte scilabsymbolsttf titleentityfontsize 4 tamanho da fonte scilabsymbolsttf xlfont xlfontreset Ver Também getfont Autor Allan CORNET 835 Name xload carrega gráficos salvos xloadfilenamewinnum Parâmetros filename string o nome do arquivo winnum inteiro o número da janela de gráficos Se não for fornecido a janela de gráficos corrente é utilizada Descrição xload recarrega os gráficos contidos no arquivo filename na janela de gráficos winnum Desde o Scilab 50 todos os manipuladores uimenu ou uicontrol são também carregados Para arquivos contendo novos gráficos a função load pode ser utilizada ao invés de xload xload não recupera o número da janela nem seu tamanho ou dimensões Exemplos novo estilo t000110 subplot211plot2dtsint subplot212plot2dtsin3t saveTMPDIRfooscggcf clf loadTMPDIRfooscg agca curveachildrenchildren manipulador da curva saveTMPDIRfooscgcurve deletecurve loadTMPDIRfooscg Ver Também xsave load save Autor JPhC 836 Name xname muda o nome da janela de gráficos corrente xnamename Parâmetros name string o novo nome da janela de gráficos Descrição xname muda o nome da janela de gráficos corrente Autor JPhC 837 Name xnumb Imprime números xnumbxynumsboxangle Parâmetros xynums vetores de mesmo tamanho box valor inteiro angle vetor opcional de mesmo tamanho de x Descrição xnumb imprime os valores de numsi na posição xiyi na escala corrente Se box tem valor 1 um retângulo é desenhado ao redor dos números Se angle for dado fornece a direção para escrita do string Exemplos plot2d10050010060011022 x0100200 xnumbx500onesx1020351 Ver Também xstring Autor JPhC 838 Name xpause suspende o Scilab xpausemicrosecs Descrição xpause suspende o processo corrente pelo número de microssegundos especificados pelo argumento A suspensão real pode tornarse mais longa devido a outras atividades do sistema ou por causa do tempo gasto no processamento da chamada Autor JPhC 839 Name xpoly desenha uma poligonal ou um polígono xpolyxvyv dtype close Parâmetros xvyv matrizes de mesmo tamanho os pontos da poligonal dtype string estilo de desenho O valor padrão é lines close inteiro Se close 1a poligonal é fechada o valor padrão é 0 Descrição xpoly desenha uma poligonal descrita pelos vetores de coordenadas xv e yv Se xv e yv forem matrizes serão considerados vetores obtidos por concatenação de suas colunas dtype pode ser lines para uso do estilo de linha corrente ou marks para utilizar a marca corrente para de senho da poligonal Exemplos xsin2pi045 ycos2pi045 plot2d001010 2222 xsetcolor5 xpolyxylines1 por padrão é fechado apenas no novo estilo de gráficos egce retorna a entidade corrente a última criada aqui é a poligonal eclosed off a poligonal está agora aberta Ver Também xfpoly xfpolys xpolys Autor JPhC 840 Name xpolys desenha um conjunto de poligonais ou polígonos xpolysxpolsypolsdraw Parâmetros xpolsypols matrizes de mesmo tamanho pn pontos das poligonais draw vetor de tamanho n Descrição xpolys desenha um conjunto de poligonais usando marcas ou linhas tracejadas As coordenadas de cada poligonal são armazenadas em uma coluna de xpols e ypols O estilo da poligonal i é dado por drawi Se drawi for negativo a marca com identificador drawi i é utilizada para desenhar a poligonal i marcas são desenhadas utilizandose o padrão corrente Use xset para ver o sig nificado dos identificadores Se drawi for estritamente positivo o estilo de linha ou cor com identificador drawi é utilizado para desenhar a poligonal i Use xset para ver o significado dos idenficadores Exemplos plot2d001012 0011 randuniform xsetcolor3 xpolysrand35rand3512012 xsetdefault Ver Também xfpoly xfpolys xpoly Autor JPhC 841 Name xrect desenha um retângulo xrectxywh xrectrect rect xywh Parameters xywh quatro valores reais definindo o retângulo Descrição xrect desenha um retângulo definido por xywh ponto superior esquerdo largura altura usando a escala e o estilo correntes AVISO por favor note que a altura é positiva indo para baixo Exemplos plot2d001010 2222 xsetcolor5 xrect1122 xsetdefault Ver Também xfrect xrects Autor JPhC 842 Name xrects desenha ou preenche um conjunto de retângulos xrectsrectsfill Parâmetros rects matrtiz de tamanho 4n fill vetor de tamanho n Descrição xrects desenha ou preenche retângulos Cada coluna de rects descreve um retângulo ponto su perior esquerdo largura altura rectsx1 y1 w1 h1x2 y2 w2 h2 filli fornece o padrão para preenchimento ou desenho do retângulo i Se filli0 o retângulo i é desenhado utilizandose o estilo de linha ou cor filli Se filli0 o retângulo i é preenchido utilizandose o padrão ou cor filli Se filli0 o retângulo i é desenhado utilizandose o estilo de linha corrente ou cor AVISO por favor note que a altura é positiva indo para baixo Exemplos plot2d100500505011022 cols34333220520323334 x40001414 step20 rectsx10onesxsteponesx30onesx xrectsrectscols xnumbx15onesxcols Ver Também xfrect xrect Autor JPhC 843 Name xrpoly desenha um polígono regular xrpolyorignrtheta Parâmetros orig vetor de tamanho 2 n inteiro número de lados r escalar real theta escalar real ângulo em radianos 0 é o valor padrão Descrição xrpoly desenha um polígono regular com n lados contindo no círculo de diâmetro r e com a origem do círculo posta em um ponto orig theta especifica a rotação do ângulo em radianos Esta função utiliza as escalas gráficas correntes Exemplos plot2d001012 001010 xrpoly5555 Ver Também xrect 844 Name xsave salva gráficos em um arquivo xsavefilenamewinnum Parâmetros filename string nome do arquivo winnum inteiro o número da janela de gráficos Se não for forneceido a janela de gráficos corrente é utilizada Descrição xsave salva os gráficos contidos na janela de gráficos winnum no arquivo binário filename e pode ser carregado com xload Desde o Scilab 50 todos os manipuladores uimenu ou uicontrol também são salvos Para novos gráficos xsavefilenamewinnumuse preferivelmente savefilenamescfwinnum Exemplos novo estilo t000110 subplot211plot2dtsint subplot212plot2dtsin3t saveTMPDIRfooscggcf clf loadTMPDIRfooscg agca curveachildrenchildren handle on the curve saveTMPDIRfooscgcurve deletecurve loadTMPDIRfooscg Ver Também xload save load Autor JPhC 845 Name xsegs desenha segmentos desconexos xsegsxvyvstyle Parâmetros xvyv matrizes de mesmo tamanho style vetor ou escalar Se style is a positive scalar it gives the color to use for all segments Se style for negativo então a cor corrente é utilizada Se style for um vetor então stylei fornece a cor a ser utilizada no segmento i Descrição xsegs desenha um conjunto de segmentos desconexos dados por xv e yv Se xv e yv forem matrizes serão considerados como vetores através da concatenação de suas colunas As coordenadas dos dois pontos definindo um segmento são dadas por dois valores consecutivos de xv e yv xviyvixvi1yvi1 Por exemplo utilizando matrizes de tamanho 2n os segmentos são definidos por xvxi1 xi2 xf1 xf2 yvyi1 yi2 yf1 yf2 e os segmentos são xikyikxfkyfk Exemplos x2pi0910 xvsinx9sinx yvcosx9cosx plot2d1010101011022 xsegsxvyv110 Autor JPhC 846 Name xselect restaura a janela de gráficos corrente xselect Descrição xselect restaura a janela de gráficos corrente Se tal janela não existir uma é criada Aviso está função está obsoleta e será removida no Scilab 51 Ela foi substituída pela função showwindow Ver Também showwindow Autores JPhC JeanBaptiste Silvy 847 Name xset ajusta valores para o contexto gráfico Função obsoleta xsetchoicenamex1x2x3x4x5 xset Parâmetros choicename string x1x5 dependem de choicename Descrição Aviso está função está obsoleta Utilize a representação de objetos do Scilab ao invés ver as documentações das funções set e get bem como a página graphicsentities xset é utilizado para ajustar valores padrões do contexto da janela de gráficos corrente Quando chamado sem argumento um menu de escolha é criado exibindo os valores correntes e mudanças podem ser realizadas através e botões de escolha Use xset para exibir ou ajustar a cor corrente marca e fontes utilizadas xsetalufunctionnumber usado para ajustar a função lógica para desenho A função lógica utilizada é ajustada por x1 Os valores usuais são 3 para cópia padrão 6 para animação e 0 para limpeza Ver alufunctions para mais detalhes xsetauto clearonoff alterna o modo de limpeza automática para gráficos entre on e off Quando o modo de limpeza automática é on esboços sucessivos não são superpostos ie uma operação xbasc a janela de gráficos é limpa e os gráficos gravados associados são apagados é realizada antes de cada função gráfica de altonível O valor padrão é off xsetbackgroundcolor ajusta a cor de plano de fundo do objeto Axes corrente O argumento color é um índice no mapa de cores da cor a ser utilizada xsetclippingxywh ajusta a zona de recorte a zona da janela de gráficos onde os esboços podem ser desenhados como sendo o retângulo xywh ponto superior esquerdo largura altura Esta função utiliza a utiliza as coordenadas correntes do esboço xsetcolorvalue ajusta a cor padrão para funções de preechimento linha ou impressão de textos value é um inteiro projetado no intervalo 0whiteid 0 é usado para preenchimento com preto e whiteid para preenchimento com branco O valor do identificador do branco pode ser obtido através de xgetwhite xsetcolormapcmap ajusta o mapa de cores como sendo uma matriz m x 3 m é o número de cores A cor de número i é dada como sendo a tripla cmapi1 cmapi2 cmapi3 correspondentes respectivamente às intensidades de vermelho verde e azul entre 0 e 1 xset 848 xsetdashesi no modo preto e branco xsetuse color0 ajusta o estilo de tracejado como o estilo i 0 para linha sólida No modo colorido xsetuse color1 é utilizado para ajustar a cor da linha da marca e do texto Esta palavrachave está obsoleta utilize xsetcolori ou xsetline stylei ao invés xsetdefault reajusta o contexto gráfico para valores padrões xsetfontfontidfontsize ajusta a fonte corrente e seu tamanho Note que fontsize se aplica a todas as fontes não só a fontid xsetfont sizefontsize ajusta o tamanho da fonte xsetforegroundcolor ajusta a cor de primeiro plano do objeto Axes corrente O argumento color é um índice no mapa de cores da cor a ser utilizada xsetfpfstring ajusta o formato de exibição de ponto flutuante para funções de contorno string é um string fornecendo o formato em sintaxe C por exemplo string3f Use string para retornar ao formato padrão xsethidden3dcolorid ajusta o número de cor para as faces escondidas em um plot3d colorid0 suprime o desen ho de faces escondidas de objetos 3d Isto é tecnicamente chamdo culling e acelera a renderização de superfícies fechadas xsetline modetype esta função é utilizada para se ajustar o modo de desenho da linha O modo absoluto é ajustado com type 1 e o modo relativo com type0 aviso o modo type 0 possui defeitos xsetline stylevalue ajusta o estilo de linha corrente 1 sólida 1 estilos tracejados xsetmarkmarkidmarksize ajusta a marca corrente e seu tamanho Use xset para visualizar as marcas Note que mark size se aplica a todas as marcas não apenas a markid xsetmark sizemarksize ajusta o tamanho da marca xsetpatternvalue ajusta o padrão pattern não confundir com padrão default corrente para funções de preenchi mento O valor é um inteiro projetado no intervalo 0whiteid 0 é utilizado para preenchimento com preto e whiteid para preenchimento com branco O valor de whiteid pode ser obtido com xgetwhite pattern é equivalente a color xsetpixmapflag se flag0 os gráficos são diretamente exibidos na tela Se flag1 os gráficos são feitos em um pixmap mapa de pixel e enviados à janela de gráficos através do comando xsetwshow O pixmap é limpo com o comando xsetwwpc Note que o comando usual xbasc também limpa o pixmap xsetthicknessvalue ajusta o valor de espessura das linhas em pixel 0 e 1 têm o mesmo significado 1 pixel de es pessura xset 849 xsetuse colorflag se flag1 então xsetpattern ou xsetdashes será utilizado de modo a modificar a cor padrão para desenho ou para padrões de preenchimento Se flag0 então retornase ao modo de escalas de cinza e tracejados xsetviewportxy ajusta a posição do cursor xsetwdimwidthheight ajusta a largura e altura da janela de gráficos corrente Esta opção não é utilizada pelo driver Postscript xsetwpdimwidthheight ajusta a largura e altura da janela de gráficos física corrente que pode ser diferente do tamanho atual no modo wresize 1 Esta opção não é utilizada pelo driver Postscript xsetwindowwindownumber ajusta a janela windownumber como sendo a janela corrente e cria a janela se esta não existir xsetwposxy ajusta a posição do ponto superior esquerdo da janela de gráficos xsetwresizeflag se flag 1então o gráfico é automaticamente redimensionado para preencher a janela de gráficos xdel xsetwresize1 plot2d xsetwdim1000500 Se flag0 a escala do gráfico é inalterada quando a janela de gráfico é redimensionada O cursor no canto superior esquerdo ou as setas do teclado podem ser utilizadas para rolar o gráfico xdel plot2d xsetwresize0 xsetwdim1000500 xsetwshow ver xsetpixmap1 acima xsetwwpc ver xsetpixmap1 acima Ver Também xget getcolor getsymbol ged set graphicsentities Autor JPhC 850 Name xsetech ajusta a subjanela de uma janela de gráficos para esboço xsetechwrectfrectlogflag xsetechwrectfrectlogflag arect xsetech Parâmetros wrect vetor de tamanho 4 definindo a subjanela a ser utilizada frect vetor de tamanho 4 logflag string de tamanho 2 xy onde x e y podem ser n ou l n escala normal e l significa escala logarítmica x referese ao eixo x e y ao eixo y arect vetor de tamanho 4 Descrição xsetech é principalmente utilizado para ajustar a subjanela da janela de gráficos que será utilizada para esboço A subjanela é especificada através do parâmetro wrectxywh ponto superior esquerdo largura altura Os valores em wrect a são especificados utilizandose a proporção de largura ou altura da janela de gráficos corrente Por exemplo wrect0011 significa que toda a janela será utilizada e wrect050051 significa que a região gráfica será a metade direita da janela de gráficos xsetech também ajusta as escalas gráficas correntes para esboço 2d e pode ser utilizada juntamente a rotinas gráficas que requerem a escala de gráficos corrente por exemplo strfx0z ou frame flag0 em plot2d frectxminyminxmaxymax é utilizado para ajustar a escala gráfica e é igual ao argumento rect de plot2d Se frect não for fornecido o valor corrente da escala de gráficos permanece inalterado O valor padrão de rect é 0011 na criação de janelas quando se volta para o valor padrão com xsetdefault ou quando se limpa eventos gráficos gravados xbasc arectxleft xrightyupydown é utilizado para ajustar a moldura gráfica dentro da subjanela A moldura gráfica é especificada como wrect utilizandose a proporção de largura ou altura da subjanela de gráficos corrente O valor padrão é 181111 Se arect não for fornecido o valor padrão permanece inalterado Exemplos para obter uma explanação gráfica dos parâmetros de xsetech entre com execSCImodulesgraphicsdemosxsetechfigsce aqui xsetech é usado para dividir a janela de gráficos em duas partes o primeiro xsetech é usado para se ajustar a primeira subjanela e a escala de gráficos corrente xsetech0010055353 chamamos plot2d com a opção 001 para utilizar a escala de gráficos ajustada por xsetech xsetech 851 plot2d1101101001 então xsetech é usado para ajustar a segunda subjanela xsetech0051005 a escala de gráficos é ajustada por xsetech para 0011 por padrão e nós a modificamos utilizando o argumento rect em plot2d plot2d1101101011 6666 quatro esboços em uma única janela de gráficos xbasc xsetfont20 xsetech000505 plot3d xsetech0500505 plot2d xsetech05050505 grayplot xsetech0050505 histplot de volta aos valores padrões para a subjanela xsetech0011 um esboço com arect modificado xbasc xsetdefault xsetecharect0000 x10110plot2dxsinx xbasc xsetecharect181811614 x10110plot2dxsinx xbasc xsetdefault Ver Também xgetech subplot isoview square Autor JPhC 852 Name xsetm Abre uma caixa de diálogo para ajustar valores do contexto gráfico Função obsoleta xsetm Descrição Esta função bem como a função xset estão fortemente ligadas ao modo gráfico antigo que não está mais disponível O novo modo gráfico é muito mais flexível quanto ao ajuste de parâmetros ver a ajuda das funções set e get bem como a página de graphicsentities É possível iniciar um editor de propriedades mais conveniente através de ged Ver Também xset ged set graphicsentities Autor JPhC ENPC 853 Name xstring imprime strings xstringxystranglebox Parâmetros xy escalares reais coordenadas do ponto inferior esquerdo dos strings str matriz de strings angle real ângulo horário em graus O valor padrão é 0 box inteio o valor padrão é 0 Descrição xstring imprime a matriz de strings str na localização xy ponto inferior esquerdo na escala de gráficos corrente cada linha da matriz significa uma linha de texto e os elementos das linhas são palavras separadas por espaços em branco Se angle for dado fornece a inclinação em graus para escrever os strings Se box for 1 e angle for 0 uma caixa é desenhada ao redor dos strings Exemplos plot2d01010 xstring0505Scilab não é esilaB outro exemplo alphabeta b c d e f g h i j k l m n o p q r s t u v w x y z xbasc plot2d01020 xstring0118alphabet alfabeto xstring0116alphabet01 alfabeto em uma caixa xstring0114alphabet20 ângulo xsetfont11 usando fontes symbol xstring0101alphabet xsetfont13 mudando tamanho da fonte xstring0103alphabet xsetfont124 xstring0106a alfa grande xsetdefault Ver Também titlepage xnumb xstringb xstringl xtitle Autor JPhC 854 Name xstringb escreve strings em uma caixa xstringbxystrwhoption Parâmetros xywh vetor de 4 escalares reais definindo a caixa str matriz de strings option string Descrição xstringb desenha a matriz de strings str centrada dentro do retângulo rectxywh ponto inferior esquerdo largura altura na escala gráfica corrente Se option for fornecido com o valor fill o tamanho do caractere é computado de modo a preencher o retângulo o máximo possível Entre com o comando xstringb para uma demonstração Exemplos strScilab nãoé elisaB plot2d0011010 0011 r00105 xstringbr1r2strr3r4fill xrectr1r2r4r3r4 rr1r2r4001r3r42 xrectr1r2r4r3r4 xstringbr1r2strr3r4fill rr1r2r4001r3r42 xrectr1r2r4r3r4 xstringbr1r2strr3r4fill Ver Também titlepage xstring xstringl xtitle Autor JPhC 855 Name xstringl computa uma caixa que cerca strings rectxstringlxystrfontIdfontSize Parâmetros rect vetor de reais de 4 entradas definindo a caixa xy escalares reais coordenadas do ponto infeirior esquerdo str matriz de strings fontId um inteiro especificando o tipo de fonte fontSize um inteiro especificando o tamanho da fonte Descrição xstringl retorna em rectxywh ponto superior esquerdo largura altura o tamanho do retângulo na escala de gráficos corrente que cerca os strings str escritos na localização xy ponto inferior esquerdo O resultado pode ser aproximado utilizandose um driver Postscript Exemplos plot2d01010 strScilab nãoé elisaB rxstringl0505str xrectsr1 r2r4 r3 r4 xstringr1r2str plot2d01010 strScilab nãoé Matlab r2 xstringl0505str25 xrectsr21 r22r24 r23 r24 xstringr21r22str txt2gce txt2fontsize 5 txt2fontstyle 2 Ver Também titlepage xstring xstringl xtitle stringbox Autor JPhC 856 Name xtitle adidciona títulos a janelas de gráficos xtitletitlexlabelylabelzlabeloptsargs Parâmetros titlexlabelylabel zlabel matrizes de strings optargs uma seqüência de declarações key1value1 key2value2 onde keys podem ser boxed ver abaixo Nesse caso a ordem não tem valor especial boxed um valor inteiro Se for 1 um retângulo é desenhado ao redor de cada título Descrição xtitle adiciona títulos a um esboço 2d ou 3d title é o título geral e xlabel ylabel e zlabel são os títulos dos três eixos Se os argumentos são matrizes cada linha das matrizes é exibida em uma linha diferente Entre com o comando xtitle para visualizar uma demonstração Exemplos desenhando uma superfície plot3d pondo os títulos xtitle Minha superfície é azul eixo X eixo Y eixo Z desenhando uma caixa ao redor dos títulos xtitle Minha superfície é azul eixo X eixo Y eixo Z boxed 1 Ver Também titlepage labelproperties Autor JPhC 857 Name zoomrect Amplia uma seleção da figura gráfica corrente zoomrect zoomrectrect zooomrecth zoomrecthrect Parâmetros rect vetor de tamanho 4 xminyminxmaxymax fornece o retângulo a ser ampliado h manipulador gráfico do tipo Figure ou Axes Especifica sobre que eixos se realizará a ampliação Descrição zoomrect é a função utilizada para realizar ampliações dentro de um conjunto de objetos Axes O argumento de entrada h especifica sobre que eixos se realizará a ampliação Se h for um manipulador do tipo Figure então a ampliação ocorrerá sobre seus galhos Axes Se h for um manipulador Axes a ampliação será aplicada apenas sobre este objeto Se h não for especificado então a ampliação será aplicada sobre a entidade Figure corrente Se o argumento de entrada rect for especificada então a propriedade zoombox dos eixos ampli ados será modificada por este argumento ver axesproperties Seus limites ao longo dos eixos X e Y serão substituídos por rect Se rect não for especificado zoomrect será uma ampliação interativa Requerse que o usuário selecione um retângulo utilizando o mouse A nova propriedade zoombox dos eixos ampliados é então computada encontrandose as interseções do retângulo com suas caixas de eixos Exemplos clf x00016pi plot2dxsinx2 zoomrect161181 mais zoom zoomrect1601621 de volta ao original unzoom ajustando o zoom através de axesproperties agca azoombox1601621 azoombox ajustando zoom de subesboços clf x00016pi subplot211 plot2dxcosx subplot212 plot2dxcos2x zoomrect 858 rect3 2 7 10 um retângulo especificado nas coordenadas dos eixos correntes os últimos zoomrectrect unzoom ajustando os eixos subjascentes globais como sendo os correntes fgcfsetcurrentaxesfchildren rect04 0 06 1 um retângulo especificado em razão do tamanho da janela zoomrectrect rect04 02 06 08 um retângulo especificado em razão do tamanho da janela zoomrectrect ampliação interativa sob a figura corrente zoomrect ou zoomrectgcf Ver Também unzoom axesproperties Autor Serge Steer INRIA JeanBaptiste Silvy INRIA 859 Name Math rendering in Scilab graphics Display mathematical equations in Scilab graphics through the LaTeX or MathML languages Usage Starting from Scilab 52 it is possible to write LaTeX or MathML expression LaTeX texts must start and end by dollar symbol while MathML texts must start by and end by and being syntactically valide On the first use these libraries are loading on the fly only when needed note that the MathML engine is slower to load than LaTeX Example with LaTeX MathML ticks plot2d agca mathmlmrowmfracmrowmidmimiymimrowmrowmidmimixmimrowmfracmomo mfracmn1mnmsupmiymimn2mnmsupmfracmrow LaTeX and MathML mixed expression axtickslabelsmathml1sinx3cosa test567 LaTeX description The rendering engine is based on the Java library JLaTeXMath JLaTeXMath is an implementation of the mathematic mode of LaTeX All LaTeX base commands are handle dont hesitate to submit a bug report if missing On the contrary TeX commands like over are not supported Since Scilab 521 greek cyrillic and complete unicode for latin alphabets characters are handled in the Scilab graphics xtitle extstylesumn1inftyfrac1n2fracpi26 xtitlebigbigg xtitlemboxVector field for ddot hetasin heta xtitleJLaTeXMath mathfrakand mathttScilab xstring0505overbrace underbrace µ JLaTeXMath provides several fonts with the commands mathbb mathscr mathcal mathbf mathit mathsf mathtt mathfrak mathds mathrm with their bold versions when they are available with the command boldsymbol xtitlemathbbSCILAB mathsfor boldsymbolmathfrakScilab xtitlemathscrCmbox nest pas boldsymbolmathcalC Different LaTeX packages are available amsmath amssymb stmaryrd amsxtra and ac cents with some commands of graphics Most of the commands of these packages are available some of amsmath are missing for example xtitlesidesetalphabetagammadeltaprod xtitlehataccentsetstarhat hundertildeABC Math rendering in Scilab graphics 860 xtitlebeginpmatrixmathfrakaalphamathbbAmathcalAendpmatrixmbox or beginbmatrixmathfrakaalphamathbbAmathcalAendbmatrix xstring0505leftfracpisqrt32middlesqrtfrac1frac1xxrightrangle xtitledoublecupddagfatbslashllloplusoveecircledcirccirclearrowright xtitlerotatebox180boxedJLaTeXMath reflectboxJLaTeXMath xtitlescalebox06sumn1inftyfrac1n2fracpi26 xtitlefcolorboxblackTanJLaTeXMath xtitle extcolorMagentamathfrakScilabmbox and extcolorGreenmathcalSCILAB It is also possible to define new commands or new environments xtitle ewcommandopleft ewcommandcpright opfrac12cp xtitle ewcommandmyfrac2fracmathfrak1mathcal2myfracAB MathML description The MathML rendering is based on Jeuclid Jeuclid is a MathML implementation which covers the whole specification Therefor all the MathML language is supported within Scilab Due to the size of the Jeuclid library on the first use it can take up to a few seconds to load However next uses are much faster plot3d agetcurrentaxes axlabelfontsize 5 axlabeltextmrowmfracmrowmn1mnmrowmrowmn2mnmrowmfracmomomfenced open close mrowmfracmrowmfracmrowmiamimrowmrowmibmimrowmfracmrowmrowmfracmrow micmimrowmrowmidmimrowmfracmrowmfracmrowmfencedmrow See Also xtitle axesproperties labelproperties legendproperties textproperties xstringb xstringl xstring Parte VII Gráficos exportando e imprimindo 862 Name driver seleciona um driver gráfico driverdrivername currentdriverdriver Parâmetros drivername string driver a ser selecionado Descrição Esta função seleciona um driver gráfico ou sem argumentos retorna o nome do driver gráfico cor rente Na maioria das vezes o usuário pode ignorar esta função e modificar o driver por uma chamada a funções de alto nível como xbasc O driver selecionado pode ser um dos seguintes X11 saída para a tela do computador Pos saída em formato Postscript Rec saída para a tela do computador É o mesmo que X11 Fig saída em formato XFig GIF saída em formato Gif PPM saída em formato PPM Observação Para converter arquivos GIF ou PPM para outro formato de imagem para construir uma animação podese utilizar o programa convert para ImageMagic httpwwwimagemagickorg Por exemplo se é gerada uma seqüência de arquivos Gif nomeada imggif é possível construir um arquivo Gif animado chamado animgif por convert delay 10 imggif animgif Ver Também xbasc Autor JPhC 863 Name xend termina uma sessão de gráficos xend Descrição xend é usado para encerrar uma sessão de gráficos Sob os drivers Postscript Xfig ou Gif xend fecha o arquivo que foi aberto por xinit Exemplos driverPos xinitfoops plot2d xend driverX11 Ver Também xinit Autor JPhC 864 Name xinit inicialização de um driver de gráficos xinitFileName xinit Parâmetros FileName string nome do arquivo a exportar Descrição Para os drivers Postscript Xfig Gif ou PPM FileName deve ser especificado É o nome do arquivo onde todas as operações gráficas são registradas Para os drivers X11 ou Rec xinit deve ser chamado sem nenhum argumento e abre uma janela de gráficos vazia Exemplos driverPos xinitfoops plot2d xend driverX11 Ver Também driver xend scf Autores JPhC JeanBaptiste Silvy 865 Name xs2bmp envia gráficos para um arquivo em sintaxe BMP xs2bmpwinnumfilen Parâmetros winnum escalar inteiro filen string nome do arquivo Descrição xs2bmp envia os gráficos gravados em uma janela winnum para o arquivo filen no formato BMP Exemplos scf0 plot2d Exportando para BMP xs2bmp0foobmp Ver Também xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf Autor AC 866 Name xs2emf envia gráficos para um arquivo em sintaxe EMF apenas para Windows xs2emfwinnumfilen orientation Parâmetros winnum escalar inteiro filen string o nome do arquivo orientation caractere opcional com valores possíveis p retrato ou l paisagem O valor padrão é p Descrição xs2emf envia os gráficos gravados em uma janela winnum para o arquivo filen no formato EMF Para o formato EMF criamos um arquivo EPS que será convertido para o formato EMFpor pstoedit Exemplos if MSDOS then scf0 plot2d Exportando para EMF xs2emf0fooemf end Ver Também xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig Autor AC 867 Name xs2eps salva gráficos em um arquivo Postscript xs2epswinnumfilen orientation Parâmetros winnum vetor de inteiros ou escalar inteiro filen string nome do arquivo orientation caractere opcional com possíveis valores p retrato ou l paisagem O valor padrão é p Descrição xs2eps salva os gráficos gravados da janela winnum em um arquivo filen em sintaxe Postscript Note que filen não deve ter extensão xs2eps produz um arquivo Postscript encapsulado completo Exemplos scf0 plot2d Exportando para EPS filenamefooeps xs2eps0filename Ver Também figuresize property toprint printfigure xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2pdf xs2svg xs2ps xs2fig xs2emf 868 Name xs2fig envia gráficos para um arquivo em sintaxe FIG xs2figwinnum filen orientation Parâmetros winnum escalar inteiro filen string nome do arquivo orientation caractere opcional com valores possíveis p retrato ou l paisagem O valor padrão é p Descrição xs2fig envia os gráficos gravados da janela winnum para o arquivo filen em formato FIG Para o formato FIG criamos um arquivo EPS que será convertido para o formato FIG por pstoedit Para exportar arquivos FIG o GPL Ghostscript 32bits precisa estar instalado Link para GPL Ghostscript httpwwwghostscriptcomawki Exemplos exemplo simples scf0 plot2d xs2fig0foofig Ver Também xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2emf Autor SK 869 Name xs2gif envia gráficos a um arquivo em sintaxe GIF xs2gifwinnumfilen Parâmetros winnum escalar inteiro ou vetor de inteiros filen string nome do arquivo Descrição xs2gif envia os gráficos gravados da janela window winnum para o arquivo filen em formato GIF Para converter uma seqüência de arquivos GIF em um arquivo GIF animado podese usar o programa convert para ImageMagic httpwwwimagemagickorg Por exemplo se for gerada uma seqüência de arquivos GIF chamada imggif é possível construir um arquivo GIF animado chamado animgif através da seqüência convert delay 10 imggif animgif Exemplos scf0 plot2d Exportando para GIF xs2gif0foogif Ver Também xs2bmp xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf 870 Name xs2jpg envia gráficos a um arquivo em sintaxe JPG xs2jpgwinnumfilen Parâmetros winnum escalar inteiro filen string nome do arquivo Descrição xs2jpg envia os gráficos gravados da janela winnum para o arquivo filen em formato JPG Exemplos scf0 plot2d Exportando para JPG xs2jpg0foojpg Ver Também xs2bmp xs2gif xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf Autor SK 871 Name xs2pdf salva gráficos a um arquivo PDF xs2pdfwinnumfilen orientation Parâmetros winnum escalar inteiro filen string nome do arquivo orientation caractere opcional com possíveis valores p retrato ou l paisagem O valor padrão é p Descrição xs2pdf salva os gráficos gravados da janela winnum em um arquivo filen in PDF syntax em sintaxe Postscript Note que filen não deve ter extensão Exemplos scf0 plot2d Exportando para PDF filenamefoo Sem extensão xs2pdf0filename Ver Também figuresize property toprint printfigure xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2svg xs2ps xs2fig xs2emf 872 Name xs2png envia gráficos a um arquivo em sintaxe PNG xs2pngwinnumfilen Parâmetros winnum escalar inteiro filen string nome do arquivo Descrição xs2png envia os gráficos gravados da janela winnum em um arquivo filen em formato PNG Exemplos scf0 plot2d Exportando para PNG xs2png0foopng Ver Também xs2bmp xs2gif xs2jpg xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf Autor SK 873 Name xs2ppm envia gráficos para um arquivo em sintaxe PPM xs2ppmwinnumfilen Parâmetros winnum vetor de inteiros ou escalar inteiro filen string o nome do arquivo Descrição xs2ppm envia os gráficos gravados em uma janela winnum para o arquivo filen em formato PPM Exemplos scf0 plot2d exportando para PPM xs2ppm0fooppm Ver Também xs2bmp xs2gif xs2jpg xs2png xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf 874 Name xs2ps envia gráficos a um arquivo em sintaxe PS xs2pswinnumfilenorientation Parâmetros winnum vetor de inteiros ou escalar inteiro filen string nome do arquivo orientation caractere opcional com possíveis valores p retrato ou l paisagem O valor padrão é p Descrição xs2ps salva os gráficos gravados da janela winnum em um arquivo filen em sintaxe Postscript Note que filen não deve ter extensão Note que o arquivo Postscript gerado não pode ser impresso diretamente desde requer cabeçalho A função xs2eps pode ser usada diretamente para produzir um arquivo Postscript encapsulado com cabeçalho Exemplos scf0 plot2d exportando para Postscript filenamefoops xs2ps0filename Ver Também figuresize property toprint printfigure xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2fig xs2emf 875 Name xs2svg Salva gráficos em um arquivo SVG xs2svgwinnumfilen orientation Parâmetros winnum vetor de inteiros ou escalar inteiro filen string nome do arquivo orientation caractere opcional com possíveis valores p retrato ou l paisagem O valor padrão é p Descrição xs2svg salva os gráficos gravados da janela winnum em um arquivo filen em sintaxe Postscript Note que filen não deve ter extensão Exemplos scf0 plot2d exportando para SVG filenamefoosvg xs2svg0filename Ver Também figuresize property toprint printfigure xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2ps xs2fig xs2emf Parte VIII Booleanos 877 Name bool2s converte uma matriz de valores booleanos para uma matriz de valores 0 ou 1 bool2sx Parâmetros x um vetor ou matriz de valores booleanos ou uma matriz constante Descrição Se x é uma matriz de valores booleanos bool2sx retorna uma matriz onde os valores true ver dadeiro são substituidos por 1 e os valores false falso são substituidos por 0 Se x é uma matriz padrão bool2sx retorna uma matriz onde os valores nãonulos são substituídos por 1 Exemplos bool2st t f t bool2s23 0 10 1 Ver Também boolean find 878 Name find encontra índices de elementos verdadeiros em uma matriz ou vetor de booleanos iifindx nmax i1i2findx nmax Parâmetros x pode ser um vetor matriz ou hipermatriz de booleanos uma matriz ou hipermatriz padrão nmax um inteiro fornecendo o número máximo de índices a serem retornados o valor padrão é 1 que significa todos Esta opção pode ser usada por eficiência para evitar uma busca por todos os índices ii i1 i2 vetores de índices inteiros ou matrizes vazias Descrição Se x é uma matriz booleana iifindx retorna o vetor de índices i para os quais xi é true verdadeiroSe nenhum elemento true for encontrado retorna uma matriz vazia i1i2findx retorna vetores de índices i1 para linhas e i2 para colunas tais que xi1ni2n ié true verdadeiro Se nenhum elemento true for encontrado retorna matrizes vazias em i1 i2 Se x é uma matriz ou hipermatriz padrão findx é interpretado como findx0 find retorna Exemplos Arand120 wfindA04 Aw wfindA100 Brand120 wfindB042 no máximo dois valores retornados Hrand435 uma hipermatriz ijkfindH09 Hi1j1k1 Ver Também boolean extraction insertion vectorfind Parte IX CACSD 880 Name black diagrama de Black carta de Nichols black slfminfmax step comments black slfrq comments blackfrqdbphi comments blackfrqrepf comments Parâmetros sl lista sistema linear syslin fminfmax reais limites de freqüência frq vetor linha ou matriz freqüências dbphi vetores linhas ou matrizes módulo fase repf vetores linhas ou matrizes resposta de freqüência complexa step real comments string Descrição Diagrama de Black carta de Nichols para um sistema linear sl sl pode ser um sistema SIMO de tempo contínuo ou discreto ver syslin No caso de múltiplas saídas elas são esboçadas com símbolos diferentes As freqüências são dadas pelos limites fminfmax em Hz ou por um vetor linha ou uma matriz para múltiplas saídas frq step é o passo de discretização logarítmica ver calfrq para escolha do valor padrão comments é um vetor de strings legendas dbphi são matrizes de módulos em Db e fases em graus Uma linha para cada resposta repf matriz de números complexos Uma linha para cada resposta Para esboçar o grid de isoganho e isofase de y1y use chart Valores padrões para fmin e fmax são 1d3 1d3 se sl for de tempo contínuo ou 1d3 05sldt freqüência de Nyquist se sl for de tempo discreto Exemplos spoly0s hsyslincs220910s100s2203101s10201 black 881 clfblackh001100 chartlist10 h1hsyslincs2201151s22801s220915s225 clf blackh1h001100h1h chartlist10 Ver Também bode nyquist chart freq repfreq calfrq phasemag 882 Name bode diagrama de Bode bodeslfminfmax step comments bodeslfrq comments bodefrqdbphi comments bodefrq repf comments Parâmetros sl syslin lista sistema linear SISO ou SIMO em tempo contínuo ou discreto fminfmax real limites de freqüência em Hz step real passo logarítmico comments vetor de strings legendas frq vetor linha ou matriz freqüências em Hz uma linha para cada subsistema SISO db vetor linha ou matriz magnitudes em Db um para cada subsistema SISO phi vetor linha ou matriz fases em graus um para cada subsistema SISO repf vetor linha ou matriz de números complexos freqüência de resposta complexa Descrição Diagrama de bode ie magnitude e fase da freqüência de resposta de sl sl pode ser um sistema SIMO de tempo contínuo ou discreto ver syslin No caso de múltiplas saídas elas são esboçadas com símbolos diferentes As freqüências são dadas pelos limites fminfmax em Hz ou por um vetor linha ou uma matriz para múltiplas saídas frq step é o passo de discretização logarítmica ver calfrq para escolha do valor padrão comments é um vetor de strings legendas dbphi são matrizes de módulos em Db e fases em graus Uma linha para cada resposta repf matriz de números complexos Uma linha para cada resposta Valores padrões para fmin e fmax são 1d3 1d3 se sl for de tempo contínuo ou 1d3 05 sldt freqüência de Nyquist se sl for de tempo discreto Discretização automática das freqüências é feita por calfrq Exemplos bode 883 spoly0s hsyslincs220910s100s2203101s10201 tits220910s100s2203101s10201 bodeh001100tit h1hsyslincs2201151s22801s220915s225 clf bodeh1h001100h1h Ver Também black nyquist gainplot repfreq gmargin pmargin calfrq phasemag 884 Name chart carta de Nichols chartflags chartgain flags chartgainphase flags Parâmetros gain vetor de reais ganhos em DB decibel phase vetor de reais fases em graus flags uma lista de no máximo quatro flags sup leg cm cphi sup 1 indica superposição sobre o esboço anterior e 0 indica que nenhuma superposição é feita leg 1 indica que as legendas são impressas 0 indica sem legendas cm número da cor para curvas de ganho cphi número da cor para curvas de fase Descrição Esboça a carta de Nichols curvas de nível de isoganho e isofase dey1y no plano de faseganho chart pode ser utilizado em conjunção a black Os valore padrões para gain e phase são respectivamente 12 8 6 5 4 3 2 14 1 5 025 05 07 1 14 2 23 3 4 5 6 8 12 110 2010160 Exemplos spoly0s hsyslincs220910s100s2203101s10201 blackh001100 chartlist1023 clf h1hsyslincs2201151s22801s220915s225 blackh1h001100h1h setgcadatabounds180 30180 30 aumentando a moldura chartlist10 Ver Também nyquist black 886 Name evans lugar geométrico das raízes Evans evansH kmax Parâmetros H lista sistema linear syslin kmax real ganho máximo desejado para o esboço Descrição Fornece o lugar geométrico das raízes Evans para um sistema linear em estadoespaço ou forma de transferência Hs lista syslin Este é o lugar geométrico das raízes de 1kHs1kNs Ds no plano dos complexos Para uma amostra seleta de ganhos k kmax a parte imaginária das raízes de DskNs é esboçada versus a parte real Para obter o ganho num dado ponto do lugar geométrico você pode simplesmente executar a seguinte instrução k1realhornerh1ilocate1 e clicar no ponto desejado sobre lugar geométrico das raízes Se as coordenadas dos pontos selecionados estão no vetor de reais 2 x 1 Plocate1 este k resolve a equação kNw Dw 0 com wP1iP21 iP Exemplos Hsyslinc352poly5spoly002000200251sc evansH100 P30548543 88491842i Pponto selecionado k1realhornerHP NsHnumDsHden rootsDskNs contém P como raiz particular outro clfspoly0sn1s drealpoly1 2 i is evansnd100 clfnrealpoly01i 01i10s evansnd80 Ver Também kpure krac2 locate 887 Name gainplot esboço de magnitude gainplotslfminfmax step comments gainplotfrqdbphi comments gainplotfrq repf comments Parâmetros sl lista sistema linear syslin SIMO fminfmax escalares reais intervalo de freqüência step real passo de discretização escala logarítmica comments string frq matriz freqüências linha por linha dbphi matrizes magnitudes e fases correspondentes a frq repf matriz de complexos Uma linha para cada resposta de freqüência Descrição É o mesmo que Bode mas esboça apenas a magnitude Exemplos spoly0s hsyslincs220910s100s2203101s10201 gainploth001100s220910s100s2203101s10201 clf h1hsyslincs2201151s22801s220915s225 gainploth1h001100h1h Ver Também bode black nyquist freq repfreq gmargin pmargin 888 Name mcircle esboça os contornos de isoganho y1y plano complexo mcircle mcirclegain Parâmetros gain vetor de ganhos em DB decibel O valor padrão é gain 12 8 6 5 4 3 2 14 1 5 025 05 07 1 14 2 23 3 4 5 6 8 12 Descrição mcircle desenha os contornos de isoganho fornecidos pelo argumento gain no plano complexo ReIm O valor padrão para gain é 12 8 6 5 4 3 2 14 1 5 025 05 07 1 14 2 23 3 4 5 6 8 12 mcircle é utilizado com nyquist Exemplos Exemplo 1 spoly0s hsyslincs220910s100s2203101s10201 nyquisth001100s220910s100s2203101s10201 mcircle Exemplo 2 xbasc h1hsyslincs2201151s22801s220915s225 nyquisth1h001100h1h mcircle8 6 4 Ver Também nyquist chart black Autor SSteer 889 Name nyquist diagrama de Nyquist nyquist slfminfmax step comments nyquist sl frq comments nyquistfrqdbphi comments nyquistfrq repf comments Parâmetros sl syslin sistema linear SIMO em tempo contínuo ou discreto fminfmax reais limites de freqüência em Hz step real passo de discretização logarítmica comments vetor de strings legendas frq vetor linha ou matriz freqüências em Hz um linha para cada saída de sl dbphi vetores linhas ou matrizes de módulo em Db e fases uma linha para cada saída de sl repf vetor linha ou matriz de números complexos freqüência de resposta complexa uma para cada saída de sl Descrição Diagrama de Nyquist ie parte imaginária versus parte real da freqüência de resposta de sl Para sistmeas de tempo contínuo sl2ipiw é esboçado Para sistemas de tempo discreto ou sistemas discretizados slexp2ipiwfd é utilizado fd1 para sistemas de tempo discreto e fdsldt para sistemas discretizados sl para sistemas discretizados syslin No caso de múltiplas saídas elas são esboçadas com símbolos diferentes As freqüências são dadas pelos limites fminfmax em Hz ou por um vetor linha ou uma matriz para múltiplas saídas frq step é o passo de discretização logarítmica ver calfrq para escolha do valor padrão comments é um vetor de strings legendas dbphi são matrizes de módulos em Db e fases em graus Uma linha para cada resposta repf é uma matriz de números complexos Uma linha para cada resposta Valores padrões para fmin e fmax são 1d3 1d3 se sl for de tempo contínuo 1d3 05 sldt freqüência de Nyquist se sl for de tempo discreto Discretização automática das freqüências é feita por calfrq nyquist 890 Exemplos clf spoly0s hsyslincs220910s100s2203101s10201 comms220910s100s2203101s10201 nyquisth001100comm h1hsyslincs2201151s22801s220915s225 clf nyquisth1h001100h1h clfnyquisth1h Ver Também bode black calfrq freq repfreq phasemag 891 Name routht tabela de Routh rrouthth k Parâmetros h matriz quadrada de razões de polinômios Descrição rrouththk computa a tabela de Routh do denominador do sistema descrito pela matriz de transferência SISO h com a resposta pelo ganho k se kpoly0k teremos uma matriz de polinômios com variável livre k expressão formal da tabela de Routh 892 Name sgrid esboça linhas de grid de um splano sgrid sgridnew sgridzetawn color Descrição Usado em conjunto com evans esboça linhas de taxa de amortecimento constante zeta e freqüência natural wn sgrid adiciona um grid sobre uma raiz do splano contínuo existente com valores padrões para zeta e wn sgridnew limpa a tela de gráficos e então esboça um grid de splano padrão sgridzetawn color é o mesmo que sgrid mas utiliza a taxa de amortecimento e a freqüência natural fornecidas Exemplos Hsyslinc352poly5spoly002000200251sc evansH100 sgrid sgrid0627 Ver Também evans 893 Name zgrid esboçode um zgrid zgrid Descrição Esboça as linhas de grid de um Zplano linhas de fator constante de amortecimento zeta e freqüência natural Wn são esboçadas dentro do círculo unitário do Zplano Curvas de isofreqüência são exibidas em freqüênciapasso no intervalo 005 O limite superior corresponde à freqüência de Shannon 1dt 2f Ver Também frep2tf freson 894 Name abcd statespace matrices ABCDabcdsl Parameters sl linear system syslin list in statespace or transfer form ABCD real matrices of appropriate dimensions Description returns the ABCD matrices from a linear system Sl Utility function For transfer matrices Sl is converted into statespace form by tf2ss The matrices ABCD are the elements 2 to 5 of the syslin list Sl ie ABCD Sl25 Examples Adiag123B111C222 syssyslincABC sysA sysC A1B1C1D1abcdsys A1 systfss2tfsys abcdabcdsystf speca cbCB cabCAB See Also syslin ssrand 895 Name abinv AB invariant subspace XdimsFUkZabinvSysalphabetaflag Parameters Sys syslin list containing the matrices ABCD alpha optional real number or vector possibly complex location of closed loop poles beta optional real number or vector possibly complex location of closed loop poles flag optional character string ge default or st or pp X orthogonal matrix of size nx dim of state space dims integer row vector dimsdimRdimVgdimVnocnos with dimRdimVgdimVnocnos If flagst resp pp dims has 4 resp 3 components F real matrix state feedback k integer normal rank of Sys Z nonsingular linear system syslin list Description Output nulling subspace maximal unobservable subspace for Sys linear sys tem defined by a syslin list containing the matrices ABCD of Sys The vector dimsdimRdimVgdimVnocnos gives the dimensions of subspaces defined as columns of X according to partition given below The dimV first columns of X ie VX1dimV span the ABinvariant subspace of Sys ie the unobservable subspace of ABFCDF dimVnx iff C1DX The dimR first columns of X ie RX1dimR spans the controllable part of Sys in V dimRdimV dimR0 for a left invertible system R is the maximal controllability subspace of Sys in kernelC The dimVg first columns of X spans Vgmaximal ABstabilizable subspace of Sys dimRdimVgdimV F is a decoupling feedback for XVX2 X2XdimV1nx one has X2A BFV0 and CDFV0 The zeros od Sys are given by X0XdimR1dimV specX0ABFX0 ie there are dimVdimR closedloop fixed modes abinv 896 If the optional parameter alpha is given as input the dimR controllable modes of ABF in V are set to alpha or to alpha1 alpha2 alpha can be a vector real or complex pairs or a real number Default value alpha1 If the optional real parameter beta is given as input the nocdimV controllable modes of ABF outside V are set to beta or beta1beta2 Default value beta1 In the XU bases the matrices XABFXXBUCDFXDU are displayed as follows A11 B11 0A22 0 00A33 0 000A44 0 B42 0000A55 0 0 00000A66 0 0 000 0 D2 where the Xpartitioning is defined by dims and the Upartitioning is defined by k A11 is dimR x dimR and has its eigenvalues set to alphais The pair A11B11 is controllable and B11 has nuk columns A22 is a stable dimVgdimR x dimVgdimR matrix A33 is an unstable dimVdimVg x dimVdimVg matrix see stility A44 is nocdimV x nocdimV and has its eigenvalues set to betais The pair A44B42 is controllable A55 is a stable nosnoc x nosnoc matrix A66 is an unstable nxnos x nxnos matrix see stility Z is a column compression of Sys and k is the normal rank of Sys ie SysZ is a columncompressed linear system k is the column dimensions of B42B52B62 and D2 B42B52B62D2 is full column rank and has rank k If flagst is given a five blocks partition of the matrices is returned and dims has four components If flagpp is given a four blocks partition is returned In case flagge one has dimsdimRdimVgdimVdimVnc2dimVns2 where nc2 resp ns2 is the dimension of the controllable resp stabilizable pair A44B42 resp A440A55 B420 In case flagst one has dimsdimRdimVgdimVgncdimVgns and in case flagpp one has dimsdimRdimRncdimRns nc resp ns is here the di mension of the controllable resp stabilizable subspace of the blocks 3 to 6 resp 2 to 6 This function can be used for the exact disturbance decoupling problem DDPS Find uFxRdFRxd which rejects Qd and stabilizes the plant xdot AxBuQd y CxDuTd DDPS has a solution if ImQ is included in Vg ImB and stabilizability assumption is satisfied Let GXdimVg1 left annihilator of Vg ie GVg0 B2GB Q2GQ DDPS solvable iff B2DR Q2T 0 has a solution The pair FR is the solution with Foutput of abinv ImQ2 is in ImB2 means rowcompression of B2rowcompression of Q2 Then CsIABF1DQBR 0 GQBR0 abinv 897 Examples nu3ny4nx7 nrt2ngt3ng03nvt5rk2 flaglistonnrtngtng0nvtrk Sysssrandnynunxflagmyalpha1mybeta2 XdimsFUkZabinvSysmyalphamybeta ABCDabcdSysdimVdims3dimRdims1 VX1dimVX2XdimV1nx X2ABFV CDFV X0XdimR1dimV specX0ABFX0 trzerosSys specABF nr2 evals at 1 and nocdimV2 evals at 2 cleanss2tfSysZ 2nd Example nx6ny3nu2 Adiag16A227A559B120304050000 CzerosnynyeyenynyD010203 slsyslincABCDslss2ssslrand66rand22 ABCDabcdsl The matrices of sl myalpha1mybeta2 XdimsFUkZabinvslmyalphamybetadimVgdims2 cleanXABFX cleanXBU cleanCDFX cleanDU GXdimVg1 B2GBnd3 RrandnundQ2TB2DR psizeG1Q2Q2T1pTQ2Tp1 QGQ2 a valid QT since GBDR GQT is zero closedsyslincABFQBRCDFTDR closed loop dy ss2tfclosed Closed loop is zero specclosedA The plant is not stabilizable nsncWsl1stilitysl ABCDabcdsl1AA1ns1nsBB1nsCC1ns slnewsyslincABCD Now stabilizable FnewstabilslnewAslnewB11 slnewAslnewAslnewBFnew slnewCslnewCslnewDFnew XdimsFUkZabinvslnewmyalphamybetadimVgdims2 ABCDabcdslnew GXdimVg1 B2GBnd3 RrandnundQ2TB2DR psizeG1Q2Q2T1pTQ2Tp1 QGQ2 a valid QT since GBDR GQT is zero closedsyslincABFQBRCDFTDR closed loop dy ss2tfclosed Closed loop is zero specclosedA abinv 898 See Also cainv stility ssrand ss2ss ddp Authors FD 899 Name arhnk Hankel norm approximant slmarhnkslordtol Parameters sl linear system syslin list ord integer order of the approximant tol threshold for rank determination in equil1 Description computes slm the optimal Hankel norm approximant of the stable continuoustime linear system sl with matrices ABCD Examples Adiag12345Brand51Crand15 slsyslincABC slapproxarhnksl2 nkWhankelsvslnk nkredWredhankelsvslapproxnkred See Also equil equil1 hankelsv 900 Name arl2 SISO model realization by L2 transfer approximation harl2yden0n imp harl2yden0n impall dennumerrarl2yden0n imp dennumerrarl2yden0n impall Parameters y real vector or polynomial in z1 it contains the coefficients of the Fouriers series of the rational system to approximate the impulse response den0 a polynomial which gives an initial guess of the solution it may be poly1zc n integer the degree of approximating transfer function degree of den imp integer in 012 verbose mode h transfer function numden or transfer matrix column vector when flag all is given den polynomial or vector of polynomials contains the denominators of the solutions num polynomial or vector of polynomials contains the numerators of the solutions err real constant or vector the l2error achieved for each solutions Description dennumerrarl2yden0n imp finds a pair of polynomials num and den such that the transfer function numden is stable and its impulse response approximates with a minimal l2 norm the vector y assumed to be completed by an infinite number of zeros If yz y11zy21z2 yny1zny then l2norm of numden yz is err n is the degree of the polynomial den The numden transfer function is a L2 approximant of the Fouriers series of the rational system Various intermediate results are printed according to imp dennumerrarl2yden0n impall returns in the vectors of polynomials num and den a set of local optimums for the problem The solutions are sorted with increasing errors err In this case den0 is already assumed to be poly1zc Examples arl2 901 vones120 clf plot2d1enn0vzeros8012051 10510015 dnearl2vpoly1zc1 plot2d1enn0ldivnd1002000 dnearl2vd3 plot2d1enn0ldivnd1003000 dnearl2vd8 plot2d1enn0ldivnd1005000 dnearl2vpoly1zc4all plot2d1enn0ldivn1d110010000 See Also ldiv imrep2ss timeid armax frep2tf 902 Name arma Scilab arma library Description Armax processes can be coded with Scilab tlist of type ar armac is used to build Armax scilab object An ar tlist contains the fields abdnynusig armac this function creates a Scilab tlist which code an Armax process Az1y Bz1u Dz1siget ararmac1234111sig ara ans 1 2 arsig ans 1 armapar out Display the armax equation associated with ar armappar out Display the armax equation associated with ar using polynomial matrix display ABDarmap2par extract polynomial matrices from ar representation armax is used to identify the coefficients of a ndimensional ARX process Az1y Bz1u siget armax1 armax1 is used to identify the coefficients of a 1dimensional ARX process Az1y Bz1u Dz1siget arsimul armax trajectory simulation narsimul armax simulation using rtitr odedi Simple tests of ode and arsimul Tests the option discret of ode prbsa pseudo random binary sequences generation reglin Linear regression Example arma 903 Example extracted from the demo arma3demsce in the cacsd module Spectral power estimation form Sawaragi et all m 18 a 1131361440110919083527 b 000131370023543010775003516 u rand11000n z arsimulab00u Using macro mese smfrmesezm The theorical result function gxgxxzab w expi2piz04 gx absbw2absaw2 endfunction res for xfr res res gxxxab end using armax estimation of order 44 its a bit tricky because we are not supposed to know the order arclalbsigresidarmax44zu res1 for xfr res1 res1 gxxxla1lb1 end visualization of the results plot2dfrfrfr20log10smsm120log10resres120log10res1res11211 legendUsing macro meseTheoretical valueArma identification xtitleSpectral powerfrequencyspectral estimate Authors JPC 904 Name arma2p extract polynomial matrices from ar representation ABDarma2par Parameters ABD three polynomial matrices ar Scilab ar tlist for arma storage see armac Description this function extract polynomial matrices ABD from an armax description Examples a1285127170865eye22 b011111 d10702eye22 sigeye22 ararmacabd21sig extract polynomial matrices from ar representation ABDarma2par See Also arma armax armax1 arsimul armac 905 Name armac Scilab description of an armax process ararmacabdnynusig Parameters aIda1ar is a matrix of size nyrny bb0bs is a matrix of size nys1nu dIdd1dp is a matrix of size nypny ny dimension of the output y nu dimension of the output u sig a matrix of size nyny Description This function creates a description as a tlist of an ARMAX process ar is defined by artlistarabdnynusigabdnynusig and thus the coefficients of ar can be retrieved by eg ara Examples a1285127170865eye22 b011111 d10702eye22 sigeye22 ararmacabd21sig extract polynomial matrices from ar representation ABDarma2par See Also arma armax armax1 arsimul arma2p tlist 906 Name armax armax identification arclalbsigresidarmaxrsyub0fprf Parameters y output process ynyn ny dimension of y n sample size u input process unun nu dimension of u n sample size r and s autoregression orders r 0 et s 1 b0f optional parameter Its default value is 0 and it means that the coefficient b0 must be identified if bof1 the b0 is supposed to be zero and is not identified prf optional parameter for display control If prf 1 the default value a display of the identified Arma is given arc a Scilab arma object see armac la is the listaaetaaeta la a in dimension 1 where eta is the estimated standard deviation aIda1a2ar where each ai is a matrix of size nyny lb is the listbbetbbetb lb b in dimension 1 where etb is the estimated standard deviation bb0bs where each bi is a matrix of size nunu sig is the estimated standard deviation of the noise and resid siget0 Description armax is used to identify the coefficients of a ndimensional ARX process Az1y Bz1u siget where et is a ndimensional white noise with variance I sig an nxn matrix and Az and Bz Az 1a1zarzr r0 Az1 Bz b0b1zbs zs s1 Bz0 for the method see Eykhoff in trends and progress in system identification page 96 with ztyt1ytrututs and coef a1 arb0bs we can write yt coef zt siget and the algorithm minimises sumt1N yt coefzt2 where t0maximaxirs11 armax 907 Examples Ex1 Arma model yt 02ut1001et1 ny1nu1sig001 Armaarmac100201nynusig defining the above arma model urand11000normal a random input sequence u yarsimulArmau simulation of a y output sequence associated with u Armaestarmax01yu Identified model given u and y AcoeffArmaesta Coefficients of the polynomial Ax BcoeffArmaestb Coefficients of the polynomial Bx DcoeffArmaestd Coefficients of the polynomial Dx AxBxDxarma2pArmaest Results in polynomial form Ex2 Arma1 yt 08yt1 02yt2 siget ny1nu1sig0001 First step simulation the Arma1 model for that we define Arma2 yt 08yt1 02yt2 sigut with normal deviates for ut Arma2armac10802sig0nynu0 Definition of the Arma2 arma model a model with Bsig and without noise urand110000normal An input sequence for Arma2 yarsimulArma2u y output of Arma2 with input u can be seen as output of Arma1 Second step identification We look for an Arma model yt a1yt1 a2 yt2 siget Arma1estarmax21y ABDarma2pArma1est See Also imrep2ss timeid arl2 armax frep2tf Authors JPh Chancelier 908 Name armax1 armax identification arcresidarmax1rsqyu b0f Parameters y output signal u input signal rsq auto regression orders with r 0 s 1 b0f optional parameter Its default value is 0 and it means that the coefficient b0 must be identified if bof1 the b0 is supposed to be zero and is not identified arc is tlist with type ar and fields a b d ny nu sig a is the vector 1a1ar b is the vector b0bs d is the vector 1d1dq sig resid sigechap1 Description armax1 is used to identify the coefficients of a 1dimensional ARX process Az1y Bz1u Dz1siget et is a 1dimensional white noise with variance 1 Az 1a1zarzr r0 Az1 Bz b0b1zbs zs s1 Bz0 Dz 1d1zdqzq q0 Dz1 for the method see Eykhoff in trends and progress in system identification page 96 with ztyt1ytrut utset1etq and coef a1arb0bsd1dq armax1 909 yt coef zt siget a sequential version of the AR estimation where eti is replaced by an estimated value is used RLLS With q0 this method is exactly a sequential version of armax Important notice In Scilab versions up to 412 the returned value in arcsig is the square of sig square To be conform with the help the display of arma models and the armax function starting from Scilab50 version the returned arcsig is sig Authors JPhC 910 Name arsimul armax simulation zarsimulabdsiguupypep zarsimularuupypep Parameters ar an armax process See armac a is the matrix Ida1ar of dimension nr1n b is the matrix b0bs of dimension ns1m d is the matrix Idd1dt of dimension nt1n u is a matrix mN which gives the entry ujuj sig is a nn matrix ek is an ndimensional Gaussian process with variance I up yp optional parameter which describe the past up u0u1us1 yp y0y1yr1 ep e0e1er1 if they are omitted the past value are supposed to be zero z zy1yN Description simulation of an ndimensional armax process Az1 zk Bz1uk Dz1sigek Az Ida1zarzr r0 AzId Bz b0b1zbs zs s1 Bz Dz Idd1zdt zt t0 DzId z et e are in Rn et u in Rm Method a statespace representation is constructed and ode with the option discr is used to compute z Authors JPhC 911 Name augment augmented plant PraugmentG PraugmentGflag1 PraugmentGflag1flag2 Parameters G linear system syslin list the nominal plant flag1 one of the following upper case character string S R T SR ST RT SRT flag2 one of the following character string o stands for output this is the default value or i stands for input P linear system syslin list the augmented plant r 1x2 row vector dimension of P22 G Description If flag1SRT default value returns the full augmented plant I G S 0 I R P 0 G T I G S R T refer to the first three block rows of P respectively If one of these letters is absent in flag1 the corresponding row in P is missing If G is given in statespace form the returned P is minimal P is calculated by I000I0 I0II00IG0II0 The augmented plant associated with input sensitivity functions namely I I S input sensitivity G G R Ginput sensitivity P 0 I T KGinput sensitivity G G is obtained by the command PraugmentGflagi For statespace G this P is calcu lated by II000I000I0IGII and is thus generically minimal augment 912 Note that weighting functions can be introduced by leftmultiplying P by a diagonal system of appro priate dimension eg P sysdiagW1W2W3eyeGP Sensitivity functions can be calculated by lft One has For output sensitivity functions PraugmentPSRT lftPrKinveyeGKKinveyeGKGKinveyeGK For input sensitivity functions PraugmentPSRTi lftPrKinveyeKGGinveyeKGKGinveyeGK Examples Gssrand232 Plant Kssrand322 Compensator PraugmentGT TlftPrK Complementary sensitivity function Ktfss2tfKGtfss2tfG Ttfss2tfTT11Ttf11 OloopGtfKtf TnOloopinveyeOloopOloop cleanT11Tn11 PiraugmentGTi T1lftPirKT1tfss2tfT1 Input Complementary sensitivity function OloopKtfGtf T1nOloopinveyeOloopOloop cleanT1tf11T1n11 See Also lft sensi 913 Name balreal balanced realization slb U balrealsl Parameters slslb linear systems syslin lists Description Balanced realization of linear system slABCD sl can be a continuoustime or discretetime statespace system sl is assumed stable slbinvUAU invUB CU D is the balanced realization slb is returned as a syslin list Examples Adiag12345Brand52Crand15 slsyslincABC slbUbalrealsl Wccleanctrgramslb W0cleanobsgramslb See Also ctrgram obsgram hankelsv equil equil1 914 Name bilin general bilinear transform sl1bilinslv Parameters slsl1 linear systems syslin lists v real vector with 4 entries vabcd Description Given a linear system in state space form slsyslindomABCD syslin list sl1bilinslv returns in sl1 a linear system with matrices A1B1C1D1 such that the transfer function H1sC1invseyeA1B1D1 is obtained from HzCinvzeyeABD by replacing z by zasbcsd One has wbilinbilinwabcddbca Examples spoly0szpoly0z wssrand113 wtfss2tfwv2314av1bv2cv3dv4 hornerwtfazbczdss2tfbilinwabcd cleanss2tfbilinbilinwabcddbcawtf See Also horner cls2dls 915 Name bstap hankel approximant QbstapSl Parameters sl linear system syslin list assumed continuoustime and antistable Q best stable approximation of Sl syslin list Description Computes the best approximant Q of the linear system Sl where T is the Hinfinity norm of the Hankel operator associated with Sl See Also syslin 916 Name cainv Dual of abinv XdimsJYkZcainvSlalfabetaflag Parameters Sl syslin list containing the matrices ABCD alfa real number or vector possibly complex location of closed loop poles beta real number or vector possibly complex location of closed loop poles flag optional character string ge default or st or pp X orthogonal matrix of size nx dim of state space dims integer row vector dimsnd1nu1dimSdimSgdimN 5 entries nondecreasing orderIf flagst resp pp dims has 4 resp 3 components J real matrix output injection Y orthogonal matrix of size ny dim of output space k integer normal rank of Sl Z nonsingular linear system syslin list Description cainv finds a bases XY of state space and output space resp and output injection matrix J such that the matrices of Sl in bases XY are displayed as A11 0A22 XAJCX 00A33 XBJD 000A44 0 0000A55 0 00000A66 0 YCX 00C13 YD 00000C26 0 The partition of X is defined by the vector dimsnd1nu1dimSdimSgdimN and the par tition of Y is determined by k cainv 917 Eigenvalues of A11 nd1 x nd1 are unstable Eigenvalues of A22 nu1nd1 x nu1nd1 are stable The pair A33 C13 dimSnu1 x dimSnu1 k x dimSnu1 is observable and eigenvalues of A33 are set to alfa Matrix A44 dimSgdimS x dimSgdimS is unstable Matrix A55 dimNdimSgdimN dimSg is stable The pair A66C26 nxdimN x nxdimN is observable and eigenvalues of A66 set to beta The dimS first columns of X span S smallest CA invariant subspace which contains ImB dimSg first columns of X span Sg the maximal complementary detectability subspace of Sl The dimN first columns of X span the maximal complementary observability subspace of Sl dimS0 if BkerD0 If flagst is given a five blocks partition of the matrices is returned and dims has four com ponents If flagpp is given a four blocks partition is returned see abinv This function can be used to calculate an unknown input observer DDEP dotxA x Bu Gd y Cx observation z Hx zvariable to be estimated ddisturbance Find dotw Fw Ey Ru such that zhat Mw Ny zHx goes to zero at infinity Solution exists iff Ker H contains SgACG inter KerC assuming detectability ie H is such that For any W which makes a column compression of Xp1dimSgC with XpX and XdimsJYkZcainvsyslincAGC Xp1dimSgCW 0 one has HW 0 with at least as many aero columns as above See Also abinv dtility uiobserver 918 Name calfrq frequency response discretization frqbndssplitcalfrqhfminfmax Parameters h Linear system in state space or transfer representation see syslin fminfmax real scalars min and max frequencies in Hz frq row vector discretization of the frequency interval bnds vector Rmin Rmax Imin Imax where Rmin and Rmax are the lower and upper bounds of the frequency response real part Imin and Imax are the lower and upper bounds of the frequency response imaginary part split vector of frq splitting points indexes Description frequency response discretization frq is the discretization of fminfmax such that the peaks in the frequency response are well represented Singularities are located between frqsplitk1 and frqsplitk for k1 Examples spoly0s hsyslincs220910s100s2203101s10201 h1hsyslincs2201151s22801s220915s225 f1bndssplcalfrqh10011000 rfrepfreqh1f1 plot2drealrfimagrf See Also bode black nyquist freq repfreq logspace 919 Name canon canonical controllable form AcBcUindcanonAB Parameters AcBc canonical form U current basis square nonsingular matrix ind vector of integers controllability indices Description gives the canonical controllable form of the pair AB AcinvUAU BcinvUB The vector ind is made of the epsilonis indices of the pencil sI A B decreasing order For example with ind32 Ac and Bc are as follows 10000 0 Ac 01000 Bc0 00010 0 If AB is controllable by an appropriate choice of F the entries of AcBcF can be arbitrarily set to desired values pole placement Examples A12345 10000 01000 67890 00010 B12 00 00 21 00 Xrand55AXAinvXBXB Controllable pair AcBcUindcanonAB Two indices ind32 index1for k1sizeind1indexindex1sumind1kend AcstarAcindexBcstarBcindex spoly0s p1s32s25s3p2s5s3 p1 and p2 are desired closedloop polynomials with degrees 32 c1coeffp1c1c1111c2coeffp2c2c2111 canon 920 Acstardesiredc100000c2 Acstardesiredindex is companion matrix with char polp1p2 FBcstarAcstardesiredAcstar Feedbak gain AcBcF Companion form specABFU FU is the gain matrix in original basis See Also obsvmat contmat ctrgram contrss ppol contr stabil Authors FD 921 Name ccontrg central Hinfinity controller KccontrgPrgamma Parameters P syslin list linear system in statespace representation r 1x2 row vector dimension of the 22 part of P gamma real number Description returns a realization K of the central controller for the general standard problem in statespace form Note that gamma must be gopt ouput of gamitg P contains the parameters of plant realization ABCD syslin list with B B1 B2 C C1 D D11 D12 C2 D21 D22 r1 and r2 are the dimensions of D22 rows x columns See Also gamitg hinf Authors P Gahinet INRIA 922 Name cls2dls bilinear transform sl1cls2dlsslT fp Parameters slsl1 linear systems syslin lists T real number the sampling period fp prevarping frequency in hertz Description given slABCD syslin lista continuous time system cls2dls returns the sampled sys tem obtained by the bilinear transform s2Tz1z1 Examples spoly0szpoly0z slsyslincs1s25s2 Continuoustime system in transfer form slsstf2sssl Now in statespace form sl1cls2dlsslss02 sl1 output of cls2dls sl1tss2tfsl1 Converts in transfer form sl2hornersl202z1z1 Compare sl2 and sl1 See Also horner 923 Name colinout innerouter factorization InnXGbarcolinoutG Parameters G linear system syslin list ABCD Inn inner factor syslin list Gbar outer factor syslin list X rowcompressor of G syslin list Description Innerouter factorization and column compression of lxp G ABCD with lp G is assumed to be fat lp without zero on the imaginary axis and with a D matrix which is full row rank G must also be stable for having Gbar stable Dual of rowinout See Also syslin rowinout 924 Name colregul removing poles and zeros at infinity StmpWscolregulSlalfabeta Parameters SlStmp syslin lists alfabeta reals new pole and zero positions Description computes a prefilter Ws such that StmpSlWs is proper and with full rank D matrix Poles at infinity of Sl are moved to alfa Zeros at infinity of Sl are moved to beta Sl is a assumed to be a left invertible linear system syslin list in statespace representation with possibly a polynomial D matrix See Also invsyslin inv rowregul rowshuff Authors F D R N 925 Name contfrm transfer to controllable statespace slcontfrmNUMden Parameters NUM polynomial matrix den polynomial sl syslin list slABCD Description controllable statespace form of the transfer NUMden Examples spoly0sNUM1ssdens25s1 slcontfrmNUMden slssss2tfsl Compare with NUMden See Also tf2ss canon contr 926 Name contmat controllability matrix CccontmatAB Cccontmatsl Parameters ab two real matrices of appropriate dimensions sl linear system syslin list Description contmat returns the controllability matrix of the pair AB resp of the system slABCD CcB AB A2 B An1 B See Also ctrgram contr canon stility 927 Name contr controllability controllable subspace staircase ncontrAB tol nUcontrAB tol nUindVAcBccontrABtol Parameters A B real matrices tol tolerance parameter n dimension of controllable subspace U orthogonal change of basis which puts AB in canonical form V orthogonal matrix change of basis in the control space Ac block Hessenberg matrix AcUAU Bc is UBV ind p integer vector associated with controllability indices dimensions of subspaces B B ABind1ind1ind2 Description nUcontrABtol gives the controllable form of an AB pairdxdt A x B u or xn1 A xn b un The n first columns of U make a basis for the controllable subspace If VU1n then VAV and VB give the controllable part of the AB pair The pair Bc Ac is in staircase controllable form B sIA 1 11 A sIA 21 22 UBVsI UAU 0 0 A sIA pp1 pp 0 0 0 sIA p1p1 contr 928 Reference Slicot library see ab01od in SCImodulescacsdsrcslicot Examples Wssrand235listco3 cont subspace has dim 3 AWABWB nUcontrABn A1UAU specA1n1n1 uncontrollable modes specABrand35 See Also canon contmat unobs stabil stility 929 Name contrss controllable part slccontrsssl tol Parameters sl linear system syslin list tol is a threshold for controllability see contr default value is sqrteps Description returns the controllable part of the linear system sl ABCD in statespace form Examples A1102B10C11slsyslincABC Non minimal slccontrsssl sl1ss2tfslsl2ss2tfslc Compare sl1 and sl2 See Also contmat ctrgram contfrm contr 930 Name copfac right coprime factorization NMXTYTcopfacG polfpolctol Parameters G syslin list continuoustime linear system polf polc respectively the poles of XT and YT and the poles of n and M default values 1 tol real threshold for detecting stable poles default value 100eps NMXTYT linear systems represented by syslin lists Description NMXTYTcopfacGpolfpolctol returns a right coprime factorization of G G NM1 where N and M are stable proper and right coprime ie N M leftinvertible with stability XT and YT satisfy XT YTM N eye Bezout identity G is assumed stabilizable and detectable See Also syslin lcf 931 Name csim simulation time response of linear system y xcsimutslx0 tol Parameters u function list or string control t real vector specifying times with t1 is the initial time x0xt1 sl list syslin y a matrix such that yyti i1n x a matrix such that xxti i1n tol a 2 vector atol rtol defining absolute and relative tolerances for ode solver see ode Description simulation of the controlled linear system sl sl is assumed to be a continuoustime system repre sented by a syslin list u is the control and x0 the initial state y is the output and x the state The control can be 1 a function inputsut 2 a list listutparameter1parametern such that inputsuttparameter1parametern ut is a function 3 the string impuls for impulse response calculation here sl is assumed SISO without direct feed through and x00 4 the string step for step response calculation here sl is assumed SISO without direct feed through and x00 5 a vector giving the values of u correponding to each t value Examples spoly0srandseed0wssrand113wAwA2eye t00055 impulsew step s w clf0xsetwindow0xselect plot2dttcsimstepttf2sssw0t clf1xsetwindow1xselect csim 932 plot2dttcsimimpulsetw0t stepw impulse s1 w clf3xsetwindow3xselect plot2dttcsimsteptw0t clf4xsetwindow4xselect plot2dttcsimimpulsettf2ss1sw0t input defined by a time function deffuinputtuabssint clfplot2dttcsiminputtw0t See Also syslin dsimul flts ltitr rtitr ode impl 933 Name ctrgram controllability gramian GcctrgramAB dom Gcctrgramsl Parameters AB two real matrices of appropriate dimensions dom character string c default value or d sl linear system syslin list Description Controllability gramian of AB or sl a syslin linear system dom character string giving the time domain d for a discrete time system and c for continuous time default case Examples Adiag123Brand32 WcctrgramAB Urand33A1UAUB1UB Wc1ctrgramA1B1 Not invariant See Also equil1 obsgram contr contmat contfrm contrss Authors S Steer INRIA 1988 934 Name dbphi frequency response to phase and magnitude representation dbphi dbphirepf Parameters dbphi vector of gains db and phases degrees repf vector of complex frequency response Description dbk is the magnitude of repfk expressed in dB ie dbk20logabsrepfk log10 and phik is the phase of repfk expressed in degrees See Also repfreq bode 935 Name dcf double coprime factorization NMXYNTMTXTYTdcfGpolfpolctol Parameters G syslin list continuoustime linear system polf polc respectively the poles of XT and YT and the poles of N and M default values 1 tol real threshold for detecting stable poles default value 100eps NMXTYTNTMTXY linear systems represented by syslin lists Description returns eight stable systems NMXYNTMTXTYT for the doubly coprime factorization G must be stabilizable and detectable See Also copfac 936 Name ddp disturbance decoupling ClosedFGddpSyszeroedB1D1 ClosedFGddpSyszeroedB1D1flagalfabeta Parameters Sys syslin list containing the matrices AB2CD2 zeroed integer vector indices of outputs of Sys which are zeroed B1 real matrix D1 real matrix B1 and D1 have the same number of columns flag string ge or st default or pp alpha real or complex vector loc of closed loop poles beta real or complex vector loc of closed loop poles Description Exact disturbance decoupling output nulling algorithm Given a linear system and a subset of out puts z which are to be zeroed characterize the inputs w of Sys such that the transfer function from w to z is zero Sys is a linear system AB2CD2 with one input and two outputs ie Sys uzy part the following system defined from Sys and B1D1 xdot A x B1 w B2 u z C1 x D11 w D12 u y C2 x D21 w D22 u outputs of Sys are partitioned into zy where z is to be zeroed ie the matrices C and D2 are CC1C2 D2D12D22 C1Czeroed D12D2zeroed The matrix D1 is partitioned similarly as D1D11D21 with D11D1zeroed The control is uFxGw and one looks for matriced FG such that the closed loop system wz given by xdot AB2F x B1 B2G w z C1D12F x D11D12G w has zero transfer transfer function ddp 937 flaggeno stability constraints flagst look for stable closed loop system AB2F sta ble flagpp eigenvalues of AB2F are assigned to alfa and beta Closed is a realization of the wy closed loop system xdot AB2F x B1 B2G w y C2D22F x D21D22G w Stability resp pole placement requires stabilizability resp controllability of AB2 Examples randseed0nx6nz3nu2ny1 Adiag16A227A559B2120304050000 C1zerosnznzeyenznzD12010203 Sys12syslincAB2C1D12 CC1randnynxD2D12randnysizeD122 SyssyslincAB2CD2 AB2C1D12abcdSys12 The matrices of Sys12 myalpha1mybeta2flagge XdimsFUkZabinvSys12myalphamybetaflag cleanXAB2FX cleanXB2U cleanC1D12FX cleanD12U Calculating an adhoc B1D1 G1randsizeB223 B1B2G1 D11D12G1 D1D11randnysizeB12 ClosedFGddpSys1nzB1D1stmyalphamybeta closedsyslincAB2FB1B2GC1D12FD11D12G ss2tfclosed See Also abinv uiobserver Authors FD 938 Name des2ss descriptor to statespace Sldes2ssABCDE tol Sldes2ssDes Parameters ABCDE real matrices of appropriate dimensions Des list Sl syslin list tol real parameter threshold default value 100eps Description Descriptor to statespace transform Sldes2ssABCDE returns a linear system Sl equivalent to the descriptor system EABCD For index one EA pencil explicit formula is used and for higher index pencils rowshuff is used Sldes2ssDes with DeslistdesABCDE returns a linear system Sl in state space form with possibly a polynomial D matrix A generalized Leverrier algorithm is used Examples spoly0sG1s1s12s3 S1tf2desGS2tf2desGwithD W1des2ssS1W2des2ssS2 cleanss2tfW1 cleanss2tfW2 See Also des2tf glever rowshuff 939 Name des2tf descriptor to transfer function conversion Sdes2tfsl BfsBischisdes2tfsl Parameters sl list linear system in descriptor form Bfs Bis two polynomial matrices chis polynomial S rational matrix Description Given the linear system in descriptor form ie SllistdesABCDE des2tf converts sl into its transfer function representation SCsEA1BD Called with 3 outputs arguments des2tf returns Bfs and Bis two polynomial matrices and chis polynomial such that SBfschis Bis chis is the determinant of sEA up to a xcative constant Examples spoly0s G1s1s1s23s3 Descriptf2desGTf1des2tfDescrip Descrip2tf2desGwithDTf2des2tfDescrip2 ABCDEDescrip226Tf3CinvsEABD See Also glever pol2des tf2des ss2tf des2ss rowshuff Authors F D 940 Name dhinf Hinfinity design of discretetime systems AKBKCKDKRCOND dishinABCDnconnmeasgamma Parameters A the nbyn system state matrix A B the nbym system input matrix B C the pbyn system output matrix C D the pbym system matrix D ncon the number of control inputs m ncon 0 pnmeas ncon nmeas the number of measurements p nmeas 0 mncon nmeas gamma the parameter gamma used in Hinfinity design It is assumed that gamma is sufficiently large so that the controller is admissible gamma 0 AK the nbyn controller state matrix AK BK the nbynmeas controller input matrix BK CK the nconbyn controller output matrix CK DK the nconbynmeas controller matrix DK RCOND a vector containing estimates of the reciprocal condition numbers of the matrices which are to be inverted and estimates of the reciprocal condition numbers of the Riccati equations which have to be solved during the computation of the controller See the description of the algorithm in 1 RCOND 1 contains the reciprocal condition number of the matrix R3 RCOND 2 contains the reciprocal condition number of the matrix R1 R2invR3R2 RCOND 3 contains the reciprocal condition number of the matrix V21 RCOND 4 contains the reciprocal condition number of the matrix St3 RCOND 5 contains the reciprocal condition number of the matrix V12 dhinf 941 RCOND 6 contains the reciprocal condition number of the matrix Im2 DKHATD22 RCOND 7 contains the reciprocal condition number of the XRiccati equation RCOND 8 contains the reciprocal condition number of the ZRiccati equation Description AKBKCKDKRCOND dhinfABCDnconnmeas gamma To compute the matrices of an Hinfinity suboptimal nstate controller AK BK K CK DK for the discretetime system A B1 B2 A B P C1 D11 D12 C D C2 D21 D22 and for a given value of gamma where B2 has column size of the number of control inputs ncon and C2 has row size of the number of measurements nmeas being provided to the controller References 1 PHr Petkov DW Gu and MM Konstantinov Fortran 77 routines for Hinf and H2 design of linear discretetime control systems Report998 Department of Engineering Leicester University April 1999 Examples example from Niconet report SLWN199912 Hinf A07 0 03 0 05 01 06 02 04 03 0 0 05 07 01 0 0 08 07 0 0 05 1 0 0 03 06 09 01 04 05 08 0 0 02 09 B1 2 2 1 0 1 0 1 2 1 3 4 0 2 2 1 2 1 0 1 0 1 2 0 3 1 0 3 1 2 C 1 1 2 2 0 3 3 0 1 1 1 0 0 2 0 4 0 2 dhinf 942 1 3 0 0 3 1 0 1 2 1 0 2 D1 1 2 0 0 0 1 0 1 0 2 1 3 0 1 0 1 0 1 1 0 0 1 2 1 ncon2 nmeas2 gam11130 AKBKCKDK dhinfABCDnconnmeasgam See Also hinf hinf 943 Name dhnorm discrete Hinfinity norm hinfnormdhnormsltolnormax Parameters sl the state space system syslin list discretetime tol tolerance in bisection step default value 001 normax upper bound for the norm default value is 1000 hinfnorm the discrete infinity norm of Sl Description produces the discretetime infinity norm of a statespace system the maximum over all frequencies on the unit circle of the maximum singular value See Also hnorm linfn 944 Name dscr discretization of linear system sld rdscrsldt m Parameters sl syslin list containing ABCD dt real number sampling period m covariance of the input noise continuous timedefault value0 r covariance of the output noise discrete time given if m is given as input sld sampled discretetime linear system syslin list Description Discretization of linear system sl is a continuoustime system dxdtAxBu noise sld is the discretetime system obtained by sampling sl with the sampling period dt Examples spoly0s Syssyslinc11s12ss221s ss2tfdscrtf2ssSys01 See Also syslin flts dsimul 945 Name dsimul state space discrete time simulation ydsimulslu Parameters sl syslin list describing a discrete time linear system u real matrix of appropriate dimension y output of sl Description Utility function If ABCDabcdsl and x0slX0 dsimul returns yCltitrABux0Du ie the time response of sl to the input u sl is assumed to be in state space form syslin list Examples zpoly0z h12zz202z1 sltf2ssh uzeros120u11 x1dsimulslu Impulse response uones120 x2dsimulslu Step response See Also syslin flts ltitr 946 Name dtility detectability test k n U Sld dtilitySl tol Parameters Sl linear system syslin list n dimension of unobservable subspace k dimension of unstable unobservable subspace kn U orthogonal matrix Sld linear system syslin list tol threshold for controllability test Description Detectability test for sl a linear system in statespace representation U is a basis whose k first columns span the unstable unobservable subspace of Sl intersection of unobservable subspace of AC and unstable subspace of A Detectability means k0 Sld UAUUBCUD displays the detectable part of SlABCD ie UAU 0 00 CU 00 with A33C3 observable dimension nxn A22 stable dimension nk and A11 unstable di mension k Examples A211021003 C001 Xrand33AinvXAXCCX WsyslincAC knUW1dtilityW W1A W1C See Also contr stility unobs stabil 947 Name dtsi stable antistable decomposition GaGsGidtsiGtol Parameters G linear system syslin list Ga linear system syslin list antistable and strictly proper Gs linear system syslin list stable and strictly proper Gi real matrix or polynomial matrix for improper systems tol optional parameter for detecting stables poles Default value 100eps Description returns the stableantistable decomposition of G G Ga Gs Gi Gi Goo G can be given in statespace form or in transfer form See Also syslin pbig psmall pfss 948 Name equil balancing of pair of symmetric matrices TequilPQ Parameters P Q two positive definite symmetric matrices T nonsingular matrix Description equil returns t such that TPT and invTQinvT are both equal to a same diagonal and positive matrix Examples Prand44PPP Qrand44QQQ TequilPQ cleanTPT cleaninvTQinvT See Also equil1 balanc ctrgram 949 Name equil1 balancing nonnegative pair of matrices T sizequil1PQ tol Parameters P Q two nonnegative symmetric matrices T nonsingular matrix siz vector of three integers tol threshold Description equil1 computes t such that P1TPT and Q1invTQinvT are as follows P1 diagS1S200 and Q1 diagS10S30 with S1S2S3 positive and diag onal matrices with respective dimensions sizn1n2n3 tol is a threshold for rank determination in SVD Examples S1rand22S1S1S1 S2rand22S2S2S2 S3rand22S3S3S3 PsysdiagS1S2zeros44 QsysdiagS1zeros22S3zeros22 Xrand88 PXPXQinvXQinvX Tsizequil1PQ P1cleanTPT Q1cleaninvTQinvT See Also balreal minreal equil hankelsv Authors S Steer 1987 950 Name feedback feedback operation SlSl1Sl2 Parameters Sl1Sl2 linear systems syslin list in statespace or transfer form or ordinary gain matrices Sl linear system syslin list in statespace or transfer form Description The feedback operation is denoted by slashdot This command returns SlSl1I Sl2Sl11 ie the negative feedback of Sl1 and Sl2 Sl is the transfer v y for y Sl1 u u v Sl2 y The result is the same as SlLFT0IISl2Sl1 Caution do not use with decimal point eg 11 is ambiguous Examples S1ssrand223S2ssrand222 WS1S2 ss2tfS1S2 Same operation by LFT ss2tflftzeros22eye22eye22S2S1 Other approach with constant feedback BigSsysdiagS1S2 Fzeros22eye22eye22zeros22 BigclosedBigSF W1Bigclosed1212 W1W in statespace ss2tfW1 Inverting ss2tfS1inveyeS2S1 See Also lft sysdiag augment obscont 951 Name findABCD discretetime system subspace identification SYSK findABCDSNLRMETHNSMPLTOLPRINTW SYS findABCDSNLRMETH SYSKQRySRCND findABCDSNLRMETHNSMPLTOLPRINTW SYSRCND findABCDSNLRMETH Parameters S integer the number of block rows in the blockHankel matrices N integer the system order L integer the number of output R matrix relevant part of the R factor of the concatenated blockHankel matrices computed by a call to findr METH integer an option for the method to use 1 MOESP method with past inputs and outputs 2 N4SID method 3 combined method A and C via MOESP B and D via N4SID Default METH 3 NSMPL integer the total number of samples used for calculating the covariance matrices and the Kalman predictor gain This parameter is not needed if the covariance matrices andor the Kalman predic tor gain matrix are not desired If NSMPL 0 then K Q Ry and S are not computed Default NSMPL 0 TOL the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine precision PRINTW integer switch for printing the warning messages PRINTW 1 print warning messages PRINTW 0 do not print warning messages Default PRINTW 0 findABCD 952 SYS computes a statespace realization SYS ABCD an syslin object K the Kalman predictor gain K if NSMPL 0 Q state covariance Ry output covariance S stateoutput crosscovariance RCND vector reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions Description Finds the system matrices and the Kalman gain of a discretetime system given the system order and the relevant part of the R factor of the concatenated blockHankel matrices using subspace identifi cation techniques MOESP andor N4SID SYSK findABCDSNLRMETHNSMPLTOLPRINTW computes a state space realiza tion SYS ABCD an ss object and the Kalman predictor gain K if NSMPL 0 The model structure is xk1 Axk Buk Kek k 1 yk Cxk Duk ek where xk and yk are vectors of length N and L respectively SYSKQRySRCND findABCDSNLRMETHNSMPLTOLPRINTW also returns the state output and stateoutput crosscovariance matrices Q Ry and S used for computing the Kalman gain as well as the vector RCND of length lr containing the reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions where lr 4 if Kalman gain matrix K is not required and lr 12 if Kalman gain matrix K is required Matrix R computed by findR should be determined with suitable arguments METH and JOBD METH 1 and JOBD 1 must be used in findR for METH 1 in findABCD METH 1 must be used in findR for METH 3 in findABCD Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 findABCD 953 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15 RN1SVAL findRSYU N3 SYS1 findABCDSN1R SYS1dt01 SYS1X0 inistateSYS1YU Y1fltsUSYS1 clfplot2d1nsmpYY1 See Also findAC findBD findBDK findR sorder sident 954 Name findAC discretetime system subspace identification AC findACSNLRMETHTOLPRINTW ACRCND findACSNLRMETHTOLPRINTW Parameters S integer the number of block rows in the blockHankel matrices N integer L integer R matrix relevant part of the R factor of the concatenated blockHankel matrices computed by a call to findr METH integer an option for the method to use 1 MOESP method with past inputs and outputs 2 N4SID method Default METH 3 TOL the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine precision PRINTW integer switch for printing the warning messages PRINTW 1 print warning messages 0 do not print warning messages Default PRINTW 0 A matrix state system matrix C matrix output system matrix RCND vector of length 4 condition numbers of the matrices involved in rank decision findAC 955 Description finds the system matrices A and C of a discretetime system given the system order and the relevant part of the R factor of the concatenated blockHankel matrices using subspace identification tech niques MOESP or N4SID AC findACSNLRMETHTOLPRINTW computes the system matrices A and C The mod el structure is xk1 Axk Buk Kek k 1 yk Cxk Duk ek where xk and yk are vectors of length N and L respectively ACRCND findACSNLRMETHTOLPRINTW also returns the vector RCND of length 4 containing the condition numbers of the matrices involved in rank decisions Matrix R computed by findR should be determined with suitable arguments METH and JOBD Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15L1 RNSVAL findRSYU N3 METH3TOL1 AC findACSNLRMETHTOL See Also findABCD findBD findBDK findR sorder sident 956 Name findBD initial state and system matrices B and D of a discretetime system x0 B D V rcnd findBDjobx0comuse jobA BC DY Utolprintwldwork Parameters jobx0 integer option to specify whether or not the initial state should be computed 1 compute the initial state x0 2 do not compute the initial state possibly because x0 is known to be zero comuse integer option to specify whether the system matrices B and D should be computed or used 1 compute the matrices B and D as specified by job 2 use the matrices B and D as specified by job 3 do not computeuse the matrices B and D job integer option to determine which of the system matrices B and D should be computed or used 1 computeuse the matrix B only D is known to be zero 2 computeuse the matrices B and D job must not be specified if jobx0 2 and comuse 2 or if comuse 3 A state matrix of the given system B optionnal input matrix of the given system C output matrix of the given system D optionnal direct feedthrough of the given system Y the tbyl outputdata sequence matrix Column j of Y contains the t values of the jth output component for consecutive time increments U the tbym inputdata sequence matrix input when jobx0 1 and comuse 2 or comuse 1 Column j of U contains the t values of the jth input component for consecutive time increments findBD 957 tol optionnal tolerance used for estimating the rank of matrices If tol 0 then the given value of tol is used as a lower bound for the reciprocal condition number an mbyn matrix whose estimated condition number is less than 1tol is considered to be of full rank Default mnepsilonmachine where epsilonmachine is the relative machine precision printw optionnal switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default printw 0 ldwork optional the workspace size Default computed by the formula LDWORK MAX minimum workspace size needed 2CSIZE3 CSIZE m l t 2n n m l lm where CSIZE is the cache size in double precision words x0 initial state vector Br system input matrix Dr system direct feedthrough matrix V the nbyn orthogonal matrix which reduces A to a real Schur form output when jobx0 1 or comuse 1 rcnd optional the reciprocal condition numbers of the matrices involved in rank decisions Description findBD function for estimating the initial state and the system matrices B and D of a discretetime system using SLICOT routine IB01CD x0BrVrcnd findBD111ACYU x0BrDrVrcnd findBD112ACYU BrVrcnd findBD211ACYU BDrVrcnd findBD212ACYU x0Vrcnd findBD121ABCYU x0Vrcnd findBD122ABCDYU x0rcnd findBD22 Set x0 0 rcnd 1 x0Vrcnd findBD13ACY Note the example lines above may contain at the end the parameters tol printw ldwork FINDBD estimates the initial state andor the system matrices Br and Dr of a discretetime system given the system matrices A C and possibly B D and the input and output trajectories of the system The model structure is findBD 958 xk1 Axk Buk k 1 yk Cxk Duk where xk is the ndimensional state vector at time k uk is the mdimensional input vector yk is the ldimensional output vector and A B C and D are real matrices of appropriate dimensions Comments 1 The nbym system input matrix B is an input parameter when jobx0 1 and comuse 2 and it is an output parameter when comuse 1 2 The lbym system matrix D is an input parameter when jobx0 1 comuse 2 and job 2 and it is an output parameter when comuse 1 and job 2 3 The nvector of estimated initial state x0 is an output parameter when jobx0 1 but also when jobx0 2 and comuse 2 in which case it is set to 0 4 If ldwork is specified but it is less than the minimum workspace size needed that minimum value is used instead Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15L1 RNSVAL findRSYU N3 METH3TOL1 AC findACSNLRMETHTOL X0BD findBD112ACYU SYS1syslin1ABCDX0 Y1fltsUSYS1 clfplot2d1nsmpYY1 findBD 959 See Also inistate findx0BD findABCD findAC findBD Authors V Sima Katholieke Univ Leuven Belgium May 2000 Revisions V Sima July 2000 960 Name findBDK Kalman gain and B D system matrices of a discretetime system BDK findBDKSNLRACMETHJOBNSMPLTOLPRINTW BDRCND findBDKSNLRACMETHJOB BDKQRySRCND findBDKSNLRACMETHJOBNSMPLTOLPRINTW Parameters S integer the number of block rows in the blockHankel matrices N integer L integer R matrix relevant part of the R factor of the concatenated blockHankel matrices computed by a call to findR A square matrix C matrix METH integer an option for the method to use 1 MOESP method with past inputs and outputs 2 N4SID method Default METH 2 JOB an option specifying which system matrices should be computed 1 compute the matrix B 2 compute the matrices B and D Default JOB 2 NSMPL integer the total number of samples used for calculating the covariance matrices and the Kalman predictor gain This parameter is not needed if the covariance matrices andor the Kalman predic tor gain matrix are not desired If NSMPL 0 then K Q Ry and S are not computed Default NSMPL 0 TOL the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine precision findBDK 961 PRINTW integer switch for printing the warning messages PRINTW 1 print warning messages PRINTW 0 do not print warning messages Default PRINTW 0 SYS computes a statespace realization SYS ABCD an syslin object K the Kalman predictor gain K if NSMPL 0 Q state covariance Ry output covariance S stateoutput crosscovariance RCND he vector of length 12 containing the reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions Description finds the system matrices B and D and the Kalman gain of a discretetime system given the system order the matrices A and C and the relevant part of the R factor of the concatenated blockHankel matrices using subspace identification techniques MOESP or N4SID BDK findBDKSNLRACMETHJOBNSMPLTOLPRINTW computes the system ma trices B if JOB 1 B and D if JOB 2 and the Kalman predictor gain K if NSMPL 0 The model structure is xk1 Axk Buk Kek k 1 yk Cxk Duk ek where xk and yk are vectors of length N and L respectively BDRCND findBDKSNLRACMETHJOB also returns the vector RCND of length 4 con taining the reciprocal condition numbers of the matrices involved in rank decisions BDKQRySRCND findBDKSNLRACMETHJOBNSMPLTOLPRINTW also re turns the state output and stateoutput crosscovariance matrices Q Ry and S used for comput ing the Kalman gain as well as the vector RCND of length 12 containing the reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions Matrix R computed by findR should be determined with suitable arguments METH and JOBD METH 1 and JOBD 1 must be used in findR for METH 1 in findBDK Using METH 1 in FINDR and METH 2 in findBDK is allowed The number of output arguments may vary but should correspond to the input arguments eg findBDK 962 B findBDKSNLRACMETH1 or BD findBDKSNLRACMETH2 or BDRCND findBDKSNLRACMETH2 Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15L1 RNSVAL findRSYU N3 METH3TOL1 AC findACSNLRMETHTOL BDK findBDKSNLRAC SYS1syslin1ABCD SYS1X0 inistateSYS1YU Y1fltsUSYS1 clfplot2d1nsmpYY1 See Also findABCD findAC findBD findR sorder sident 963 Name findR Preprocessor for estimating the matrices of a linear timeinvariant dynamical system RN SVALRCND findRSYUMETHALGJOBDTOLPRINTW RN findRSY Parameters S the number of block rows in the blockHankel matrices Y U METH an option for the method to use 1 MOESP method with past inputs and outputs 2 N4SI15 0 1 1 1000D method Default METH 1 ALG an option for the algorithm to compute the triangular factor of the concatenated blockHankel matrices built from the inputoutput data 1 Cholesky algorithm on the correlation matrix 2 fast QR algorithm 3 standard QR algorithm Default ALG 1 JOBD an option to specify if the matrices B and D should later be computed using the MOESP approach 1 the matrices B and D should later be computed using the MOESP approach 2 the matrices B and D should not be computed using the MOESP approach Default JOBD 2 This parameter is not relevant for METH 2 TOL a vector of length 2 containing tolerances TOL 1 is the tolerance for estimating the rank of matrices If TOL1 0 the given value of TOL1 is used as a lower bound for the reciprocal condition number Default TOL1 prodsizematrixepsilonmachine where epsilonmachine is the rela tive machine precision findR 964 TOL 2 is the tolerance for estimating the system order If TOL2 0 the estimate is indicated by the index of the last singular value greater than or equal to TOL2 Singular values less than TOL2 are considered as zero When TOL2 0 then Sepsilonmachinesval1 is used instead TOL2 where sval1 is the maximal singular value When TOL2 0 the estimate is indicated by the index of the singular value that has the largest logarithmic gap to its successor Default TOL2 1 PRINTW a switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default PRINTW 0 R N the order of the discretetime realization SVAL singular values SVAL used for estimating the order RCND vector of length 2 containing the reciprocal condition numbers of the matrices involved in rank decisions or least squares solutions Description findR Preprocesses the inputoutput data for estimating the matrices of a linear timeinvariant dynam ical system using Cholesky or fast QR factorization and subspace identification techniques MOE SP or N4SID and estimates the system order RN findRSYUMETHALGJOBDTOLPRINTW returns the processed upper triangular fac tor R of the concatenated blockHankel matrices built from the inputoutput data and the order N of a discretetime realization The model structure is xk1 Axk Buk wk k 1 yk Cxk Duk ek The vectors yk and uk are transposes of the kth rows of Y and U respectively RNSVALRCND findRSYUMETHALGJOBDTOLPRINTW also returns the singular val ues SVAL used for estimating the order as well as if meth 2 the vector RCND of length 2 con taining the reciprocal condition numbers of the matrices involved in rank decisions or least squares solutions RN findRSY assumes U and default values for the remaining input arguments Examples generate data from a given linear system findR 965 A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC Uones11000rand11000normal YfltsUSYS05rand11000normal Compute R RNSVAL findR15YU SVAL N See Also findABCD findAC findBD findBDK sorder sident 966 Name findx0BD Estimates state and B and D matrices of a discretetime linear system X0BD findx0BDACYUWITHX0WITHDTOLPRINTW x0BDVrcnd findx0BDACYU Parameters A state matrix of the system C C matrix of the system Y system output U system input WITHX0 a switch for estimating the initial state x0 1 estimate x0 0 do not estimate x0 Default WITHX0 1 WITHD a switch for estimating the matrix D 1 estimate the matrix D 0 do not estimate the matrix D Default WITHD 1 TOL the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine precision PRINTW a switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default PRINTW 0 X0 intial state of the estimated linear system findx0BD 967 B B matrix of the estimated linear system D D matrix of the estimated linear system V orthogonal matrix which reduces the system state matrix A to a real Schur form rcnd estimates of the reciprocal condition numbers of the matrices involved in rank decisions Description findx0BD Estimates the initial state andor the matrices B and D of a discretetime linear system given the estimated system matrices A C and a set of inputoutput data X0BD findx0BDACYUWITHX0WITHDTOLPRINTW estimates the initial state X0 and the matrices B and D of a discretetime system using the system matrices A C output data Y and the input data U The model structure is xk1 Axk Buk k 1 yk Cxk Duk The vectors yk and uk are transposes of the kth rows of Y and U respectively x0BDVrcnd findx0BDACYU also returns the orthogonal matrix V which reduces the system state matrix A to a real Schur form as well as some estimates of the reciprocal condition numbers of the matrices involved in rank decisions B findx0BDACYU00 returns B only and BD findx0BDACYU0 returns B and D only Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15L1 RNSVAL findRSYU N3 METH3TOL1 AC findACSNLRMETHTOL findx0BD 968 X0BDVrcnd findx0BDACYU SYS1syslin1ABCDX0 Y1fltsUSYS1 clfplot2d1nsmpYY1 See Also findBD inistate 969 Name flts time response discrete time sampled system y xfltsusl x0 yfltsusl past Parameters u matrix input vector sl list linear system syslin x0 vector initial state default value0 past matrix of the past default value0 xy matrices state and output Description Statespace form sl is a discrete linear system given by its state space representation see syslin slsyslindABCD xt1 A xt B ut yt C xt D ut or more generally if D is a polynomial matrix p degreeDz Dz D0 z D1 z2 D2 zp Dp yt C xt D0 ut D1 ut1 Dp utp Transfer form yfltsuslpast Here sl is a linear system in transfer matrix representation ie slsyslindtransfermatrix see syslin past u u nd 1 y y nd 1 is the matrix of past values of u and y nd is the maximum of degrees of lcms of each row of the denominator matrix of sl flts 970 uu0 u1 un input yy0 y1 yn output p is the difference between maximum degree of numerator and maximum degree of denominator Examples slsyslind111u110 yfltsusl plot2dy y1x1fltsu15sly2fltsu610slx1 yy1y2 With polynomial D zpoly0z D1zz2 p degreeD slsyslind111D yfltsusly1x1fltsu15sl y2fltsu5p110slx1 update yy1y2 Delay transfer form fltsu1z Usual responses zpoly0z hsyslin0112zz203z1 imprepfltseye120tf2ssh Impulse response clf plotimprepb uones120 stprepfltsones120tf2ssh Step response plotstprepg Other examples A1 2 30 2 40 0 1B1 00 00 1Ceye33SyssyslindABC Hss2tfSys u11110 yhfltsuH ysfltsuSys normyhys1 hot restart ys1xfltsu14Sysys2fltsu510Sysx normys1ys2ys1 yh1fltsu14Hyh2fltsu510Hu24yh24 normyh1yh2yh1 with Dltgt0 D3 84 0522 09 SyssyslindABCD Hss2tfSys u11110 rhfltsuH rsfltsuSys normrhrs1 hot restart ys1xfltsu14Sysys2fltsu510Sysx normys1ys2rs1 With H yh1fltsu14Hyh2fltsu510Hu24 yh124 flts 971 normyh1yh2rh See Also ltitr dsimul rtitr 972 Name fourplan augmented plant to four plants P11P12P21P22fourplanPr Parameters P syslin list linear system r 1x2 row vector dimension of P22 P11P12P21P22 syslin lists Description Utility function P being partitioned as follows P P11 P12 P21 P22 with sizeP22r this function returns the four linear systems P11P12P21P22 See Also lqg lqg2stan lqr lqe lft 973 Name frep2tf transfer function realization from frequency response h errfrep2tffrqrepfdg domtolsweight Parameters frq vector of frequencies in Hz repf vector of frequency response dg degree of linear system dom time domain c or d or dt tols a vector of size 3 giving the relative and absolute tolerance and the maximum number of iterations default values are rtol1e2 atol1e4 N10 weight vector of weights on frequencies h SISO transfer function err error for example if domc sumabsh2ipifrq rep2sizefrq Description Frequency response to transfer function conversion The order of h is a priori given in dg which must be provided The following linear system is solved in the least square sense weightkn phik dphikrepk0 k1n where phik 2ipifrq when domc and phikexp2ipidomfrq if not If the weight vector is not given a default penalization is used when domc A stable and minimum phase system can be obtained by using function factors Examples spoly0s hsyslincs1s35s20 frq00053repfrepfreqhfrq cleanfrep2tffrqrepf3 Sysssrand1110 frqlogspace32200 frqreprepfreqSysfrq Frequency response of Sys frep2tf 974 Sys2errfrep2tffrqrep10Sys2cleanSys2Sys2 obtained from freq resp of Sys frqrep2repfreqSys2frq Frequency response of Sys2 clfbodefrqreprep2 Responses of Sys and Sys2 gsortspecSysAgsortrootsSys2den poles dom11000 Sampling time zpoly0z hsyslindomz205z301z205z008 frq000105domrepfrepfreqhfrq Sys2errfrep2tffrqrepf3dom frqrep2repfreqSys2frq Frequency response of Sys2 clfplot2d1onnfrqabsrepfrep2 See Also imrep2ss arl2 timeid armax frfit 975 Name freq frequency response xfreqABC Df xfreqNUMDENf Parameters A B C D real matrices of respective dimensions nxn nxp mxn mxp NUMDEN polynomial matrices of dimension mxp x real or complex matrix Description xfreqABC Df returns a real or complex mxpt matrix such that xkpk1p CinvfkeyeAB D Thus for f taking values along the imaginary axis or on the unit circle x is the continuous or discrete time frequency response of ABCD xfreqNUMDENf returns a real or complex matrix x such that columns kp11 to kp of x contain the matrix NUMfkDENfk Examples spoly0s syss1s35s4 repfreqsysnumsysden00911231020 hornersys0hornersys20 Systf2sssys ABCDabcdSys freqABC00911231020 See Also repfreq horner 976 Name freson peak frequencies frfresonh Parameters h syslin list fr vector of peak frequencies in Hz Description returns the vector of peak frequencies in Hz for the SISO plant h Examples hsyslinc1s32ss25001ss2 frfresonh bodeh g20logabsrepfreqhfrlog10 See Also frep2tf zgrid hnorm 977 Name fspecg stable factorization gmfspecgg Parameters ggm syslin lists linear systems in statespace representation Description returns gm with gm and gm1 stable such that gtildgg gtildgmgm g and gm are continuoustime linear systems in statespace form Imaginaryaxis poles are forbidden 978 Name fstabst Youlas parametrization JfstabstPr Parameters P syslin list linear system r 1x2 row vector dimension of P22 J syslin list linear system in statespace representation Description Parameterization of all stabilizing feedbacks P is partitioned as follows P P11 P12 P21 P22 in statespace or transfer form automatic conversion in statespace is done for the computations r size of P22 subsystem 22 block of P J J11 J12 J21 J22 K is a stabilizing controller for P ie P22 iff KlftJrQ with Q stable The central part of J J11 is the lqg regulator for P This J is such that defining T as the 2port lft of P and J TrtlftPrJr one has that T12 is inner and T21 is coinner Examples ny2nu3nx4 P22ssrandnynunx bigQrandnxnunxnubigQbigQbigQ bigRrandnxnynxnybigRbigRbigR Prlqg2stanP22bigQbigR JfstabstPr Qssrandnuny1QA1 Stable Q KlftJrQ AhclPrK specA fstabst 979 See Also obscont lft lqg lqg2stan 980 Name gmargin gain margin and associated crossover frequency gmgmarginh gmfrgmarginh Parameters h a SISO linear system see syslin gm a number the gain margin in dB if any of Inf fr a number the associated frequency in hertz or an empty matrix if the gain margin does not exist Description Given a SISO linear system in continuous or discrete time gmargin returns gm the gain margin in dB of h and fr the achieved corresponding frequency in hz The gain margin if it exists is the minimal value of the system gain at points where the nyquist plot crosses the negative real axis In other words the gain margin is 20log101g where g is the open loop gain of h when the frequency response phase of h equals 180 The algorithm uses polynomial root finder to solve the equations hshs for the continuous time case hzh1z for the discrete time case Examples hsyslinc1s32ss2 continuous time case gfrgmarginh gfrgmarginh10 nyquisth10 h syslin01004798z00464z2181z09048discrete time case g frgmarginh showmarginsh See Also pmargin showmargins repfreq black bode chart nyquist Authors Serge Steer INRIA 981 Name gamitg Hinfinity gamma iterations goptgamitgGrprec options Parameters G syslin list plant realization r 1x2 row vector dimension of G22 prec desired relative accuracy on the norm option string t gopt real scalar optimal Hinfinity gain Description goptgamitgGrprec options returns the Hinfinity optimal gain gopt G contains the statespace matrices ABCD of the plant with the usual partitions B B1 B2 C C1 D D11 D12 C2 D21 D22 These partitions are implicitly given in r r1 and r2 are the dimensions of D22 rows x columns With optiont gamitg traces each bisection step ie displays the lower and upper bounds and the current test point See Also ccontrg hinf Authors P Gahinet 982 Name gcare control Riccati equation XFgcareSl Parameters Sl linear system syslin list X symmetric matrix F real matrix Description Generalized Control Algebraic Riccati Equation GCARE X solution F gain The GCARE for SlABCD is ABSiDCXXABSiDCXBSiBXCRiC0 where SeyeDD SiinvS ReyeDD RiinvR and FSiDC BX is such that ABF is stable See Also gfare 983 Name gfare filter Riccati equation ZHgfareSl Parameters Sl linear system syslin list Z symmetric matrix H real matrix Description Generalized Filter Algebraic Riccati Equation GFARE Z solution H gain The GFARE for SlABCD is ABDRiCZZABDRiCZCRiCZBSiB0 where SeyeDD SiinvS ReyeDD RiinvR and H BDZCRi is such that AHC is stable See Also gcare 984 Name gfrancis Francis equations for tracking LMTgfrancisPlantModel Parameters Plant syslin list Model syslin list LMT real matrices Description Given the the linear plant x Fx Gu y Hx Ju and the linear model xm Axm Bum ym Cxm Dum the goal is for the plant to track the model ie e y ym 0 while keeping stable the state xt of the plant u is given by feedforward and feedback u Lxm Mum KxTxm K LKT xxm Mum The matrices TLM satisfy generalized Francis equations FT GL TA HT JL C GM TB JM D The matrix K must be chosen as stabilizing the pair FG See example of use in directory de mostracking Examples Plantssrand135 FGHJabcdPlant nw4nuu2Arandnwnw gfrancis 985 stmaxirealspecAAAsteyeA BrandnwnuuC2rand1nwD0randCB ModelsyslincABCD LMTgfrancisPlantModel normFTGLTA1 normHTJLC1 normGMTB1 normJMD1 See Also lqg ppol 986 Name gtild tilde operation GtgtildG GtgtildGflag Parameters G either a polynomial or a linear system syslin list or a rational matrix Gt same as G flag character string either c or d optional parameter Description If G is a polynomial matrix or a polynomial GtgtildGc returns the polynomial matrix GtsGs If G is a polynomial matrix or a polynomial GtgtildGd returns the polynomial matrix GtG1zzn where n is the maximum degree of G For continuoustime systems represented in statespace by a syslin list Gt gtildGc returns a statespace representation of Gs ie the ABCD matrices of Gt are AC B D If G is improper D Ds the D matrix of Gt is Ds For discretetime systems represented in statespace by a syslin list Gt gtildGd re turns a statespace representation of G1z ie the possibly improper statespace representation of zCinvzABC D1z For rational matrices Gt gtildGc returns the rational matrix GtsGs and Gt gtildGd returns the rational matrix Gtz G1z The parameter flag is necessary when gtild is called with a polynomial argument Examples Continuous time spoly0sGss32s3s25 GtgtildGc GthornerGs continuoustime interpretation GtgtildGd GthornerG1ss3 discretetime interpretation Gssrand223GtgtildG Statespace G is cont time by default cleanhornerss2tfGsss2tfGt Check Discretetime zpoly0z Gssssrand223Gssdtd discretetime Gss51201 With a constant D matrix Gss2tfGssGt1hornerG1z GtgtildGss Gt2cleanss2tfGt cleanGt1Gt2 Check gtild 987 Improper systems zpoly0z Gssssrand223Gss7d discretetime Gss5zz21z3 Dz is polynomial Gss2tfGssGt1hornerG1z Calculation in transfer form GtgtildGss in statespace Gt2cleanss2tfGtcleanGt1Gt2 Check See Also syslin horner factors 988 Name h2norm H2 norm nh2normSl tol Parameters Sl linear system syslin list n real scalar Description produces the H2 norm of a linear continuous time system Sl For Sl in statespace form h2norm uses the observability gramian and for Sl in transfer form h2norm uses a residue method 989 Name hcl closed loop matrix AclhclPrK AclhclP22K Parameters P P22 linear system syslin list augmented plant or nominal plant respectively r 1x2 row vector dimensions of 22 part of P rrowscolssizeP22 K linear system syslin list controller Acl real square matrix Description Given the standard plant P with rsizeP22 and the controller K this function returns the closed loop matrix Acl The poles of Acl must be stable for the internal stability of the closed loop system Acl is the Amatrix of the linear system I P22K I1 ie the Amatrix of lftPrK See Also lft Authors F D 990 Name hinf Hinfinity central controller SkrohinfPrrominromaxnmax SkrkrohinfPrrominromaxnmax Parameters P syslin list continuoustime linear system augmented plant given in statespace form or in transfer form r size of the P22 plant ie 2vector outputsinputs rominromax a priori bounds on ro with ro1gama2 romin0 usually nmax integer maximum number of iterations in the gamaiteration Description hinf computes Hinfinity optimal controller for the continuoustime plant P The partition of P into four subplants is given through the 2vector r which is the size of the 22 part of P P is given in statespace eg PsyslincABCD with ABCD constant matrices or PsyslincH with H a transfer matrix SkroHinfPrrominromaxnmax returns ro in rominromax and the central controller Sk in the same representation as P All calculations are made in statespace ie conversion to statespace is done by the function if necessary Invoked with three LHS parameters SkrkroHinfPrrominromaxnmax returns ro and the Parameterization of all stabilizing controllers a stabilizing controller K is obtained by KlftSkrPHI where PHI is a linear system with dimensions r and satisfy HnormPHI gamma rk r is the size of the Sk22 block and ro 1gama2 after nmax iterations Algorithm is adapted from SafonovLimebeer Note that P is assumed to be a continuoustime plant See Also gamitg ccontrg leqr Authors FDelebecque INRIA 1990 991 Name hinfst static Hinfinity problem KoptgamaopthinfstatDr Parameters D real matrix r 1x2 vector Kopt matrix Description computes a matrix Kopt such that largest singular value of lftDrKD11D12 KinvID22K D21 is minimal Static Hinfinity four blocks problem D is partionned as DD11 D12 D21 D22 where sizeD22rr1 r2 Authors FD 992 Name hnorm Hinfinity norm hinfnorm frequencyhnormsl rerr Parameters sl the state space system syslin list rerr max relative error default value 1e8 hinfnorm the infinity norm of Sl frequency frequency at which maximum is achieved Description produces the infinity norm of a statespace system the maximum over all frequencies of the maximum singular value See Also linfn linf svplot 993 Name hankelsv Hankel singular values nk2Whankelsvsl tol nk2hankelsvsl tol Parameters sl syslin list representing the linear system statespace tol tolerance parameter for detecting imaginary axis modes default value is 1000eps Description returns nk2 the squared Hankel singular values of sl and W PQ controllability gramian times observability gramian nk2 is the vector of eigenvalues of W Examples Adiag123 slsyslincArand32rand23nk2Whankelsvsl QMpbigWnk22epsc slrprojslslQMhankelsvslr See Also balreal equil equil1 994 Name hinf Hinfinity design of continuoustime systems AKBKCKDKRCOND hinfABCDnconnmeasgamma Parameters A the nbyn system state matrix A B the nbym system input matrix B C the pbyn system output matrix C D the pbym system matrix D ncon the number of control inputs m ncon 0 pnmeas ncon nmeas the number of measurements p nmeas 0 mncon nmeas gamma the parameter gamma used in Hinfinity design It is assumed that gamma is sufficiently large so that the controller is admissible gamma 0 AK the nbyn controller state matrix AK BK the nbynmeas controller input matrix BK CK the nconbyn controller output matrix CK DK the nconbynmeas controller matrix DK RCOND a vector containing estimates of the reciprocal condition numbers of the matrices which are to be inverted and estimates of the reciprocal condition numbers of the Riccati equations which have to be solved during the computation of the controller See the description of the algorithm in 1 RCOND 1 contains the reciprocal condition number of the control transformation matrix TU RCOND 2 contains the reciprocal condition number of the measurement transformation matrix TY RCOND 3 contains an estimate of the reciprocal condition number of the XRiccati equation RCOND 4 contains an estimate of the reciprocal condition number of the YRiccati equation hinf 995 Description AKBKCKDKRCOND hinfABCDnconnmeasgamma To compute the ma trices of an Hinfinity suboptimal nstate controller AK BK K CK DK for the continuoustime system A B1 B2 A B P C1 D11 D12 C D C2 D21 D22 and for a given value of gamma where B2 has column size of the number of control inputs ncon and C2 has row size of the number of measurements nmeas being provided to the controller References 1 PHr Petkov DW Gu and MM Konstantinov Fortran 77 routines for Hinf and H2 design of continuoustime linear control systems Report9814 Department of Engineering Leicester Univer sity August 1998 Examples example from Niconet report SLWN199912 Hinf A1 0 4 5 3 2 2 4 7 2 0 3 6 9 5 0 2 1 8 4 7 1 3 0 2 5 8 9 1 4 3 5 8 0 2 6 B3 4 2 1 0 2 0 1 5 2 5 7 0 7 2 4 6 1 1 2 3 9 8 0 5 1 2 3 6 2 C 1 1 2 4 0 3 3 0 5 1 1 1 7 5 0 8 2 2 9 3 4 0 3 7 0 1 2 1 6 2 D 1 2 3 0 0 0 4 0 1 0 5 3 4 0 1 hinf 996 0 1 0 1 3 0 0 1 7 1 Gamma1018425636157899 AKBKCKDK hinfABCD22Gamma See Also dhinf 997 Name imrep2ss statespace realization of an impulse response slimrep2ssv deg Parameters v vector coefficients of impulse response vk is the kth sample deg integer order required sl syslin list Description Impulse response to linear system conversion one input v must have an even number of columns Examples spoly0s H1s052s04 strictly proper np20wldivHnumHdennp repw1npwnp12np The impulse response H1ss2tfimrep2ssrep zpoly0z H2z234z15z216z08 Proper transfer function uzeros120u11 reprtitrHnumHdenu Impulse rep repldivHnumHden20 wzimrep2ssrep Realization with shifted impulse response ie strictly proper to proper H2ss2tfw See Also frep2tf arl2 timeid armax markp2ss ldiv 998 Name inistate Estimates the initial state of a discretetime system X0 inistateSYSYUTOLPRINTW X0 inistateABCYU X0 inistateACY x0Vrcnd inistateSYSYUTOLPRINTW Parameters SYS given system syslindtABCD Y the output of the system U the input of the system TOL TOL is the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine pre cision PRINTW PRINTW is a switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default PRINTW 0 X0 the estimated initial state vector V orthogonal matrix which reduces the system state matrix A to a real Schur form rcnd estimate of the reciprocal condition number of the coefficient matrix of the least squares problem solved Description inistate Estimates the initial state of a discretetime system given the estimated system matrices and a set of inputoutput data X0 inistateSYSYUTOLPRINTW estimates the initial state X0 of the discretetime system SYS ABCD using the output data Y and the input data U The model structure is xk1 Axk Buk k 1 inistate 999 yk Cxk Duk The vectors yk and uk are transposes of the kth rows of Y and U respectively Instead of the first input parameter SYS an syslin object equivalent information may be specified using matrix parameters for instance X0 inistateABCYU or X0 inistateACY x0Vrcnd inistateSYSYUTOLPRINTW returns besides x0 the orthogonal matrix V which reduces the system state matrix A to a real Schur form as well as an estimate of the reciprocal condition number of the coefficient matrix of the least squares problem solved See Also findBD findx0BD 1000 Name invsyslin system inversion sl2invsyslinsl1 Parameters sl1sl2 syslin lists linear systems in state space representation Description Utility function Computes the state form of the inverse sl2 of the linear system sl1 which is also given in state form The Dmatrix is supposed to be full rank Old stuff used by invS when S is a syslin list See Also rowregul inv 1001 Name kpure continuous SISO system limit feedback gain Kkpuresys tol KRkpuresys tol Parameters sys SISO linear system syslin tol vector with 2 elements epsK epsI epsK is a tolerance used to determine if two values of K can be considered as equal epsI is a tolerance used to determine if a root is imaginary or not The default value is 1e6 1e6 K Real vector the vector of gains for which at least one closed loop pole is imaginary R Complex vector the imaginary closed loop poles associated with the values of K Description Kkpuresys computes the gains K such that the system sys feedback by Ki sysKi has poles on imaginary axis Examples spoly0s hsyslincs115ss2s3 clfevansh Kkpureh hfhK1 rootsdenomhf See Also evans krac2 1002 Name krac2 continuous SISO system limit feedback gain gkrac2sys Parameters sys SISO linear system syslin g constant Description krac2sys computes the gains g such that the system sys fedback by g sysg has 2 real equal poles Examples hsyslinc352poly5spoly002000200251sc clfevansh100 gkrac2h hf1hg1rootsdenomhf1 hf2hg2rootsdenomhf2 See Also evans kpure 1003 Name lcf normalized coprime factorization NMlcfsl Parameters sl linear system given in state space or transfer function syslin list NM two linear systems syslin list Description Computes normalized coprime factorization of the linear dynamic system sl sl M1 N Authors F D 1004 Name leqr Hinfinity LQ gain full state KXerrleqrP12Vx Parameters P12 syslin list Vx symmetric nonnegative matrix should be small enough KX two real matrices err a real number l1 norm of LHS of Riccati equation Description leqr computes the linear suboptimal Hinfinity LQ fullstate gain for the plant P12AB2C1D12 in continuous or discrete time P12 is a syslin list eg P12syslincAB2C1D12 C1 Q S C1 D12 D12 S R Vx is related to the variance matrix of the noise w perturbing x usually Vxgama2B1B1 The gain K is such that A B2K is stable X is the stabilizing solution of the Riccati equation For a continuous plant AB2invRSXXAB2invRSXB2invRB2VxXQSinvRS0 KinvRB2XS For a discrete time plant XAbarinvinvXB2invRB2VxAbarQbar0 KinvRB2invinvXB2invRB2VxAbarS with AbarAB2invRS and QbarQSinvRS leqr 1005 The 3blocks matrix pencils associated with these Riccati equations are discrete continuous I Vx 0 A 0 B2 I 0 0 A Vx B2 z0 A 0 Q I S s0 I 0 Q A S 0 B2 0 S 0 R 0 0 0 S B2 R See Also lqr Authors FD 1006 Name lft linear fractional transformation P1lftPK P1lftPrK P1r1lftPrPsrs Parameters P linear system syslin list the augmented plant implicitly partitioned into four blocks two input ports and two output ports K linear system syslin list the controller possibly an ordinary gain r 1x2 row vector dimension of P22 Ps linear system syslin list implicitly partitioned into four blocks two input ports and two output ports rs 1x2 row vector dimension of Ps22 Description Linear fractional transform between two standard plants P and Ps in state space form or in transfer form syslin lists r sizeP22 rssizeP22s lftPr K is the linear fractional transform between P and a controller K K may be a gain or a controller in state space form or in transfer form lftPK is lftPrK with rsize of K transpose P1 P11P12K IP22K1 P21 P1r1lftPrPsrs returns the generalized 2 ports lft of P and Ps P1 is the pair twoport interconnected plant and the partition of P1 into 4 blocks in given by r1 which is the dimension of the 22 block of P1 P and R can be PSSDs ie may admit a polynomial D matrix Examples spoly0s P1s 1s1 1s22s K 1s1 lftPK lftP11K P11P12Kinv1P22KP21 Numerically dangerous ss2tflfttf2ssPtf2ssK lftP1 lft 1007 f0001wPf w11 Improper plant PID control W1111s201sK11ss lftW11K ss2tflfttf2ssW11tf2ssK See Also sensi augment feedback sysdiag 1008 Name lin linearization ABCDlinsimx0u0 sllinsimx0u0 Parameters sim function x0 u0 vectors of compatible dimensions ABCD real matrices sl syslin list Description linearization of the nonlinear system yxdotsimxu around x0u0 sim is a function which computes y and xdot The output is a linear system syslin list sl or the four matrices ABCD For example if ftz is the function passed to ode eg zdftztzu and if we assume that yx zodex0t0tflistftzu compute xtf If simula is the following function deffyxdsimulaxuxdftztfxu yx the tangent linear system sl can be obtained by ABCDlinsimulazu sl syslincABCDx0 Examples deffyxdotsimxuxdotusinxux2yxdot1xdot2 sllinsim12 See Also external derivat 1010 Name linf infinity norm linfg epstol Parameters g is a syslin linear system eps is error tolerance on n tol threshold for imaginary axis poles Description returns the Linfinity norm of g nsup sigmaxgjw w sigmax largest singular value See Also hnorm linfn 1011 Name linfn infinity norm xfreqlinfnGPRECRELTOLoptions Parameters G is a syslin list PREC desired relative accuracy on the norm RELTOL relative threshold to decide when an eigenvalue can be considered on the imaginary axis options available options are trace or cond x is the computed norm freq vector Description Computes the Linf or Hinf norm of G This norm is welldefined as soon as the realization GABCD has no imaginary eigenvalue which is both controllable and observable freq is a list of the frequencies for which G is attainedie such that G j om G If 1 is in the list the norm is attained at infinity If 2 is in the list G is allpass in some direction so that G j omega G for all frequencies omega The algorithm follows the paper by G Robel AC34 pp 882884 1989 The case D0 is not treated separately due to superior accuracy of the general method when ABC is nearly non minimal The trace option traces each bisection step ie displays the lower and upper bounds and the current test point The cond option estimates a confidence index on the computed value and issues a warning if computations are illconditioned In the general case A neither stable nor antistable no upper bound is prespecified If by contrast A is stable or anti stable lower and upper bounds are computed using the associated Lyapunov solutions See Also hnorm Authors P Gahinet 1012 Name linmeq Sylvester and Lyapunov equations solver Xsep linmeqtaskABCflagtransschur Parameters task integer option to determine the equation type 1 solve the Sylvester equation 1a or 1b 2 solve the Lyapunov equation 2a or 2b 3 solve for the Cholesky factor opX the Lyapunov equation 3a or 3b A real matrix B real matrix C real matrix flag optional integer vector of length 3 or 2 containing options task 1 flag has length 3 flag1 0 solve the continuoustime equation 1a otherwise solve the discretetime equation 1b flag2 1 A is quasi upper triangular flag2 2 A is upper Hessenberg otherwise A is in general form flag3 1 B is quasi upper triangular flag3 2 B is upper Hessenberg otherwise B is in general form task 2 flag has length 2 linmeq 1013 flag1 if 0 solve continuoustime equation 2a otherwise solve discretetime equation 2b flag2 1 A is quasi upper triangular otherwise A is in general form task 3 flag has length 2 flag1 0 solve continuoustime equation 3a otherwise solve discretetime equation 3b flag2 1 A is quasi upper triangular otherwise A is in general form Default flag1 0 flag2 0 flag3 0 trans optional integer specifying a transposition option 0 solve the equations 1 3 with opM M 1 solve the equations 1 3 with opM M 2 solve the equations 1 with opA A opB B 3 solve the equations 1 with opA A opB B Default trans 0 schur optional integer specifying whether the HessenbergSchur or Schur method should be used Available for task 1 1 HessenbergSchur method one matrix is reduced to Schur form 2 Schur method two matrices are reduced to Schur form Default schur 1 X sep optional estimator of SepopAopA for 2a or SepdAA for 2b Description linmeq function for solving Sylvester and Lyapunov equations using SLICOT routines SB04MD SB04ND SB04PD SB04QD SB04RD SB03MD and SB03OD X linmeq1ABCflagtransschur Xsep linmeq2ACflagtrans X linmeq2ACflagtrans X linmeq3ACflagtrans linmeq 1014 linmeq solves various Sylvester and Lyapunov matrix equations opAX XopB C 1a opAXopB X C 1b opAX XopA C 2a opAXopA X C 2b opAopXopX opXopXopA opCopC 3a opAopXopXopA opXopX opCopC 3b where opM M or M Comments 1 For equation 1a or 1b when schur 1 the HessenbergSchur method is used reducing one matrix to Hessenberg form and the other one to a real Schur form Otherwise both matrices are reduced to real Schur forms If one or both matrices are already reduced to SchurHessenberg forms this could be specified by flag2 and flag3 For general matrices the HessenbergSchur method could be significantly more efficient than the Schur method 2 For equation 2a or 2b matrix C is assumed symmetric 3 For equation 3a or 3b matrix A must be stable or convergent respectively 4 For equation 3a or 3b the computed matrix X is the Cholesky factor of the solution ie the real solution is opXopX where X is an upper triangular matrix Revisions V Sima Katholieke Univ Leuven Belgium May 1999 May Sep 2000 V Sima University of Bucharest Romania May 2000 Examples 1a n40m30 ArandnnCrandnmBrandmm X linmeq1ABC normAXXBC1 1b flag100 X linmeq1ABCflag normAXBXC1 linmeq 1015 2a ArandnnCrandACCC X linmeq2AC normAX XA C1 2b X linmeq2AC1 0 normAXA XC1 3a Arandnn AAmaxrealspecA1eye shift eigenvalues CrandA Xlinmeq3AC normAXXXXA CC1 3b A 002 002010 002003 012 002 014 012010002014 010 012 005 003004004 002010 003006 008 011 003002004 008 014007 012014004 011007 004 CrandA Xlinmeq3AC1 0 normAXXA XX CC1 See Also sylv lyap Authors H Xu TU Chemnitz FR Germany Dec 1998 1016 Name lqe linear quadratic estimator Kalman Filter KXlqeP21 Parameters P21 syslin list K X real matrices Description lqe returns the Kalman gain for the filtering problem in continuous or discrete time P21 is a syslin list representing the system P21AB1C2D21 P21syslincAB1C2D21 or P21syslindAB1C2D21 The input to P21 is a white noise with variance B1 Q S BigV B1 D21 D21 S R X is the solution of the stabilizing Riccati equation and AKC2 is stable In continuous time ASinvRC2XXASinvRC2XC2invRC2XQSinvRS0 KXC2SinvR In discrete time XAXAAXC2B1D21pinvC2XC2D21D21C2XAD21B1B1B1 KAXC2B1D21pinvC2XC2D21D21 xhatt1 Ext1 y0yt onestep predicted x satisfies the recursion xhatt1AKC2xhatt Kyt Examples Assume the equations lqe 1017 x Ax Ge y Cx v with E ee Qe Evv R Eev N This is equivalent to x Ax B1 w y C2x D21 w with E Ge Ge v E B1w B1w D21w bigR v D21w B1B1 B1D21 D21B1 D21D21 GQeG GN NG R To find B1D21 given GQeRN form bigR GQeG GNNG R Then WWtfullrfbigR B1W1sizeG1 D21W1sizeC21 P21syslincAB1C2D21 KXlqeP21 Example nx5ne2ny3 Adiag1nxGonesnxne Conesnynx Qenene1 Rdiag1ny Nzerosneny bigR GQeG GNNG R WWtfullrfbigRB1W1sizeG1 D21W1sizeC1 C2C P21syslincAB1C2D21 KXlqeP21 Riccati check SGNQB1B1 ASinvRC2XXASinvRC2XC2invRC2XQSinvRS Stability check specAKC See Also lqr observer Authors F D 1018 Name lqg LQG compensator KlqgPr Parameters P syslin list augmented plant in statespace form r 1x2 row vector number of measurements number of inputs dimension of the 22 part of P K syslin list controller Description lqg computes the linear optimal LQG H2 controller for the augmented plant PsyslincABCD continuous time or PsyslindABCD discrete time The function lqg2stan returns P and r given the nominal plant weighting terms and variances of noises K is given by the following ABCD matrices ABKcKfCKfDKcKfKc0 where KclqrP12 is the controller gain and KflqeP21 is the filter gain See example in lqg2stan See Also lqg2stan lqr lqe hinf obscont Authors FD 1019 Name lqg2stan LQG to standard problem Prlqg2stanP22bigQbigR Parameters P22 syslin list nominal plant in statespace form bigQ QSSN symmetric weighting matrix bigR RTTV symmetric covariance matrix r 1x2 row vector number of measurements number of inputs dimension of the 22 part of P P syslin list augmented plant Description lqg2stan returns the augmented plant for linear LQG H2 controller design P22syslindomAB2C2 is the nominal plant it can be in continuous time domc or discrete time domd x Ax w1 B2u y C2x w2 for continuous time plant xn1 Axn w1 B2u y C2x w2 for discrete time plant The instantaneous cost function is x u bigQ xu The covariance of w1w2 is Ew1w2 w1w2 bigR If B1D21 is a factor of bigQ C1D12 is a factor of bigR and AB2C2D22 is a re alization of P22 then P is a realization of AB1B2C1C20D12D21D22 The negative feedback computed by lqg stabilizes P22 ie the poles of clP22K are stable Examples ny2nu3nx4 P22ssrandnynunx bigQrandnxnunxnubigQbigQbigQ lqg2stan 1020 bigRrandnxnynxnybigRbigRbigR Prlqg2stanP22bigQbigRKlqgPr KLQGcontroller spechclPrK Closed loop should be stable Same as ClP22K specClA spoly0s lqg2stan1s2eye22eye22 See Also lqg lqr lqe obscont hinf augment fstabst feedback Authors FD 1021 Name lqgltr LQG with loop transform recovery kfkclqgltrslmuro Parameters sl linear system in statespace form syslin list muro real positive numbers chosen small enough kfkc controller and observer Kalman gains Description returns the Kalman gains for x ax bu lw1 sl y cx muIw2 z hx Cost function oo J E ztzt ro2ututdt lqg 0 The lqgltr approach looks for LmuHro such that Jlqg Jfreq where oo J trS W W S trT Tdw freq 0 and S I GK1 T GKIGK1 See Also syslin 1022 Name lqr LQ compensator full state KXlqrP12 Parameters P12 syslin list statespace linear system KX two real matrices Description lqr computes the linear optimal LQ fullstate gain for the plant P12AB2C1D12 in contin uous or discrete time P12 is a syslin list eg P12syslincAB2C1D12 The cost function is l2norm of zz with zC1 x D12 u ie xu BigQ xu where C1 Q S BigQ C1 D12 D12 S R The gain K is such that A B2K is stable X is the stabilizing solution of the Riccati equation For a continuous plant AB2invRSXXAB2invRSXB2invRB2XQSinvRS0 KinvRB2XS For a discrete plant XAXAAXB2C1D12pinvB2XB2D12D12B2XAD12C1C1C1 KpinvB2XB2D12D12B2XAD12C1 An equivalent form for X is XAbarinvinvXB2invrB2AbarQbar lqr 1023 with AbarAB2invRS and QbarQSinvRS The 3blocks matrix pencils associated with these Riccati equations are discrete continuous I 0 0 A 0 B2 I 0 0 A 0 B2 z0 A 0 Q I S s0 I 0 Q A S 0 B2 0 S 0 R 0 0 0 S B2 R Caution It is assumed that matrix R is non singular In particular the plant must be tall number of outputs number of inputs Examples Arand22Brand21 two states one input Qdiag25R2 Usual notations xQx uRu BigsysdiagQR Now we calculate C1 and D12 wwpfullrfBigC1wp12D12wp3 C1D12C1D12Big PsyslincABC1D12 The plant continuoustime KXlqrP specABK check stability normAXXAXBinvRBXQ1 Riccati check PsyslindABC1D12 Discrete time plant KXlqrP specABK check stability normAXAAXBpinvBXBRBXAQX1 Riccati check See Also lqe gcare leqr Authors FD 1024 Name ltitr discrete time response state space XltitrABUx0 xfXltitrABUx0 Parameters AB real matrices of appropriate dimensions UX real matrices x0xf real vectors default value0 for x0 Description calculates the time response of the discrete time system xt1 Axt But The inputs uis are the columns of the U matrix Uu0u1un x0 is the vector of initial state default value 0 X is the matrix of outputs same number of columns as U Xx0x1x2xn xf is the vector of final state xfXn1 Examples Aeye22B11 x012 u12345 xltitrABux0 x1Ax0Bu1 x2Ax1Bu2 x3Ax2Bu3 See Also rtitr flts 1025 Name macglov Mac Farlane Glover problem PrmacglovSl Parameters Sl linear system syslin list P linear system syslin list augmented plant r 1x2 vector dimension of P22 Description PrmacglovSl returns the standard plant P for the GloverMcFarlane problem For this problem rooptimal 1hankelnormNM with NMlcfsl Normalized coprime factorization ie gamaoptimal 1sqrtrooptimal Authors F Delebecque INRIA 1026 Name markp2ss Markov parameters to statespace slmarkp2ssmarkparnnoutnin Parameters markpar matrix nnoutnin integers Sl syslin list Description given a set of n Markov parameters stacked in the rowmatrix markpar of size noutXnnin markp2ss returns a statespace linear system sl syslin list such that with ABCDabcdsl CB markpar1nout1nin CAB markpar1noutnin12nin Examples Wssrand234 random system with 2 outputs and 3 inputs abcdabcdW markparcbcabca2bca3bca4b Smarkp2ssmarkpar523 ABCDabcdS MarkparCBCABCA2BCA3BCA4B normmarkparMarkpar1 Caution ca5b is not CA5B See Also frep2tf tf2ss imrep2ss 1027 Name minreal minimal balanced realization slbminrealsl tol Parameters slslb syslin lists tol real threshold Description aebeceminrealabcdomain tol returns the balanced realization of linear system sl syslin list sl is assumed stable tol threshold used in equil1 Examples Aeye22rand22zeros222eye22 Brand22zeros22Crand24 slsyslincABC slbminrealsl ss2tfsl ss2tfslb ctrgramsl cleanctrgramslb cleanobsgramslb See Also minss balreal arhnk equil equil1 Authors S Steer INRIA 1987 1028 Name minss minimal realization slcminss sl tol Parameters slslc syslin lists linear systems in statespace form tol real threshold for rank determination see contr Description minss returns in slc a minimal realization of sl Examples slsyslinc1 00 2102 1 ssprintsl ssprintminsssl See Also contr minreal arhnk contrss obsvss balreal 1029 Name mucomp mu structured singular value calculation BOUND D G mucompZ K T Parameters Z the complex nbyn matrix for which the structured singular value is to be computed K the vector of length m containing the block structure of the uncertainty T the vector of length m indicating the type of each block TI 1 if the corresponding block is real TI 2 if the corresponding block is complex BOUND the upper bound on the structured singular value D G vectors of length n containing the diagonal entries of the diagonal matrices D and G respectively such that the matrix ZD2Z sqrt1GZZG bound2D2 is negative semidefinite Description To compute an upper bound on the structured singular value for a given square complex matrix and given block structure of the uncertainty Reference Slicot routine AB13MD 1030 Name narsimul armax simulation using rtitr znarsimulabdsiguupypep znarsimularuupypep Description ARMAX simulation Same as arsimul but the method is different the simulation is made with rtitr Authors JPh Chancelier ENPC Cergrene 1031 Name nehari Nehari approximant xnehariR tol Parameters R linear system syslin list x linear system syslin list tol optional threshold Description xnehariR tolreturns the Nehari approximant of R R linear system in statespace representation syslin list R is strictly proper and R is stable ie R is anti stable R X oo min R Y oo Y in Hoo 1032 Name noisegen noise generation bnoisegenpasTmaxsig Description generates a Scilab function bNoiset where Noiset is a piecewise constant function constant on kpask1pas The value on each constant interval are random values from iid Gaussian variables of standard deviation sig The function is constant for t0 and tTmax Examples noisegen053010 x500135 yfevalxNoise plotxy 1033 Name obsgram observability gramian GoobsgramAC dom Goobsgramsl Parameters AC real matrices of appropriate dimensions dom string d or c default value sl syslin list Description Observability gramian of the pair AC or linear system sl syslin list dom is the domain which can be c continuous system default d discrete system Examples Adiag13Crand23 GoobsgramACc wsyslincAC Goobsgramw normGoAAGoCC1 normlyapACCcGo1 AA4 GoobsgramACd discrete time case normlyapACCdGo1 See Also ctrgram obsvss obsvmat lyap 1034 Name obscont observer based controller KobscontPKcKf JrobscontPKcKf Parameters P syslin list nominal plant in statespace form continuous or discrete time Kc real matrix full state controller gain Kf real matrix filter gain K syslin list controller J syslin list extended controller r 1x2 row vector Description obscont returns the observerbased controller associated with a nominal plant P with matrices ABCD syslin list The fullstate control gain is Kc and the filter gain is Kf These gains can be computed for example by pole placement ABKc and AKfC are usually assumed stable K is a statespace representation of the compensator K yu in xdot A x B u yC x D u zdot A Kf Cz Kf y B u uKc z K is a linear system syslin list with matrices given by KABKcKfCKfDKcKf Kc The closed loop feedback system Cl v y with negative feedback K ie y P u u v K y or xdot A x B u y C x D u zdot A Kf C z Kf y B u u v F z is given by Cl PK The poles of Cl specclA are located at the eigenvalues of ABKc and AKfC Invoked with two output arguments obscont returns a square linear system K which parametrizes all the stabilizing feedbacks via a LFT obscont 1035 Let Q an arbitrary stable linear system of dimension r2xr1 ie number of inputs x number of outputs in P Then any stabilizing controller K for P can be expressed as KlftJrQ The controller which corresponds to Q0 is KJ1nu1ny this K is returned by KobscontPKcKf r is sizeP ie the vector number of outputs number of inputs Examples ny2nu3nx4PssrandnynunxABCDabcdP KcppolAB1111 Controller gain KfppolAC2222KfKf Observer gain clPobscontPKcKfspecclA closed loop system JrobscontPKcKf Qssrandnuny3QAQAmaxirealspecQA05eyeQA Q is a stable parameter KlftJrQ spechclPK closedloop A matrix should be stable See Also ppol lqg lqr lqe hinf lft syslin feedback observer Authors FD 1036 Name observer observer design ObsobserverSysJ ObsUmobserverSys flagalfa Parameters Sys syslin list linear system J nx x ny constant matrix output injection matrix flag character strings pp or st default alfa location of closedloop poles optional parameter default1 Obs linear system syslin list the observer U orthogonal matrix see dtility m integer dimension of unstable unobservable st or unobservable pp subspace Description ObsobserverSysJ returns the observer ObssyslintdAJCBJD JeyeA obtained from Sys by a J output injection td is the time domain of Sys More gen erally observer returns in Obs an observer for the observable part of linear system Sys dotxA x Bu yCx Du represented by a syslin list Sys has nx state variables nu inputs and ny outputs Obs is a linear system with matrices AoBoIdentity where Ao is no x no Bo is no x nuny Co is no x no and nonxm Input to Obs is uy and output of Obs is xhatestimate of x modulo unobservable subsp case flagpp or xhatestimate of x modulo unstable unobservable subsp case flagst case flagst zHx can be estimated with stable observer iff HU1m0 and assignable poles of the observer are set to alfa1alfa2 case flagpp zHx can be estimated with given error spectrum iff HU1m0 all poles of the observer are assigned and set to alfa1alfa2 If H satifies the constraint HU1m0 kerH contains unobssubsp of Sys one has HU0H2 and the observer for zHx is H2Obs with H2HUm1nx ie Co the Cmatrix of the observer for Hx is CoH2 In the particular case where the pair AC of Sys is observable one has m0 and the lin ear system UObs resp HUObs is an observer for x resp Hx The error spectrum is alpha1alpha2alphanx observer 1037 Examples nx5nu1ny1un3us2Sysssrandnynunxlistdtususun nx5 states nu1 input ny1 output un3 unobservable states us2 of them unstable ObsUmobserverSys Stable observer default WUHWm1nxABCDabcdSys HU0eyenono Sys2ss2tfsyslincABH Transfer uz IdueyenunuSys3ss2tfHUm1ObsIduSys Transfer uuySysuObsxhatHUxhatzhat ie uoutput of Obs this transfer must equal Sys2 the uz transfer H2eye Assume a Kalman model dotx A x B u G w y C x D u H w v with Eww QN Evv RN Ewv NN To build a Kalman observer 1Form BigR GQNG GQNHGNN HQNGNNG HQNHRN the covariance matrix of the noise vector GwHwv 2Build the plant P21 dotx A x B1 e y C2 x D21 e with e a unit white noise WWtfullrfBigR B1W1sizeG1D21W1sizeC1 C2C P21syslincAB1C2D21 3Compute the Kalman gain L lqeP21 4 Build an observer for the plant ABCD Plant syslincABCD Obs observerPlantL Test example Adiag14 Bones41 CB D 0 G2B H3 QN2 RN5 NN0 BigR GQNG GQNHGNN HQNGNNG HQNHRN WWtfullrfBigR B1W1sizeG1D21W1sizeC1 C2C P21syslincAB1C2D21 L lqeP21 Plant syslincABCD Obs observerPlantL specObsA See Also dtility unobs stabil Authors FD 1038 Name obsvmat observability matrix OobsvmatAC Oobsvmatsl Parameters ACO real matrices sl syslin list Description obsvmat returns the observability matrix OC CA CA2 CAn1 See Also contrss obsvss obsgram 1039 Name obsvss observable part AoBoCoobsvssABC tol sloobsvsssl tol Parameters ABCAoBoCo real matrices slslo syslin lists tol real threshold default value 100eps Description sloAoBoCo is the observable part of linear system slABC syslin list tol threshold to test controllability see contr default value 100eps See Also contr contrss obsvmat obsgram 1040 Name pmargin phase margin and associated crossover frequency phmfr pmarginh phmpmarginh Parameters h a SISO linear system see syslin phm a number the phase margin in degree if it exists or an empty matrix fr a number the corresponding frequency in hz or an empty matrix Description Given a SISO linear system in continuous or discrete time pmargin returns phm the phase margin in degree of h and fr the achieved corresponding frequency in hz The phase margin is the values of the phase at frequency points where the nyquist plot of h crosses the unit circle In other words the phase margin is the difference between the phase of the frequency response of h and 180 when the gain of h is 1 The algorithm uses polynomial root finder to solve the equations hshs1 for the continuous time case hzh1z1 for the discrete time case Examples continuous case hsyslinc1s32ss2 pfrpmarginh pfrpmarginh07 showmarginsh07nyquist discrete case h syslin01004798z00464z2181z09048ok p fpmarginh showmarginshnyquist See Also pmargin showmargins repfreq black bode chart nyquist Authors Serge Steer INRIA 1041 Name parrot Parrots problem KparrotDr Parameters DK matrices r 1X2 vector dimension of the 22 part of D Description Given a matrix D partionned as D11 D12 D21 D22 where sizeD22rr1r2 compute a matrix K such that largest singular value of D11 D12 D21 D22K is minimal Parrots problem See Also hinfst 1042 Name pfss partial fraction decomposition eltspfssSl eltspfssSlrmax eltspfssSlcord eltspfssSlrmaxcord Parameters Sl syslin list statespace or transfer linear system rmax real number controlling the condition ing of block diagoanalization cord character string c or d Description Partial fraction decomposition of the linear system Sl in statespace form transfer matrices are au tomatically converted to statespace form by tf2ss elts is the list of linear systems which add up to Sl ie eltslistS1S2S3Sn with Sl S1 S2 Sn Each Si contains some poles of S according to the blockdiagonalization of the A matrix of S For non proper systems the polynomial part of Sl is put in the last entry of elts If Sl is given in transfer form it is first converted into statespace and each subsystem Si is then converted in transfer form The A matrix is of the statespace is put into block diagonal form by function bdiag The optional parameter rmax is sent to bdiag If rmax should be set to a large number to enforce blockdiago nalization If the optional flag cordc is given the elements in elts are sorted according to the real part resp magnitude if cordd of the eigenvalues of A matrices Examples Wssrand116 eltspfssW W10for k1sizeelts W1W1ss2tfeltskend cleanss2tfWW1 See Also pbig bdiag coffg dtsi Authors FD 1043 Name phasemag phase and magnitude computation phidbphasemagz mod Parameters z matrix or row vector of complex numbers mod character string modc continuous representation between infinity and 360 degrees default modm representation between 360 and 0 degrees phi phases in degree of z db magnitude in Db Description phasemag computes the phases and magnitudes of the entries of a complex matrix For modcphasemag computes phii1 to minimize the distance with phii ie it tries to obtain a continuous representation of the phase To obtain the phase between pi and pi use phiatanimagzrealz Examples spoly0s hsyslinc1s5s101006ssss3 frqrfrepfreqh01200005 scf plot2dfrqphasemagrfc scf plot2dfrqphasemagrfm See Also repfreq gainplot atan bode 1044 Name ppol pole placement KppolABpoles Parameters AB real matrices of dimensions nxn and nxm poles real or complex vector of dimension n K real matrix negative feedback gain Description KppolABpoles returns a mxn gain matrix K such that the eigenvalues of ABK are poles The pair AB must be controllable Complex number in poles must appear in conjugate pairs An outputinjection gain F for AC is obtained as follows FtppolACpoles FFt The algorithm is by PH Petkov Examples Arand33Brand32 FppolAB123 specABF See Also canon stabil 1045 Name prbsa pseudo random binary sequences generation uprbsanncids Description generation of pseudo random binary sequences uu0u1un1 u takes values in 11 and changes at most nc times its sign ids can be used to fix the date at which u must change its sign ids is then an integer vector with values in 1n Examples uprbsa5010 plot2d2onn150u1151 0155015 1046 Name projsl linear system projection slpprojslslQM Parameters slslp syslin lists QM matrices projection factorization Description slp projected model of sl where QM is the full rank factorization of the projection If ABCD is the representation of sl the projected model is given by MAQMBCQD Usually the projection QM is obtained as the spectral projection of an appropriate auxiliary matrix W eg W product of weighted gramians or product of Riccati equations Examples randseed0slssrand225ABCDabcdslpolesspecA QMpbigA0c keeping unstable poles slredprojslslQMspecslredA slDrand22 making proper system trzerossl zeros of sl wiinvsl wiinverse in statespace qmpsmallwiA2d keeping small zeros poles of wi ie absz2 slred2projslslqm trzerosslred2 zeros of slred2 small zeros of sl Example keeping second order modes Adiag123 slsyslincArand32rand23nk2Whankelsvsl QMpbigWnk22epsc keeping 2 eigenvalues of W slrprojslslQM reduced model hankelsvslr See Also pbig Authors F D 1047 Name reglin Linear regression absigreglinxy Description solve the regression problem yax b in the least square sense sig is the standard deviation of the residual x and y are two matrices of size xpn and yqn where n is the number of samples The estimator a is a matrix of size qp and b is a vector of size q1 simulation of data for a35 and b31 xrand5100 aatestmatrixmagi5aaaa13 bb91011 yaax bbones1100 01rand3100 identification absigreglinxy maxiabsaaa maxiabsbbb an other example fitting a polynom f1100 xff f y 23x 10onesf 01randf abreglinxy See Also pinv leastsq qr 1048 Name repfreq frequency response frq repfrepfreqsysfminfmax step frq repfrepfreqsys frq frqrepfsplitfrepfreqsysfminfmax step frqrepfsplitfrepfreqsys frq Parameters sys syslin list SIMO linear system fminfmax two real numbers lower and upper frequency bounds frq real vector of frequencies Hz step logarithmic discretization step splitf vector of indexes of critical frequencies repf vector of the complex frequency response Description repfreq returns the frequency response calculation of a linear system If syss is the transfer function of Sys repfk equals syss evaluated at s ifrqk2pi for continuous time systems and at exp2ipidtfrqk for discrete time systems dt is the sampling period dbk is the magnitude of repfk expressed in dB ie dbk20log10absrepfk and phik is the phase of repfk expressed in degrees If fminfmaxstep are input parameters the response is calculated for the vector of frequencies frq given by frq10log10fminsteplog10fmax fmax If step is not given the output parameter frq is calculated by frqcalfrqsysfminfmax Vector frq is splitted into regular parts with the split vector frqsplitfksplitfk 11 has no critical frequency sys has a pole in the range frqsplitfkfrqsplitfk1 and no poles outside Examples Adiag12B11C11 SyssyslincABC frq00025wfrq2pi frqfrequencies in Hz wfrequencies in radsec frq1rep repfreqSysfrq dbphidbphirep Systfss2tfSys Transfer function of Sys xhornerSystfw2sqrt1 x is Systfs evaluated at s i w2 repfreq 1049 rep20logabsxlog10 magnitude of x in dB db2 same as rep angatanimagxrealx in rad angang180pi in degrees phi2 repfrepfreqSysfrq repf2x See Also bode freq calfrq horner nyquist dbphi Authors S S 1050 Name ricdesc Riccati equation XricdescH E X1X2zeroricdescH E Parameters HE real square matrices X1X2 real square matrices zero real number Description Riccati solver with hamiltonian matrices as inputs In the continuous time case calling sequence is ricdescrH one input Riccati equation is Ec AX XA XRX Q 0 Defining the hamiltonian matrix H by H A R Q A with the calling sequence X1X2zeroricdescrH the solution X is given by XX1X2 zero L1 norm of rhs of Ec The solution X is also given by XriccatiAQRc In the discretetime case calling sequence is ricdescrHE two inputs The Riccati equation is Ed AXAAXBRBXB1BXACX 0 Defining GBRB and the hamiltonian pencil EH by EeyennG HA 0onesnn 0onesnnA C eyenn with the calling sequence X1X2errricdescrHE the solution X is given by XX1 X2 ricdesc 1051 zero L1 norm of rhs of Ed The solution X is also given by XriccatiAGCd with GBRB See Also riccati 1052 Name ricc Riccati equation XRCONDFERRriccABCcontmethod XRCONDFERRriccFGHdiscmethod Parameters ABC real matrices of appropriate dimensions FGH real matrices of appropriate dimensions X real matrix contdisc imposed string flag for continuous or discrete method schr or sign for continuoustime systems and schr or invf for discretetyme systems Description Riccati solver Continuous time XriccABCcont gives a solution to the continuous time ARE AXXAXBXC0 B and C are assumed to be nonnegative definite AG is assumed to be stabilizable with GG a full rank factorization of B AH is assumed to be detectable with HH a full rank factorization of C Discrete time XriccFGHdisc gives a solution to the discrete time ARE XFXFFXG1G2G1XG11G1XFH F is assumed invertible and G G1invG2G1 One assumes FG1 stabilizable and CF detectable with CC full rank factorization of H Use preferably ricdesc ricc 1053 C D are symmetric It is assumed that the matrices A C and D are such that the corresponding matrix pencil has N eigenvalues with moduli less than one Error bound on the solution and a condition estimate are also provided It is assumed that the matrices A C and D are such that the corresponding Hamiltonian matrix has N eigenvalues with negative real parts Examples Standard formulas to compute Riccati solutions Arand33Brand32Crand33CCCRrand22RRReye BBinvRB XriccABCcont normAXXAXBXC1 HA BC A TdschureyeHHcontTT1d X1T46T13 normX1X1 TdschurHcontTT1d X2T46T13 normX2X1 Discrete time case FABrand32G1BG2RGG1G2G1HC XriccFGHdisc normFXFFXG1G2G1XG1G1XFHX H1eye33 Gzeros33 F H2F zeros33H eye33 TdschurH2H1discTT1dX1T46T13 normX1X1 FiinvF HamiFi FiGHFi FHFiG TdschurHamidTT1d FitinvF HamFGFitH GFitFitH Fit TdschurHamdTT1dX2T46T13 normX2X1 See Also riccati ricdesc schur Authors P Petkov Used Functions See SCImodulescacsdsrcslicotriccpackf 1054 Name riccati Riccati equation XriccatiABCdomtyp X1X2riccatiABCdomtyp Parameters ABC real matrices nxn B and C symmetric dom c or d for the time domain continuous or discrete typ string eigen for block diagonalization or schur for Schur method X1X2X square real matrices X2 invertible X symmetric Description XriccatiABCdomtyp solves the Riccati equation AXXAXBXC0 in continuous time case or AXAAXB1B2B1XB1B1XACX with BB1B2B1 in the discrete time case If called with two output arguments riccati returns X1X2 such that XX1X2 See Also ricc ricdesc 1055 Name rowinout innerouter factorization InnXGbarrowinoutG Parameters G linear system syslin list ABCD Inn inner factor syslin list Gbar outer factor syslin list X rowcompressor of G syslin list Description Innerouter factorization and row compression of lxp G ABCD with lp G is assumed to be tall lp without zero on the imaginary axis and with a D matrix which is full column rank G must also be stable for having Gbar stable G admits the following innerouter factorization G Inn Gbar 0 where Inn is square and inner all pass and stable and Gbar square and outer ie Gbar is square bi proper and bistable Gbar inverse is also proper and stable Note that Gbar XG 0 is a row compression of G where X Inn inverse is allpass ie T X s Xs Identity for the continuous time case See Also syslin colinout 1056 Name rowregul removing poles and zeros at infinity StmpWsrowregulSlalfabeta Parameters SlStmp syslin lists alfabeta real numbers new pole and zero positions Description computes a postfilter Ws such that StmpWsSl is proper and with full rank D matrix Poles at infinity of Sl are moved to alfa Zeros at infinity of Sl are moved to beta Sl is a assumed to be a right invertible linear system syslin list in statespace representation with possibly a polynomial D matrix This function is the dual of colregul see function code Examples ss w1s0ss322s Sltf2ssw StmpWsrowregulSl12 StmpD D matrix of Stmp cleanss2tfStmp See Also invsyslin colregul Authors F D R N 1057 Name rtitr discrete time response transfer matrix yrtitrNumDenu upyp Parameters NumDen polynomial matrices resp dimensions nxm and nxn u real matrix dimension mxt1 upyp real matrices up dimension mxmaxidegreeDen default values0 yp dimension nx maxidegreeDen y real matrix Description yrtitrNumDenu upyp returns the time response of the discrete time linear system with transfer matrix Den1 Num for the input u ie y and u are such that Den y Num u at t01 If d1maxidegreeDen and d2maxidegreeNum the polynomial matrices Denz and Numz may be written respectively as Dz D0 D1 z Dd1 zd1 Nz N0 N1 z Nd2 zd2 and Den y Num u is interpreted as the recursion D0ytD1yt1 Dd1ytd1 N0 ut Nd2 utd2 It is assumed that Dd1 is non singular The columns of u are the inputs of the system at t01T uu0 u1uT The outputs at t01Td1d2 are the columns of the matrix y y y0 y1 yTd1d2 up and yp define the initial conditions for t 0 ie up ud1 u1 rtitr 1058 yp yd1 y1 Depending on the relative values of d1 and d2 some of the leftmost components of up yp are ignored The default values of up and yp are zero up 0onesmd1 yp0onesnd1 Examples zpoly0z Num1zDen1zu12345 rtitrNumDenuu Other examples siso causal n11d1poly1 1zcoeff yjyj1uj1 r10 1 0 1 0 1 0 1 0 1 0 rrtitrn1d1ones110normr1r1 hot restart rrtitrn1d1ones1910normr1211r non causal n2poly1 1 1zcoeffd2d1 yjyj1uj1ujuj1 r22 1 2 1 2 1 2 1 2 rrtitrn2d2ones110normrr21 hot restart rrtitrn2d2ones1912normr229r1 MIMO example causal d1d1diag1 05n11 3 12 4 1r1514r1 rrtitrn1d1ones310normr1r1 rrtitrn1d1ones3911100 normr1211r1 polynomial n1 same ex n111poly1zcrrtitrn1d1ones310normr1r1 rrtitrn1d1ones3911100 normr1211r1 non causal d2d1n2n2n1r2514r2 rrtitrn2d2ones310normr2r rrtitrn2d2ones391111028 normr229r1 Statespace or transfer a 021 063 056 023 031 076 085 066 023 093 0 069 073 022 021 033 088 02 088 031 067 007 054 065 036 b 029 05 092 057 044 004 048 027 048 033 063 026 059 041 041 c 028 078 011 015 084 rtitr 1059 013 021 069 07 041 d 041 011 056 088 02 059 ssyslindabcd hss2tfsnumhnumdenhdendenden11eye22 u1u3100r3fltsus rrtitrnumdenunormr3r1 See Also ltitr exp flts 1060 Name sensi sensitivity functions SeReTesensiGK SiRiTisensiGKflag Parameters G standard plant syslin list K compensator syslin list flag character string o default value or i Se output sensitivity function IGK1 Re KSe Te GKSe output complementary sensitivity function Description sensi computes sensitivity functions If G and K are given in statespace form the systems returned are generically minimal Calculation is made by lft eg Se can be given by the commands P augmentGS SelftPK If flag i SiRiTisensiGKi returns the input sensitivity functions SeReTe inveyeGKKinveyeGKGKinveyeGK SiRiTi inveyeKGGinveyeKGKGinveyeKG Examples Gssrand113Kssrand113 SeReTesensiGK Se1inveyeGK Other way to compute ss2tfSe Se seen in transfer form ss2tfSe1 ss2tfTe ss2tfGKSe1 SiRiTisensiGKi w1ss2tfSiss2tfRiss2tfTi w2ss2tfinveyeKGss2tfGinveyeKGss2tfKGinveyeKG cleanw1w2 See Also augment lft hcl 1061 Name showmargins display gain and phase margin and associated crossover frequencies showmarginsh showmarginshbode showmarginshnyquist Parameters h a SISO linear system see syslin Description Given a SISO linear system in continuous or discrete time showmargins display gain and phase margin and associated crossover frequencies on a bode the defaut or nyquist representation of the frequency response of the system Examples continuous case hsyslinc002909011827s012823s2035659s30256s401s5 0040901827s128225s231909s3256s4s5 showmarginsh showmarginshnyquist discrete case h syslin01001547001599z z2181z09048 showmarginsh showmarginshnyquist See Also pmargin gmargin bode nyquist Authors Serge Steer INRIA 1062 Name sident discretetime statespace realization and Kalman gain ACBDKQRySrcnd sidentmethjobsnlRtoltAi Ciprintw Parameters meth integer option to determine the method to use 1 MOESP method with past inputs and outputs 2 N4SID method 3 combined method A and C via MOESP B and D via N4SID job integer option to determine the calculation to be performed 1 compute all system matrices A B C D 2 compute the matrices A and C only 3 compute the matrix B only 4 compute the matrices B and D only s the number of block rows in the processed input and output block Hankel matrices s 0 n integer the order of the system l integer the number of the system outputs R the 2mlsby2mls part of R contains the processed upper triangular factor R from the QR factorization of the concatenated blockHankel matrices and further details needed for com puting system matrices tol optional tolerance used for estimating the rank of matrices If tol 0 then the given value of tol is used as a lower bound for the reciprocal condition number an mbyn matrix whose estimated condition number is less than 1tol is considered to be of full rank Default mnepsilonmachine where epsilonmachine is the relative machine precision t optional the total number of samples used for calculating the covariance matrices Either t 0 or t 2mls This parameter is not needed if the covariance matrices andor the Kalman predictor gain matrix are not desired If t 0 then K Q Ry and S are not computed Default t 0 sident 1063 Ai real matrix Ci real matrix printw optional switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default printw 0 A real matrix C real matrix B real matrix D real matrix K real matrix kalman gain Q optional the nbyn positive semidefinite state covariance matrix used as state weighting matrix when computing the Kalman gain RY optional the lbyl positive semidefinite output covariance matrix used as output weighting matrix when computing the Kalman gain S optional the nbyl stateoutput crosscovariance matrix used as crossweighting matrix when computing the Kalman gain rcnd optional vector of length lr containing estimates of the reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions where lr 4 if Kalman gain matrix K is not required and lr 12 if Kalman gain matrix K is required Description SIDENT function for computing a discretetime statespace realization ABCD and Kalman gain K using SLICOT routine IB01BD ACBD sidentmeth1snlR ACBDKQRySrcnd sidentmeth1snlRtolt AC sidentmeth2snlR B sidentmeth3snlRtol0AiCi BKQRySrcnd sidentmeth3snlRtoltAiCi sident 1064 BD sidentmeth4snlRtol0AiCi BDKQRySrcnd sidentmeth4snlRtoltAiCi SIDENT computes a statespace realization ABCD and the Kalman predictor gain K of a dis cretetime system given the system order and the relevant part of the R factor of the concatenated blockHankel matrices using subspace identification techniques MOESP N4SID or their combina tion The model structure is xk1 Axk Buk Kek k 1 yk Cxk Duk ek where xk is the ndimensional state vector at time k uk is the mdimensional input vector yk is the ldimensional output vector ek is the ldimensional disturbance vector and A B C D and K are real matrices of appropriate dimensions Comments 1 The nbyn system state matrix A and the pbyn system output matrix C are computed for job 2 2 The nbym system input matrix B is computed for job 2 3 The lbym system matrix D is computed for job 1 or 4 4 The nbyl Kalman predictor gain matrix K and the covariance matrices Q Ry and S are computed for t 0 Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal S 15 N 3 METH1 RN1 findRSYUMETH ACBDK sidentMETH1SN1R SYS1syslin1ABCD SYS1X0 inistateSYS1YU sident 1065 Y1fltsUSYS1 clfplot2d1nsmpYY1 METH 2 RN1SVAL findRSYUMETH tol 0 t sizeU12S1 ACBDK sidentMETH1SN1Rtolt SYS1syslin1ABCD SYS1X0 inistateSYS1YU Y1fltsUSYS1 clfplot2d1nsmpYY1 See Also findBD sorder Authors V Sima Research Institute for Informatics Bucharest Oct 1999 Revisions May 2000 July 2000 1066 Name sm2des system matrix to descriptor Dessm2desSm Parameters Sm polynomial matrix pencil system matrix Des descriptor system listdesABCDE Description Utility function converts the system matrix Sm sE A B C D to descriptor system DeslistdesABCDE See Also ss2des sm2ss 1067 Name sm2ss system matrix to statespace Slsm2ssSm Parameters Sm polynomial matrix pencil system matrix Sl linear system syslin list Description Utility function converts the system matrix Sm sI A B C D to linear system in statespace representation syslin list See Also ss2des 1068 Name sorder computing the order of a discretetime system Ronsvalrcnd sordermethalgjobdbatchconctsYUtol printwldworkRi Parameters meth integer option to determine the method to use 1 MOESP method with past inputs and outputs 2 N4SID method alg integer option to determine the algorithm for computing the triangular factor of the concatenated blockHankel matrices built from the inputoutput data 1 Cholesky algorithm on the correlation matrix 2 fast QR algorithm 3 standard QR algorithm jobd integer option to specify if the matrices B and D should later be computed using the MOESP approach 1 the matrices B and D should later be computed using the MOESP approach 2 the matrices B and D should not be computed using the MOESP approach This parameter is not relevant for meth 2 batch integer option to specify whether or not sequential data processing is to be used and for sequential processing whether or not the current data block is the first block an intermediate block or the last block as follows 1 the first block in sequential data processing 2 an intermediate block in sequential data processing 3 the last block in sequential data processing 4 one block only nonsequential data processing sorder 1069 conct integer option to specify whether or not the successive data blocks in sequential data processing belong to a single experiment as follows 1 the current data block is a continuation of the previous data block andor it will be con tinued by the next data block 2 there is no connection between the current data block and the previous andor the next ones This parameter is not used if batch 4 s the number of block rows in the input and output block Hankel matrices to be processed s 0 Y the tbyl outputdata sequence matrix Column j of Y contains the t values of the jth output component for consecutive time increments U optional the tbym inputdata sequence matrix Column j of U contains the t values of the jth input component for consecutive time increments Default U tol optional vector of length 2 containing tolerances tol1 tolerance used for estimating the rank of matrices If tol1 0 then the given value of tol1 is used as a lower bound for the reciprocal condition number an mbyn matrix whose estimated condition number is less than 1tol1 is considered to be of full rank If tol1 0 then a default value mnepsilonmachine is used where epsilonmachine is the relative machine precision tol2 tolerance used for determining an estimate of the system order If tol2 0 the estimate is indicated by the index of the last singular value greater than or equal to tol2 Singular values less than tol2 are considered as zero When tol2 0 an internally computed default value tol2 sepsilonmachinesval1 is used where sval1 is the maximal singular value and epsilonmachine the relative machine precision When tol2 0 the estimate is indicated by the index of the singular value that has the largest logarithmic gap to its successor Default tol12 01 printw optional switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default printw 0 ldwork optional the workspace size Default computed by the formulas nr 2 m l s LDWORK t 2s 3 64 nr if CSIZE MAX nrnr t m l 16 2nr then LDWORK MIN LDWORK CSIZE nrnr t m l 16 else LDWORK MIN LDWORK MAX 2nr CSIZE2 sorder 1070 end if LDWORK MAX minimum workspace size needed LDWORK where CSIZE is the cache size in double precision words If LDWORK is specified less than the minimum workspace size needed that minimum value is used instead Ri optional if batch 2 or 3 the 2mlsby2mls upper triangular if alg 2 part of R must contain the upper triangular matrix R computed at the previous call of this mexfile in sequential data processing If conct 1 R has an additional column also set at the previous call If alg 2 R has ml1 additional columns set at the previous call This parameter is not used for batch 1 or batch 4 Ro if batch 3 or 4 the 2mlsby2mls part of R contains the processed upper triangular factor R from the QR factorization of the concatenated blockHankel matrices and further details needed for computing system matrices If batch 1 or 2 then R contains intermediate results needed at the next call of this mexfile If batch 1 or 2 and conct 1 R has an additional column also set before return If batch 1 or 2 and alg 2 R has ml1 additional columns set before return n the order of the system sval optional the singular values used for estimating the order of the system rcnd optional if meth 2 vector of length 2 containing the reciprocal condition numbers of the matrices involved in rank decisions or least squares solutions Description sorder function for computing the order of a discretetime system using SLICOT routine IB01AD For one block data sequences Y U Rnsvalrcnd sordermethalgjobd4conctsYU For f blocks data sequences Yj Uj j 1 f R sordermethalgjobd1conctsY1U1 for j 2 f 1 R sordermethalgjobd2conctsYjUjtolprintwldworkR end Rnsvalrcnd sordermethalgjobd3conctsYfUftol sorder preprocesses the inputoutput data for estimating the matrices of a linear timeinvariant dynam ical system using Cholesky or fast QR factorization and subspace identification techniques MOE SP and N4SID and then estimates the order of a discretetime realization The model structure is xk1 Axk Buk wk k 1 sorder 1071 yk Cxk Duk ek where xk is the ndimensional state vector at time k uk is the mdimensional input vector yk is the ldimensional output vector wk is the ndimensional state disturbance vector ek is the ldimensional output disturbance vector and A B C and D are real matrices of appropriate dimensions Comments 1 The Cholesy or fast QR algorithms can be much faster for large data blocks than QR algorithm but they cannot be used if the correlation matrix HH is not positive definite In such a case the code automatically switches to the QR algorithm if sufficient workspace is provided and batch 4 2 If ldwork is specified but it is less than the minimum workspace size needed that minimum value is used instead See Also findBD sident Authors V Sima Research Institute for Informatics Bucharest Oct 1999 Revisions V Sima May 2000 July 2000 1072 Name specfact spectral factor W0LspecfactABCD Description Given a spectral density matrix phis 1 1 R CsIA B BsIA C with RDD 0 specfact computes W0 and L such that WsW0LsIA1B is a spectral factor of of PHIs ie phisWsWs Examples Adiag12B11C11D1spoly0s W1syslincABCD phigtildW1cW1 phiscleanss2tfphi cleanphishornerphiss check this is 0 ABCDabcdW1 W0LspecfactABCD WsyslincABLW0 Wsss2tfW hornerWssWs See Also gtild sfact fspecg Authors F D 1073 Name ss2des polynomial statespace to descriptor form Sss2desSl Sss2desSlflag Parameters Sl syslin list proper or improper linear system flag character string withD S list Description Given the linear system in statespace representation Sl syslin list with a D matrix which is either polynomial or constant but not zero ss2des returns a descriptor system as listdesABC0E such that SlCsEA1B If the flag withD is given SlistdesABCDE with a D matrix of maximal rank Examples spoly0s G1s1s1s23s3Sltf2ssG Sss2desSl S1ss2desSlwithD Desdes2ssSDes5cleanDes5 Des1des2ssS1 See Also pol2des tf2des des2ss Authors F D 1074 Name ss2ss statespace to statespace conversion feedback injection Sl1rightleftss2ssSlT F G flag Parameters Sl linear system syslin list in statespace form T square nonsingular matrix Sl1 right left linear systems syslin lists in statespace form F real matrix state feedback gain G real matrix output injection gain Description Returns the linear system Sl1A1B1C1D1 where A1invTAT B1invTB C1CT D1D Optional parameters F and G are state feedback and output injection respectively For example Sl1ss2ssSlTF returns Sl1 with and right is a non singular linear system such that Sl1Slright Sl1invright is a factorization of Sl Sl1ss2ssSlT0FG returns Sl1 with and left is a non singular linear system such that Sl1leftSl rightId if F0 When both F and G are given Sl1leftSlright When flag is used and flag1 an output injection as follows is used and then a feedback is performed F must be of size mpn ss2ss 1075 right and left have the following property Sl1 leftsysdiagsyseyeppright When flag is used and flag2 a feedback F must be of size mn is performed and then the above output injection is applied right and left have the following property Sl1 leftsysdiagsysrighteyepp Examples Slssrand225 trzerosSl zeros are invariant Sl1ss2ssSlrand55rand25rand52 trzerosSl1 trzerosrand22Sl1rand22 output injection A GC BGDG C D 0 p1m2n2 sysssrandpmn feedback mn first and then output injection F1randmn Grandnp sys1rightleftss2sssysrandnnF1G2 Sl1 equiv leftsysdiagsysrighteyepp rescleanss2tfsys1 ss2tfleftsysdiagsysrighteyepp output injection then feedback mpn F2randpn FF1F2 sys2rightleftss2sssysrandnnFG1 Sl1 equiv leftsysdiagsyseyeppright rescleanss2tfsys2ss2tfleftsysdiagsyseyeppright when F2 0 sys1 and sys2 are the same F20randpnFF1F2 sys2rightleftss2sssysrandnnFG1 rescleanss2tfsys2ss2tfsys1 See Also projsl feedback 1076 Name ss2tf conversion from statespace to transfer function hss2tfsl DsNUMchiss2tfsl hss2tfslb DsNUMchiss2tfslb hss2tfslrmax DsNUMchiss2tfslrmax Parameters sl linear system syslin list h transfer matrix Description Called with three outputs DsNUMchiss2tfsl returns the numerator polynomial matrix NUM the characteristic polynomial chi and the polynomial part Ds separately ie h NUMchi Ds Method One uses the characteristic polynomial and detAEijdetACij where C is the adju gate matrix of A With rmax or b argument uses a block diagonalization of slA matrix and applies Leverrier algorithm on blocks If given rmax controls the conditionning see bdiag Examples spoly0s h11s1s21ss22 sltf2ssh hcleanss2tfsl DsNUMchiss2tfsl See Also tf2ss syslin nlev glever 1077 Name stility stabilizability test ns nc U Slo stilitySl tol Parameters Sl syslin list linear system ns integer dimension of stabilizable subspace nc integer dimension of controllable subspace nc ns U basis such that its ns resp nc first components span the stabilizable resp controllable sub space Slo a linear system syslin list tol threshold for controllability detection see contr Description Slo UAU UB CU D Ux0 syslin list displays the stabilizable form of Sl Stabilizability means nsnx dim of A matrix UAU 0 UB 0 00 0 where A11B1 dimA11 nc is controllable and A22 dimA22nsnc is stable Stable means real part of eigenvalues negative for a continuous linear system and magnitude of eigenvalues lower than one for a discretetime system as defined by syslin Examples Adiag0923B001SlsyslincAB nsncUstilitySl UAU UB nsncUstilitysyslindAB UAU UB See Also dtility contr stabil ssrand stility 1078 Authors S Steer INRIA 1988 1079 Name stabil stabilization FstabilABalfa KstabilSysalfabeta Parameters A square real matrix nx x nx B real matrix nx x nu alfa beta real or complex vector in conjugate pairs or real number F real matrix nx x nu Sys linear system syslin list m inputs p outputs K linear system p inputs m outputs Description FstabilABalfa returns a gain matrix F such that ABF is stable if pair AB is stabiliz able Assignable poles are set to alfa1alfa2 If AB is not stabilizable a warning is given and assignable poles are set to alfa1alfa2 If alfa is a number all eigen values are set to this alfa default value is alfa1 KstabilSysalfabeta returns K a compensator for Sys such that ABcontrollable eigenvalues are set to alfa and CAobservable eigenvalues are set to beta All assignable closed loop poles which are given by the eigenvalues of AclosedhclSysK are set to alfais and betajs Examples Gain Sysssrand025listst233 ASysABSysBFstabilAB specA 2 controllable modes 2 unstable uncontrollable modes and one stable uncontrollable mode specABF the two controllable modes are set to 1 Compensator Sysssrand325listst233 3 outputs 2 inputs 5 states 2 controllables modes 3 controllable or stabilizable modes KstabilSys23 Compensator for Sys specSysA spechclSysK K Stabilizes what can be stabilized See Also stility contr ppol 1080 Name svplot singularvalue sigmaplot SVMsvplotslw Parameters sl syslin list continuous discrete or sampled system w real vector optional parameter Description computes for the system slABCD the singular values of its transfer function matrix Gjw CjwIAB1D or Gexpjw CexpjwIAB1D or GexpjwT CexpjwTIAB1D evaluated over the frequency range specified by w T is the sampling period Tsldt for sam pled systems sl is a syslin list representing the system ABCD in statespace form sl can be continuous or discrete time or sampled system The ith column of the output matrix SVM contains the singular values of G for the ith frequency value wi SVM svplotsl is equivalent to SVM svplotsllogspace33 continuous SVM svplotsllogspace3pi discrete Examples xlogspace33 ysvplotssrand224x clfplot2d1olnx20logylog10 xgrid12 xtitleSingular values plotRdsec Db Authors FD 1082 Name sysfact system factorization SSeriessysfactSysGainflag Parameters Sys syslin list containing the matrices ABCD Gain real matrix flag string post or pre S syslin list Series syslin list Description If flag equals post sysfact returns in S the linear system with ABCD matrices A BGain B Gain I and Series a minimal realization of the series system SysS If flag equals pre sysfact returns the linear system AGainC Gain C I and Series a minimal realization of the series system SSys Examples Kalman filter Sysssrand324SysDrand32 SsysfactSyslqrSyspost wwminssSysS ss2tfgtildwwwwSysDSysD Kernel Sysssrand234 XdFUkZabinvSys ss2tfSysZ ss2tfSyssysfactSysFpostU See Also lqr lqe Authors FD 1083 Name syssize size of statespace system rnxsyssizeSl Parameters Sl linear system syslin list in statespace r 1 x 2 real vector nx integer Description returns in r the vector number of outputs number of inputs of the linear system Sl nx is the number of states of Sl See Also size 1084 Name tf2des transfer function to descriptor Stf2desG Stf2desGflag Parameters G linear system syslin list with possibly polynomial D matrix flag character string withD S list Description Transfer function to descriptor form SlistdABCDE Exdot AxBu y Cx Du Note that D0 if the optional parameter flagwithD is not given Otherwise a maximal rank D matrix is returned in the fifth entry of the list S Examples spoly0s G1s1s12s3 S1tf2desGdes2tfS1 S2tf2desGwithDdes2tfS2 See Also pol2des tf2ss ss2des des2tf 1085 Name tf2ss transfer to statespace sltf2ssh tol Parameters h rational matrix tol may be the constant rtol or the 2 vector rtol atol rtol tolerance used when evaluating observability atol absolute tolerance used when evaluating observability sl linear system syslin list slABCDs Description transfer to statespace conversion hCseyeA1BDs Examples spoly0s H2ss1s25 Systf2ssH cleanss2tfSys See Also ss2tf tf2des des2tf 1086 Name timeid SISO least square identification H errtimeidnuy Parameters n order of transfer u one of the following u1 a vector of inputs to the system impuls if y is an impulse response step if y is a step response y vector of response H rational function with degree n denominator and degree n1 numerator if y10 or rational function with degree n denominator and numerator if y10 err y impulsHnpt2 where impulsHnpt are the npt first coefficients of impulse response of H Description Identification of discrete time response If y is strictly proper y10 then timeid com putes the least square solution of the linear equation DenyNumu0 with the constraint coeffDenn1 if y10 then the algorithm first computes the proper part solution and then add y1 to the solution Examples zpoly0z h12zz205z5 rep0ldivhnumhden20 impulse response Htimeid2impulsrep Same example with flts and u uzeros120u11 repfltsutf2ssh impulse response Htimeid2urep step response uones120 repfltsutf2ssh step response Htimeid2steprep Htimeid3urep with u as input and too high order required timeid 1087 See Also imrep2ss arl2 armax frep2tf Authors Serge Steer INRIA 1088 Name trzeros transmission zeros and normal rank trtrzerosSl ntdtrktrzerosSl Parameters Sl linear system syslin list nt complex vectors dt real vector rk integer normal rank of Sl Description Called with one output argument trzerosSl returns the transmission zeros of the linear system Sl Sl may have a polynomial but square D matrix Called with 2 output arguments trzeros returns the transmission zeros of the linear system Sl as trntdt Note that some components of dt may be zeros Called with 3 output arguments rk is the normal rank of Sl Transfer matrices are converted to statespace If Sl is a square polynomial matrix trzeros returns the roots of its determinant For usual statespace system trzeros uses the statespace algorithm of EmamiNaeni and Van Dooren If D is invertible the transmission zeros are the eigenvalues of the A matrix of the inverse system A BinvDC If CB is invertible the transmission zeros are the eigenvalues of NAM where MN is a full rank factorization of eyeABinvCBC For systems with a polynomial D matrix zeros are calculated as the roots of the determinant of the system matrix Caution the computed zeros are not always reliable in particular in case of repeated zeros Examples W1ssrand225trzerosW1 call trzeros rootsdetsystmatW1 roots of detsystem matrix spoly0sW1s11s2W2s3WWntdtrktrzerosW2 trzeros 1089 Stsystmattf2ssW2QZQdZdnumbepsnumbetakroneckSt St1QStZrowfQd1Qd21Qd1Qd2Qd3 colfZd1Zd21Zd1Zd2Zd3 rootsSt1rowfcolf ntdt By Kronecker form See Also gspec kroneck 1090 Name uiobserver unknown input observer UIobsJNuiobserverSysrejectC1D1 UIobsJNuiobserverSysrejectC1D1flagalfabeta Parameters Sys syslin list containing the matrices ABC2D2 reject integer vector indices of inputs of Sys which are unknown C1 real matrix D1 real matrix C1 and D1 have the same number of rows flag string ge or st default or pp alfa real or complex vector loc of closed loop poles beta real or complex vector loc of closed loop poles Description Unknown input observer Sys wu y is a ABC2D2 syslin linear system with two inputs w and u w being the unknown input The matrices B and D2 of Sys are implicitly partitioned as BB1B2 and D2D21D22 with B1Breject and D21D2reject where reject indices of unknown inputs The matrices C1 and D1 define z C1 x D1 wu the tobeestimated output The matrix D1 is implicitly partitioned as D1D11D12 with D11Dreject The data Sys rejectC1 D1 define a 2input 2output system xdot A x B1 w B2 u z C1 x D11 w D12 u y C2 x D21 w D22 u An observer uy zhat is looked for the output z flagge no stability constraints flagst stable observer default flagpp observer with pole placement alfabeta desired location of closed loop poles default 1 2 Jyoutput to x state injection Nyoutput to zestimated output injection UIobs linear system uy zhat such that The transfer function wu z equals the com posed transfer function 0I UIobs Sys wu uy zhat ie transfer function of system ABC1D1 equals transfer function UIobs0I Sys uiobserver 1091 Stability resp pole placement requires detectability resp observability of AC2 Examples Adiag337448 Beye33zeros33 C001234000001 D123000 randseed0wss2sssyslincABCDrand66 ABCDabcdw BBmatrix11863DDmatrix1623 reject13 SyssyslincABCD N123C1N1CD1N1D nwlengthrejectnusizeSysB2nw nysizeSysC1nzsizeC11 UIobsJNuiobserverSysrejectC1D1 WzerosnunweyenunuSysUIobsWUIobsW wu zUIobs0ISyswu cleanss2tfUIobsW wutozsyslincABC1D1cleanss2tfwutoz cleanss2tfwutozss2tfUIobsW1d7 2nd example nx2ny3nwu2Sysssrandnynwunx C1rand1nxD101 UIobsuiobserverSys1C1D1 See Also cainv ddp abinv Authors FD 1092 Name unobs unobservable subspace nUunobsACtol Parameters A C real matrices tol tolerance used when evaluating ranks QR factorizations n dimension of unobservable subspace U orthogonal change of basis which puts AB in canonical form Description nUunobsACtol gives the unobservable form of an AC pair The n first columns of U make a basis for the unobservable subspace The 21 block made of last nxn rows and n first columns of UAU is zero and and the n first columns of CU are zero Examples Adiag123C100 unobsAC See Also contr contrss canon contmat spantwo dtility 1093 Name zeropen zero pencil ZUzeropenSl Parameters Sl a linear system syslin list in statespace form ABCD Z matrix pencil ZsEA U square orthogonal matrix Description Z sE F is the zero pencil of the linear system Sl with matrices ABCD Utility function With U row compression of BD ie UBD0 one has UsIA B Z 0 C D The zeros of Z are the zeros of Sl See Also systmat kroneck Parte X Estructuras de Datos 1095 Name cell cria um cell célula de matrizes vazias ccell ccellm1 ccellm1 m2 ccellm1 m2 mn ccellx Parâmetros x vetor contendo as dimensões do cell a ser criado m1 m2 dimensões do cell a ser criado Descrição retorna um cell de matrizes vazias cell retorna um cell 00 de matrizes vazias cellm1 retorna um cell m1m1 de matrizes vazias cellm1m2 retorna um cell m1m2 de matrizes vazias cellm1m2mn retorna um cell m1m2mn de matrizes vazias cellx retorna um cell de matrizes vazias com a primeira dimensão sendo x1 a segunda sendo x2 Observações cellx não possui o mesmo tamanho que x cell é equivalente a cell0 Se A for um cell você pode acessar os conteúdos de um elemento de A utilizando Am1 m2 mnentries A expressão A11 zeros22 não é válida a sintaxe correta é A11entries zeros22 Se A é um cell você pode obter suas dimensões através de Adims Exemplos acell3 bcell31 ccell234 cell 1096 atribuição em entradas do cell bcell31 atribuindo o primeiro elemento de b utilizando o campo entries b1entries13 atribuindo o segundo elemento de b utilizando o campo entries b2entriesScilab atribuindo o terceiro elemento de b utilizando o campo entries b3entriespoly13s atribuição de subcells Xcell32 X1b extraindo um subcell o resultado é um cell b1 b12 extraindo o valor de um subcell o resultado é um array b1entries dimensões de b bdims Ver Também eye ones zeros 1097 Name definedfields retorna o índice dos campos definidos de uma lista kdefinedfieldsl Parâmetros l uma lista tlist ou mlist k um vetor de índices Descrição Se l é do tipo list tlist mlist kdefinedfieldsl retorna em k os índices dos campos definidos da lista Esta função é útil porque a indexação de campos indefinidos acarreta erros Exemplos llist1l35 kdefinedfieldsl ttlistxt54 definedfieldst mmlistmabmbsdfgfgd definedfieldsm Ver Também list tlist mlist insertion extraction 1098 Name getfield extração de campos de listas xgetfieldil Parâmetros x matriz de qualquer tipo possível l lista tlist ou mlist i índice de campo ver extraction para mais detalhes Descrição Esta função é equivalente à sintaxe xli para extração de campos com a única diferença de que também se aplica a objetos mlist Exemplos llist1qwerws abgetfield3 2l ahypermat222rand123 hipermatrizes são codificadas usandose mlists a1 a entrada a111 getfield1a o primeiro campo do mlist Ver Também extraction 1099 Name hypermat inicializa matrizes ndimensionais Mhypermatdims v Parâmetros dims vetor de dimensões da hipermatriz v vetor de entradas da hipermatriz valor padrão zerosproddims1 Descrição Incializa uma hipermatriz cujas dimensões são dadas pelo vetor dims e as entradas são dadas pelo argumento opcional v A estrutura de dados de M contém o vetor de dimensões da matriz Mdims e o vetor de entradas Mentries tais que os índices subescritos mais à esquerda variam primeiro M11Mn11M1n2Mn1n2 Exemplos Mhypermat2 3 2 2124 See Also hypermatrices zeros ones grand matrix 1100 Name hypermatrices objeto do Scilab matrizes ndimensionais Descrição O tipo hipermatriz hypermatrix permite manipular arrays multidimensionais Hipermatrizes podem ser definidas por uma extensão das matrizes 2D como segue a1 23 4a2rand22 ou usando a função hypermat diretamente As entradas podem ser números reais ou complexos polinômios razões de polinômios strings ou valores booleanos Hipermatrizes são mlists mlisthmdimsentriesszv onde sz é o vetor linha de dimensões e v é o vetor coluna de entradas as primeiras dimensões são armazenadas primeiro NOTAS O número de dimensões de hipermatrizes com tamanhos mais à direita iguais a 1 é auto maticamente reduzido Uma hipermatriz com apenas duas dimensões é automaticamente trocada por uma matriz regular tipo 1 Exemplos a111121 2 a1 23 4a2rand22 a11 sizea a1 redução de dimensionalidade typea1 a a Ver Também hypermat zeros ones grand matrix 1101 Name iscell verifica se um array é um cell célula bool iscellx Parâmetros x variável Scilab bool um booleano Descrição iscellx retorna t verdadeiro se x é um cell e f falso em caso contrário Exemplos iscell1 iscellcell c cell12 c1entriesScilab c2entriesdatenum iscellc Ver Também cell isstruct Autor VC 1102 Name iscellstr verifica se uma variável é um cell array de strings bool iscellstrx Parâmetros x variável Scilab bool um booleano Descrição iscellstrx retorna verdadeiro se x é um cell array de strings ou um cell array vazio e falso em caso contrário Exemplos iscellstr1 iscellstrcell iscellstrcell3 strcell cell31 strcell1entriesScilab strcell2entriesiscellstr strcell3entrieshelp iscellstrstrcell Ver Também cell iscell isstruct Autor VC 1103 Name isstruct checa se uma variável é um struct array estrutura bool isstructx Parâmetros x variável Scilab bool um booleano Descrição isstructx retorna t verdadeiro se x é um struct array e f em caso contrário Exemplos isstruct1 isstructcell isstructstructnameScilab version getversion infonameScilab infofunctionisstruct infomodulehelp isstructinfo Ver Também struct iscell Autor VC 1104 Name list objeto do Scilab e definição de lists listas lista1an Descrição Cria um list com elementos ais que são elementos Scilab arbitrários matrix list O tipo de objetos list é 15 list cria o list vazio 0 elementos Operações em Listas extração xyzLv onde v é um vetor de índices xyzL extrai todos os elementos inserção no índice i Lia note que não é errado usar Lia com i 1 sizeL mas algumas entradas de lista estão então indefinidas e sua extração levanta um erro anexar elemento no fim da lista L1e anexar elementos no início da lista L0e note que após esta operação e está no índice 1 os elementos iniciais foram movidos para a direita deleção Linull remove o iésimo elemento da lista L concatenação de duas listas L3 lstcatL1L2 número de elementos de uma lista você pode usar tanto nbelm sizeL ou nbelm lengthL iterações com uma lista é possível usar uma lista L com um laço loop for for eLend é um laço com lengthL iterações a variável de laço e sendo igual a Li na iésima iteração Observações O Scilab também possui outros tipos de listas o tipo tlist lista com tipo e o tipo mlist que são úteis para definir um novo tipo de dado com o operador overloading facilities hypermatrices hipermatrizes que são arrays multidimensionais no Scilab são na verdade mlist struct do Matlab também estão disponíveis Exemplos l list1a b l0 foo l1 olá l2 toto l3 rand12 l3 null lbis listgewurtz caipirina debug list 1105 lter lstcatllbis sizelter sizelbis sizel deve ser zero Ver Também null lstcat tlist insertion extraction size length 1106 Name lsslist definição de função linear de espaço de estados do Scilab lsslist lsslista1an Descrição lsslista1an é um atalho para tlistlssABCX0dt a1an Cria um tlist com lssABCX0dt como primeiras entradas e os ais como próximas entradas se tiver algum Não é feita verificação de tipo ou tamanho nos ais Ver Também tlist syslin 1107 Name lstcat concatenação de listas lclstcatl1ln Parâmetros li lista ou qualquer outro tipo de variável lc uma lista Descrição lclstcatl1ln concatena os componentes das li listas em uma única lista Se os li são outros tipos de variáveis eles simplesmente são adicionados à lista resultante Exemplos lstcatlist12333listfoos lstcat123 Ver Também list 1108 Name mlist objeto Scilab definição de listas com tipos orientadas matricialmente mlisttypa1an Parâmetros typ vector of character strings ai any Scilab object matrix liststring Descrição Objetos mlist são bastante semelhantes a objetos tlist objects A única diferença concerne às sintaxes de extração e inserção extraction e insertion se M é uma mlist para qualquer índice i que não é um campo de nome Mi não é mais o iésimo campo da lista A semântica da sintaxe de extração e inserção deve ser dada por uma função de sobrecarga over loading A função de overloading para sintaxe de extração bai1in tem a seguinte seqüência de chamamento btipodeaei1ina e a sintaxe x1xmai1in tem a seguinte seqüência de chamamento x1xmtypedeaei1ina A função de overloading associada à sintaxe de inserção ai1inb tem a seguinte seqüência de chamamento atypedebitypedeai1inba Os campos de um mlist devem então ser designados por seus nomes Eles também podem ser ma nipulados usandose as funções getfield e setfield Exemplos MmlistVnamevalueabc d1 2 3 4 Definindo exibição function VpMdispMnamestringMvalueendfunction Definindo operação de extração function rVevarargin Mvarargin rmlistVnamevalueMnamevarargin11Mvaluevarargin11 endfunction M2 a segunda entrada do vetor M Mvalue Definindo operações de inserção function MViVvarargin Mvarargin Nvarargin1 Mvaluevarargin12Nvalue Mnamevarargin12Nname mlist 1109 endfunction M11M22 function MsiVvarargin inserção de uma matriz regular em uma matriz V Mvarargin Nvarargin1 Mvaluevarargin12N Mnamevarargin12emptystrN endfunction M1144 caso de tlists MtlistVnamevalueabc d1 2 3 4 M2 M2astring1 23 4 Mname Ver Também tlist list overloading getfield setfield 1110 Name rlist definição de função racional do Scilab rlist rlista1an Descrição rlista1an é um atalho para tlistrnumdendt a1an Cria um tlist com rnumdendt como primeira entrada e os ais como próximas entradas se tiver algum Nenhuma verificação de tipo ou tamanho é feita nos ais Ver Também tlist syslin 1111 Name setfield inserção de campos de listas setfieldixl Parâmetros x matriz de qualquer tipo l lista tlist ou mlist i índice de campo ver insertion para mais detalhes Descrição Esta função é equivalente à sintaxe lix spara inserção de campos com a única diferença de que também se aplica a objetos mlist Exemplos llist1qwerws l1Modificado l0Adicionado l6mais umadicionado ahypermat222rand123 hipermatrizes são codificadas usandose mlists setfield318aa ajusta o valor de campo para 18 Ver Também insertion 1112 Name struct criando um struct estrutura ststructfield1value1field2value2 Parâmetros field1 field2 strings representam os nomes dos campos value1 value2 todos os tipos de dados double char int representam os valores dos campos Descrição Esta função retorna uma estrutura com campos de nomes fields1 field2 e valores corre spondentes value1 value2 Exemplos criando um dado struct datestructdia25mes DEZano2006 mudando o mes datemesAGO mudando o ano dateano1973 mudando o dia datedia19 adicionando um novo campo datesemana32 Ver Também cell 1113 Name tlist objeto do Scilab e definição de listas com tipos typed lists tlisttypa1an Parâmetros typ string ou vetor de strings ai qualquer objeto Scilab matrix liststring Descrição Cria um typedlist com elementos ais O argumento typ especifica o tipo da lista Tais typedlist permitem ao usuário definir novas operações trabalhando nestes objetos através de funções do Scilab A única diferença entre um typedlist e um list lista é o valor do tipo 16 ao invés de 15 typ1 espeifica o tipo de lista string usado para definir operações softcoded Se especificado typi pode fornecer o nome formal do i1 ésimo elemento Operações padrões em list operam de modo semelhante para typedlist Extração xyzlv onde v é o vetor de índices xyzl extrai todos os ele mentos Inserção lia Deleção linull remove o iésimo elemento do tlist l Exibição Além disso se typ2n1 forem especificados o usuário pode apontar elementos por seus nomes Abaixo fornecemos exemplos de onde tlists são usados Sistemas lineares são representados por typedlist específicos ex um sistema linear ABCD é representado pelo tlist SystlistlssABCDX0dtABCDx0c e esta lista específica pode ser criada pela função syslin Sys2 SysA ou SysA é a estadomatriz e Sysdt ou Sysdt é o domínio de tempo Uma matriz de razões de polinômios H é representada por um typedlist HtlistrnumdendtNumDen onde Num e Den são duas matrizes de polinômios e um sistema linear ex de tempo contínuo com matriz de transferência H possivelmente criada por syslincH H2 Hnum ou Hnum é o numerador da matriz de transferência Ver Também null percent syslin list 1114 Name fieldnames returns the tlist mlist or struct field names ffieldnamesx Parameters x a tlist or an mlist or a struct f column vector of strings Description This function returns the tlist mlist cell or struct field names Examples clear t ta1 tb2 fieldnamest fieldnames1s fieldnamestf2ss1s See Also extraction getfield tlist mlist struct 1115 Name isfield Checks if the given fieldname exists in the structure bool isfieldsfieldname Parameters s A struct array fieldname A matrix of strings bool A matrix of boolean Description This function returns true if the specified structure s includes the field field regardless of the corresponding value Examples s structfield1123field2456field4789 Single Fieldname Syntax isfield s field1 Multiple Fieldname Syntax isfield s field1 field2 field3 field4 See Also struct getfield definedfields Parte XI Shell 1117 Name clc Clear Command Window clcnblines Parameters nblines a double value Description clc clears all input and output from the Command Window After using clc you cannot use the scroll bar to see the history of functions but still can use the up arrow to recall statements from the command history clcnblines clears nblines above cursor current line and move cursor up to this line Note that clcnblines cannot be used under UnixLinux platforms when Scilab used in no window mode See Also tohome Authors VC 1118 Name lines rows and columns used for display linesnl nc ncllines Parameters nl an integer the number of lines for vertical paging control If 0 no vertical paging control is done nc an integer the number of column of output Used for formatting output ncl a 1x2 vector ncnl Description lines handles Scilab display paging lines returns the vector columns rows currently used by Scilab for displaying the results linesnl sets the number of displayed lines before user is asked for more to nl lines0 disables vertical paging linesnlnc changes also the size of the output to nc columns When Scilab is launched without nw option the lines parameters are automatically set according to the output window size these parameters are also automatically modified when the window is resized See Also disp print 1119 Name prompt GetSet current prompt currentprompt prompt currentpromptpauselevel prompt promptuserprompt Parameters currentprompt String current prompt returned as a character string pauselevel integer current pause level userprompt String prompt to display for next user input Then current prompt will be used again Description currentprompt prompt gets the current prompt promptuserprompt sets the prompt See Also pause input Authors AC 1120 Name tohome Move the cursor to the upper left corner of the Command Window tohome Description tohome moves the cursor to the upperleft corner of the Command Window and clears the screen You can use the scroll bar to see the history of previous functions Note that tohome cannot be used under Windows platforms when Scilab used in no window mode See Also clc Authors VC Parte XII Console 1122 Name console Keyboard Shortcuts in the Console Window Description UP or CtrlP recall previous line DOWN or CtrlN recall next line F1 call help F2 clear console F12 open console box only on Windows Ctrlspace or TAB completion scilab displays a list of all names that start with somes characters Ctrl A or HOME move to beginning of current line Ctrl B or LEFT moves the cursor one character to the left Ctrl C interrupts Scilab if nothing selected in the console else text selected is sent to clipboard Ctrl D or DELETE deletes the current character Ctrl E or END moves the cursor to the end of command line Ctrl F or RIGHT moves the cursor one character to the right Ctrl H or BACKSPACE deletes the previous character Ctrl K kills command line from cursor to the end Ctrl S select all Ctrl U delete the whole command line Ctrl V do a paste from clipboard Ctrl W delete the last word of the command line Ctrl X Interrupt Scilab Ctrl LEFT move left one word Ctrl RIGHT move right one word Shift HOME select from cursor to beginning of statement Shift END select from cursor to end of statement Doubleclick select current word Parte XIII Complementação 1124 Name completion returns words that start with the text you pass as parameter r completionbeginningofaword r completionbeginningofaworddictionary functions commands variables macros graphicproperties files completionbeginningofaword functions commands variables macros graphicproperties completionbeginningofaword functions commands variables macros completionbeginningofaword functions commands variables completionbeginningofaword functions commands completionbeginningofaword Parameters r a string matrix beginningofaword a string dictionary a string functions commands variables macros graphicproperties files functions commands variables macros graphicproperties files a string matrix Description returns words that start with the text you pass as parameter functions a string matrix of functions name C gateways see what commands a string matrix of command words reserved see what variables a string matrix of variables names see who macros a string matrix of macros names see who graphicproperties a string matrix files a string matrix Examples r completionw r completionwfunctions r completionwcommands r completionwvariables r completionwmacros r completionwgraphicproperties r completionwfiles functionscommandsvariablesmacrosgraphicpropertiesfiles completionw functionscommandsvariablesmacrosgraphicproperties completionw functionscommandsvariablesmacros completionw functionscommandsvariables completionw functionscommands completionw completion 1125 See Also getscilabkeywords who what libraryinfo librarieslist Parte XIV Gerenciador de histórico 1127 Name addhistory add lines to current history addhistorystring addhistorystringmatrix Parameters string a string stringmatrix a string matrix Description add lines to current history Examples addhistoryhello addhistoryhelloScilab Authors AC 1128 Name displayhistory displays current scilab history displayhistory Description displays current scilab history See Also gethistory Authors AC 1129 Name gethistory returns current scilab history in a string matrix matstrgethistory linegethistoryN Parameters matstr a string matrix N Nth line in scilabs history line a string Description returns current scilab history in a string matrix See Also savehistory loadhistory resethistory Authors AC 1130 Name gethistoryfile get filename used for scilabs history filename gethistoryfile Parameters filename file name used for history Description get filename for scilabs history Examples gethistoryfile Authors AC 1131 Name historymanager enable or disable history manager state1historymanagerstate2 state1historymanager Parameters state1 returns history manager state on or off state2 on or off set history managers state Description enable or disable history manager Examples displayhistory backupstatehistorymanager historymanageroff displayhistory historymanageron loadhistory displayhistory historymanagerbackupstate Authors AC 1132 Name historysize get number of lines in history nbhistorysize Parameters nb number of lines in history Description get number of lines in history Examples historysize Authors AC 1133 Name loadhistory load a history file loadhistory loadhistoryf Parameters f file pathname Description load a history file by default history filename is SCIHOMEhistoryscilab Examples loadhistorySCIsessionscilab See Also savehistory resethistory gethistory Authors AC 1134 Name removelinehistory remove the Nth line in history removelinehistoryN Parameters N a line number Description remove the Nth line in history Examples displayhistory removelinehistoryhistorysize2 displayhistory Authors AC 1135 Name resethistory Deletes all entries in the scilab history resethistory Description Deletes all entries in the current scilab history See Also savehistory loadhistory Authors AC 1136 Name saveafterncommands Save the history file after n statements are added to the file saveafterncommandsn v saveafterncommands Parameters n a integer n statements v current value Description Save the history file after n statements are added to the file For example when you select the option and set n to 5 after every 5 statements are added the history file is automatically saved Use this option if you dont want to risk losing entries to the saved history because of an abnormal termination such as a power failure saveafterncommands returns current value 0 is default value Examples saveafterncommands3 Authors AC 1137 Name saveconsecutivecommands Save consecutive duplicate commands saveconsecutivecommandsbooleanin booleanout saveconsecutivecommands Parameters booleanin a boolean t or f booleanout current value Description Save consecutive duplicate commands saveconsecutivecommandst if you want consecutive executions of the same statement to be saved to the history file Examples saveconsecutivecommands saveconsecutivecommandst 1 1 2 saveconsecutivecommandsf 1 1 2 Authors AC 1138 Name savehistory save the current history in a file savehistory savehistoryf Parameters f file pathname Description save the current history in a file by default history filename is SCIHOMEhistoryscilab Examples savehistorySCIsessionscilab See Also loadhistory resethistory gethistory Authors AC 1139 Name sethistoryfile set filename for scilab history sethistoryfilefilename sethistoryfile Parameters filename filename for history Description set filename for scilab history sethistoryfile without parameters will use the default filename SCIHOMEhistoryscilab Examples gethistoryfile sethistoryfilegethistoryfile Authors AC Parte XV IGU 1141 Índice 1 Tree 1142 uiConcatTree 1143 uiCreateNode 1144 uiCreateTree 1145 uiDeleteNode 1146 uiDisplayTree 1148 uiDumpTree 1149 uiEqualsTree 1150 uiFindNode 1151 uiGetChildrenNode 1153 uiGetNodePosition 1154 uiGetParentNode 1155 uiInsertNode 1156 Capítulo 1 Tree Tree 1143 Name uiConcatTree Concatenation of Trees concatenatedTree uiConcatTreetree1 tree2 Input parameters tree1 tree2 are of type Tree Output parameters concatenatedTree a Tree which is the concatenation of tree1 and tree2 Description Concatenation will return a tree which is the concatenation of the first tree with the second one The concatenation will took place at the parent level of the first tree Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf21 uiCreateNodeleaf 21 iconLeaf21 callbackLeaf21 leaf22 uiCreateNodeleaf 22 iconLeaf22 callbackLeaf22 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 root uiCreateNodeRoot iconRoot callbackRoot myTree1 uiCreateTreenode1 leaf11 leaf12 myTree2 uiCreateTreenode2 leaf21 leaf22 concatTree uiConcatTreemyTree1 myTree2 uiDisplayTreeconcatTree See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiEquals Tree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1144 Name uiCreateNode Creation of node for Scilab Tree myNode uiCreateNodelabel icon callback Input parameters label a string matrix which gives the label of the nodes icon optional a string matrix which gives the icon image of the nodes callback optional a string matrix which gives the callback instruction of the nodes Output parameters myNode a node of type Tree Description Creates a nodea node or a leaf of type Tree Examples leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot See Also uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiConcatTree uiEquals Tree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1145 Name uiCreateTree Creation of a Tree myTree uiCreateTreemyParentTree mySubTree1 mySubTree2mySubTreeN Input parameters myParentTree a Tree mySubTrees one or many trees Output parameters myTree a Tree Description Creates a Tree in which myParentTree will have childrenmySubTree1 mySubTree2mySubTreeN Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 uiDisplayTreetreeRoot See Also uiCreateNode uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiConcatTree uiE qualsTree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1146 Name uiDeleteNode Deletion in a Tree delTree uiDeleteNodetree node delTree uiDeleteNodetree position Input parameters tree Tree were we do the deletion node node we want to delete position a string which is the position of the node we want to delete Output parameters delTree a Tree without the deleted node Description Deletion of a node subTree from a tree If we have 3 nodes called Node1 Node2 and Node3 each one at position 11 12 and 13 Deletion of node at position 12 Node2 will pull up the Node 3 to position 12 Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Deletion of node2 treeDel uiDeleteNodetreeRoot node2 uiDisplayTreetreeDel Deletion of node at position 32 treeDel uiDeleteNodetreeRoot 32 uiDisplayTreetreeDel Tree 1147 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiConcatTree uiEquals Tree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1148 Name uiDisplayTree Printing a Tree in GUI mode uiDisplayTreetree Input parameters tree a Tree Description Display a tree into the a graphic window Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 leaf12 uiCreateNodeleaf 12 leaf31 uiCreateNodeleaf 31 leaf32 uiCreateNodeleaf 32 node1 uiCreateNodeNode 1 node2 uiCreateNodeNode 2 node3 uiCreateNodeNode 3 root uiCreateNodeRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTree root treeNode1 node2 treeNode3 uiDisplayTreetreeRoot See Also uiCreateNode uiCreateTree uiDumpTree uiInsertNode uiDeleteNode uiConcatTree uiEquals Tree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1149 Name uiDumpTree Printing a Tree in the console text mode uiDumpTreetreeb Input parameters tree a Tree boptional display features of each node of the tree By default b is F Description Display a tree into the consoletext mode Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11leaf12 treeNode3 uiCreateTreenode3 leaf31leaf32 treeRoot uiCreateTreeroot node1node2node3 uiDumpTreetreeRoot See Also uiCreateNode uiCreateTree uiDisplayTree uiInsertNode uiDeleteNode uiConcatTree uiE qualsTree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1150 Name uiEqualsTree Comparing two trees isEqual uiEqualsTreetree1 tree2 Input parameters tree1 tree2 are of type Tree Output parameters isEqual a Boolean which indicate if those trees are equal or not Description Compare two trees structures Examples Creation of trees root uiCreateNodeRoot pathrootImagejpg rootCallback node1 uiCreateNodeNode 1 default node1Callback node2 uiCreateNodeNode 2 default node2Callback myTree1 uiCreateTreeroot node1 node2 myTree2 uiCreateTreeroot node1 node2 Compare myTree1 with myTree2 isEqual uiEqualsTreemyTree1 myTree2 will return isEqual T See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1151 Name uiFindNode Find node in Tree nodeList uiFindNodetree node nodeList uiFindNodetree position nodeList uiFindNodetree property value Input parameters tree Tree in which we find the node node the node we find position a string which is the position of the node we find in the tree property a string which finds nodes by properties label icon or callback value a string which is the value of the property Output parameters nodeList a list of matching nodes Description Finds nodes in a tree Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Creation of a node myNode uiCreateNodeNode 2 iconNode2 callbackNode2 Tree 1152 Find if treeRoot contains myNode result uiFindNodetreeRoot myNode will return result listnode1 Find node at position 11 result uiFindNodetreeRoot 31 will return result listleaf31 Find node where text equals Node 2 result uiFindNodetreeRoot label Node 2 will return result listnode2 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiEqualsTree uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1153 Name uiGetChildrenNode Get Children of a node children uiGetChildrenNodetree node children uiGetChildrenNodetree position Input parameters tree Tree in which we look for children nodes node the node we look for children position a string which is the position of the node we look for children Output parameters children a list of children nodes Description Finds the children of a specific node Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Search children nodes of node node1 children uiGetChildrenNodetreeRoot node1 will return children listleaf11 leaf12 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiEqualsTree uiFindNode uiGetParentNode uiGetNodePosition Tree 1154 Name uiGetNodePosition Get the positions of a node position uiGetNodePositiontree node Input parameters tree Tree in which we look for positions of a node node the node we look for positions Output parameters position a matrix of string which contains node positions Description Get the position of a given node Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Get the position of node node1 position uiGetNodePositiontreeRoot node1 will return position 1 Get the position of leaf leaf31 position uiGetNodePositiontreeRoot leaf31 will return position 31 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiEqualsTree uiFindNode uiGetParentNode uiGetChildrenNode Tree 1155 Name uiGetParentNode Get Parent of a node parent uiGetParentNodetree node parent uiGetParentNodetree position Input parameters tree Tree in which we look for parent of a node node the node we look for parent position a string which is the position of the node we look for parent Output parameters parent the parent node Description Finds the parent of a specific node Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Search parent node of node1 parentNode uiGetParentNodetreeRoot node1 will return parentNode root Search parent node of leaf31 parentNode uiGetParentNodetreeRoot leaf31 will return parentNode node3 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiEqualsTree uiFindNode uiGetChildrenNode uiGetNodePosition Tree 1156 Name uiInsertNode Insertion in a Tree insertTree uiInsertNodetree position node insertTree uiInsertNodetree parentNode node Input parameters tree Tree were we do the insertion position a string which is the position where we want to insert the node parentNode which is the parent node into we want to insert the node node node we want to insert Output parameters insertTree a Tree with the node inserted Description Insertion of a node subTree into a tree If we have 2 nodes called Node1 and Node2 each one at position 11 and 12 Insertion of a new node Node3 at position 12 will move the Node2 to position 13 Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Creation of a new nodes to insert leaf13 uiCreateNodeleaf 13 iconLeaf13 callbackLeaf13 testNode uiCreateNodetest icontest callbacktest Insertion of leaf13 in node2 treeInsert uiInsertNodetreeRoot node2 leaf13 uiDisplayTreetreeInsert Tree 1157 Insertion of testNode at position 11 treeInsert uiInsertNodetreeRoot 11 testNode uiDisplayTreetreeInsert See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiDeleteNode uiConcatTree uiE qualsTree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition 1158 Name about show about scilab dialog box about Description show about scilab dialog box Examples about Authors Allan CORNET 1159 Name addmenu interactive button or menu definition addmenubutton submenus action addmenugwinbutton submenus action Parameters button a character string The button name An can be placed before the character in the name to be used for keyboard shortcut this character will be underlined on the GUI Under MacOSX a sub menu with the same name is automatically added no button can be added to the menu bar submenus a vector of character string The submenus items names action a list with 2 elements actionlistflagprocname flag an integer default value is 0 flag0 the action is defined by a scilab instruction flag1 the action is defined by a C or Fortran procedure flag2 the action is defined by a scilab function procname a character string which gives the name of scilab variable containing the instruction or the name of procedure to call gwin integer The number of graphic window where the button is required to be installed Description The function allows the user to add new buttons or menus in the main window or graphics windows command panels If action argument is not given the action associated with a button must be defined by a scilab instruction given by the character string variable which name is button for a main window command buttongwin for a graphic window command If action argument is set to 0 procname should be the name of a Scilab string vector Actions associated with the kth submenu must be defined by scilab instructions stored in the kth element of the character string variable If action argument is set to 1 procname designes a C or Fortran procedure this procedure may be interfaced in Fortran subroutine defaultfbutnf or dynamically linked with scilab using the link function The C calling sequence is char buttonname int gwinint k addmenu 1160 If action argument is set to 2 procname designes a Scilab function This function calling se quence should be procnamekfor a main window command procnamekgwinfor a graphic window command or a main window command Examples if getscilabmode STD then addmenufoo foo disphello addmenuHelloFranckPeter Hello disphello Franckdisphello Peter addmenuByelist0FrenchBye FrenchBye dispAu revoir else mprintfThis example requires to use scilab with GUI mode end addmenu0HelloFranckPeter Hello0 disphello Franckdisphello Peter C defined Callback creating Callback code code include machineh include sciprinth void foochar name int win int entry if win1 sciprintmenu si in Scilab window selected name entry1 else sciprintmenu si in window i selected name entry1 win creating fooc file currentdir pwd chdirTMPDIR mputlcode TMPDIRfooc creating Makefile ilibforlinkfoofoocc execloadersce chdircurrentdir add menu addmenu0fooabclist1foo See Also setmenu unsetmenu delmenu 1161 Name clipboard Copy and paste strings to and from the system clipboard clipboardcopydata strclipboardpaste clipboarddopaste clipboarddocopy clipboarddoempty clipboardwinnumEMF clipboardwinnumDIB Parameters data Scilab variable or data to set as the clipboard contents str The clipboard contents returned as a Scilab character string winnum Number of the graphic window to set as the clipboard contents Description clipboardcopydata sets the clipboard contents to data If data is not a character array the clipboard uses sci2exp to convert it to a string str clipboardpaste returns the current contents of the clipboard as a string or as an empty string if the current clipboard contents cannot be converted to a string clipboarddopaste clipboarddocopy clipboarddoempty performs a paste copy or empty clipboard clipboardwinnumEMF copy a graphic window identified by his windows number in the clipboard to EMF format clipboardwinnumDIB copy a graphic window identified by his windows number in the clipboard to DIB format Note that clipboard function works only when Scilab used in window mode Authors AC 1162 Name close close a figure Parameters h integer Handle of the window to close Description This routine close a tksci figure toplevel window If a handle is given the figure corresponding to this handle is closed Otherwise the current active figure is closed Examples hfigure creates figure number 1 uicontrol h styletext stringscilab is great position50 70 100 100 fontsize15 put a clever text in figure 1 figure create figure 2 uicontrol styletext stringReally great position50 70 100 100 fontsize15 put a text in figure 2 close close the current graphic window ie fig 2 closeh close figure 1 See Also figure gcf Authors Bertrand Guiheneuf 1163 Name delmenu interactive button or menu deletion delmenubutton delmenugwinbutton Parameters button a character string The button name On Windows operating systems not Xwindow an should be placed before the character in the name used for keyboard shortcut this character is underlined on the GUI gwin integer The number of graphic window where the button is required to be installed Description The function allows the user to delete buttons or menus create by addmenu in the main or graphics windows command panels Predefined buttons on Scilab graphic windows can also be deleted If possible it is better to delete first the latest created button for a given window to avoid gaps in command panels Examples addmenufoo delmenufoo See Also setmenu unsetmenu addmenu 1164 Name exportUI Call the file export graphical interface exportUIfigId exportUIfig Parameters figId integer Id of the figure to export fig Figure handle handle of the figure to export Description exportUI routine call the graphical interface dedicated in exporting a graphic window into an image file See Also xs2jpg xs2eps xs2png xs2svg xs2pdf Authors JeanBaptiste Silvy 1165 Name figure create a figure f figurenum f figurePropertyName1 Propertyvalue1 PropertyNameN PropertyvalueN Description This routine creates a figure If an ID is given the figure corresponding to this ID is created Otherwise the window is created with the first free ID that is the lowest integer not already used by a window Parameters num ID of the window to create If not specified the first free ID is used PropertyName1 N character string name of a property to set One of the property names listed below PropertyValue1 N scilab object value to give to the corresponding property f handle of the newly created window Properties BackgroundColor 13 real vector or string Background color of the figure A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB Figurename character string allows to set the title of the figure ForegroundColor 13 real vector or string Foreground color of the figure A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB Position allows to control the geometrical aspect of the figure It is a 14 real vector x y width height where the letters stand for the x location of the top left corner the y location of the top left corner the width and the height of the virtual graphics window the part of the figure which contains uicontrols and graphics See the axessize property description in figure properties help page One can also set this property by giving a string where the fields are separated by a ie xy widthheight Tag string this property is generally used to identify the figure It allows to give it a name Mainly used in conjontion with findobj Userdata this can be used to associate some Scilab objects to a fugure figure 1166 Examples Create figure having figureid3 hfigure3 Add a text uicontrol in figure 3 uicontrolh style text string This is a figure position 50 70 100 100 fontsize15 Create figure having figureid1 figure Add a text uicontrol in figure 1 uicontrolstyle text string Another figure position 50 70 100 100 fontsize 15 Close current figure ie figure 1 close close figure 3 closeh See Also close gcf Authors Bertrand Guiheneuf VC 1167 Name findobj find an object with specified property h findobjpropertyName propertyValue Parameters propertyName string character Name of the property to test case unsensitive propertyValue string character specify the value the tested propoerty should be equal to case sensitive h handle of the found object Description This routine is currently used to find objects knowing their tag property It returns handle of the first found object which property propertyName is equal to propertyValue If such an object does not exist the function returns an empty matrix Examples Create a figure hfigure Put a text in the figure uicontrolh styletext stringThis is a figure position50 70 100 100 fontsize15 tagAlabel Find the object which tag value is Alabel labfindobjtagAlabel dispThe text of the label is labstring Close the figure close See Also uicontrol uimenu set get Authors Bertrand Guiheneuf VC 1168 Name gcbo Handle of the object whose callback is executing gcbo Description gcbo is a Scilab variable automatically created each time a callback in executed This variable is initialised using getcallbackobject gcbo does not exists in Scilab environment if no callback is currently executed You can use gcbo in callback functions particularly if you write a single callback function for multiple objects it helps you to know which object received a user action See Also getcallbackobject Authors Vincent COUVERT 1169 Name getcallbackobject Return the handle of the object whose callback is executing h getcallbackobject Parameters h Handle the handle of the object whose callback is executing Description getcallbackobject is used to automatically create Scilab variable called gcbo each time a call back in executed getcallbackobject returns if no callback is currently executed See Also gcbo Authors Vincent COUVERT 1170 Name getinstalledlookandfeels returns a string matrix with all Look and Feels lnfgetinstalledlookandfeels Parameters lnf a string matrix Description returns a string matrix with all Look and Feels that you can use Examples getinstalledlookandfeels See Also setlookandfeel getlookandfeel Authors Allan CORNET 1171 Name getlookandfeel gets the current default look and feel lnfgetlookandfeel Parameters lnf a string with current look and feel bok a boolean Description Gets the current default look and feel Examples currentlnf getlookandfeel Look and feel CDEMotif setlookandfeelcomsunjavaswingplafmotifMotifLookAndFeel sleep3000 Look and feel métal setlookandfeeljavaxswingplafmetalMetalLookAndFeel sleep3000 setlookandfeelcurrentlnf See Also getinstalledlookandfeels setlookandfeel Authors Allan CORNET 1172 Name getvalue xwindow dialog for data acquisition okx1x14getvaluedesclabelstypini Parameters desc column vector of strings dialog general comment labels n column vector of strings labelsi is the label of the ith required value typ listtyp1dim1typndimn typi defines the type of the ith value may have the following values mat for constant matrix col for constant column vector row for constant row vector vec for constant vector str for string lis for list dimi defines the size of the ith value it must be a integer or a 2vector of integer 1 stands for undefined dimension ini n column vector of strings inii gives the suggested response for the ith required value ok boolean t if ok button pressed f if cancel button pressed xi contains the ith value if okt If left hand side has one more xi than required values the last xi contains the vector of answered strings Description This function encapsulate xmdialog function with error checking evaluation of numerical re sponse Remarks All valid expressions can be used as answers for matrices and vectors getvalues automatically adds around the given answer before numeric evaluation getvalue 1173 Examples labelsmagnitudefrequencyphase okmagfreqphgetvaluedefine sine signallabels listvec1vec1vec1085102pi3 See Also xmdialog xmatrix xdialog Authors S Steer 1174 Name messagebox Open a message box btn messageboxmsg btn messageboxmsg msgboxtitle btn messageboxmsg msgboxtitle msgboxicon btn messageboxmsg msgboxtitle msgboxicon btn messageboxmsg msgboxtitle msgboxicon buttons btn messageboxmsg msgboxtitle msgboxicon buttons ismodal Parameters msg Matrix of strings the message box displays each entry of this matrix one entry per line msgboxtitle String the title of the message box default value is Scilab Message msgboxicon String the name of the icon to be displayed in the message box its possible values are error hourglass info passwd question warning scilab default icon buttons 1xn vector of strings the names of the buttons to be displayed in the message box By default only one button is displayed with label OK modal String modal to create a modal dialog any other string to create a nonmodal dialog Please note that modal can replace any of the other input arguments except msg See examples btn Scalar number of the button that the user pressed 1 is the leftmost button for a modal dialog 0 else Description Creates a dialog window to display a message waiting or not for a user action Examples Simple example messageboxSingle line message messagebox 1175 Multi line message with title messageboxMultiline message User defined title Icon specified by th euser messageboxAn error message Error error Buttons labels modal replaces title messageboxHave you seen this beautiful message modal info Yes No modal given as fifth input argument messageboxAn error message Error error Continue Stop modal Authors Vincent COUVERT 1176 Name printfigure Opens a printing dialog and prints a figure printfigurefigid status printfigurefigid Parameters figid Real the id of the figure to be printed status Boolean T if the printing succeeds F otherwise Description This function opens a dialog to select a printer printing options and then prints the figure Examples plot2d printfiguregetgcf figureid See Also toprint printsetupbox Authors VC 1177 Name printsetupbox Display print dialog box printsetupbox statusprintsetupbox Parameters status Boolean T if the user clicked on the OK button F otherwise Description Displays the builtin printing dialogbox and configure the printer See Also toprint printfigure Authors AC 1178 Name progressionbar Draw a progression bar winIdprogressionbarmes progressionbarwinIdmes Parameters mes string message to display winId integer greater than 0 window identificator Description progressionbarmes create a new progression bar return window identificator progressionbarwinIdmes update the progression bar identificated as winId Examples winIdprogressionbarDo something realtimeinit03 for j0011 realtime3j progressionbarwinId end winclosewinId Authors Jaime Urzua 1179 Name rootproperties description of the root object properties Description The root object is a virtual object used to get the computer screen properties Use get function with 0 as first argument to access its properties Root properties screensizepx The screen size in pixels screensizept The screen size in points screensizemm The screen size in millimeters screensizecm The screen size in centimeters screensizein The screen size in inches screensizenorm The normalized screen size screendepth The number of bits used to encode colors Examples get0 screensizepx get0 screendepth See Also get Author Vincent COUVERT 1180 Name setlookandfeel sets the current default look and feel boksetlookandfeel boksetlookandfeellnf Parameters lnf a string with a look and feel bok a boolean Description Sets the current default Look and Feel setlookandfeel without parameter set system default look and feel Examples currentlnf getlookandfeel Look and feel Windows Classic setlookandfeelcomsunjavaswingplafwindowsWindowsClassicLookAndFeel Look and feel Windows setlookandfeelcomsunjavaswingplafwindowsWindowsLookAndFeel sleep3000 Look and feel CDEMotif setlookandfeelcomsunjavaswingplafmotifMotifLookAndFeel sleep3000 Look and feel GTK setlookandfeelcomsunjavaswingplafgtkGTKLookAndFeel sleep3000 Look and feel métal setlookandfeeljavaxswingplafmetalMetalLookAndFeel sleep3000 Look and feel Macintosh setlookandfeelitunitningswingplafmacosMacOSLookAndFeel System default look and feel setlookandfeel sleep3000 setlookandfeel 1181 restore previous look and feel setlookandfeelcurrentlnf See Also getinstalledlookandfeels getlookandfeel Authors Allan CORNET 1182 Name setmenu interactive button or menu activation setmenubutton nsub setmenugwinbutton nsub Parameters button a character string The button name gwin integer The number of graphic window where the button is installed nsub integer The number of submenu to deactivate if any If button has no submenu nsub is ignored Description The function allows the user to make active buttons or menus created by addmenu in the main or graphics windows command panels Examples addmenufoo New button made in main scilab window unsetmenufoo button foo cannot be activated grey string setmenufoo button foo can be activated black string See Also delmenu unsetmenu addmenu 1183 Name toolbar show or hide a toolbar state1toolbarwinnumstate2 state1toolbarwinnum Parameters state1 returns toolbars state on or off winum windows number 1 Scilab console window state2 on or off set toolbars state Description show or hide a toolbar Examples toolbar1off statetoolbar1on plot3d hgcf toolbarhfigureidoff Authors Allan CORNET Vincent COUVERT 1184 Name toprint Send text or figure to the printer toprintfilename toprintlinestoprintpageheader toprintfigid toprintfigidoutput status toprintfilename status toprintlinestoprintpageheader status toprintfigid status toprintfigidoutput Parameters filename String path of the text file to be printed linestoprint String matrix text to be printed each entry is a line in printed pages pageheader String header of printed pages figid Real the id of the figure to be printed output String printing output type must be pos for PostScript or gdi for Bitmap format gdi by default status Boolean T if the printing succeeds F otherwise Description Prints a text file Scilab character strings or figure Examples toprintSCIetcscilabstart toprintTesttoprint primitiveScilab page header scf4 plot toprint4 toprint4pos See Also printfigure printsetupbox Authors AC VC 1186 Name uicontrol create a Graphic User Interface object h uicontrolPropertyNamePropertyValue h uicontrolparentPropertyNamePropertyValue h uicontroluich Description This routine creates an object in a figure If the handle of the figure is given as the first parameter the uicontrol is created in this figure If no handle is given the uicontrol is created in the current figure which may be obtained with a call to gcf If there is no current figure then one is created before the creation of the uicontrol Then when the control is created the properties given as parameters are set with the corresponding values It is equivalent to create the uicontrol and then set its properties with the set command Nevertheless it generally more efficient to set the properties in the call to uicontrol This is particularly true concerning the Style property Indeed the default value for this property is Push button So if you do not set it at creation time a button will be created and will be transformed to another uicontrol when you call the seth Style instruction Scilab and all the graphic objects communicate through the property mechanism Thus to create adapted uicontrol one has to know the use of the property fields h uicontrolPropertyName PropertyValue creates an uicontrol and assigns the specified properties and values to it It assigns the default values to any properties you do not specify The default uicontrol style is a Pushbutton The default parent is the current figure See the Properties section for information about these and other properties h uicontrolparent PropertyName PropertyValue creates a uicontrol in the object specified by the handle parent If you also specify a different value for the Parent property the value of the Parent property takes precedence parent is the handle of a figure h uicontroluich gives focus to the uicontrol specified by uich Properties BackgroundColor 13 real vector or string Background color of the uicontrol A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB Callback String Instruction evaluated by the Scilab interpreter when an uicontrol is activated for example when you click on a button Enable on off Enable or disable the uicontrol If this property is set to on default the uicontrol is opera tional but if this property is set to off the uicontrol will not respond to the mouse actions and will be grayed out uicontrol 1187 FontAngle normal italic oblique For a control containing some text this property sets the slant of the font FontSize Scalar For a control containing some text this property sets the size of the font in FontUnits FontUnits points pixels normalized For a control containing some text this property sets the units with which the FontSize is specified FontWeight light normal demi bold For a control containing some text this property sets the weight of the used font FontName String Used to choose the name of the font selected to display the text of the control ForegroundColor 13 real vector or string Foreground color of the uicontrol A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB HorizontAlalignment left center right Set text horizontal alignment in the uicontrol This property has only effect with Text Edit and Check Boxes ListboxTop Scalar For a ListBox this property tells which item of the list appears on the first line of the visible area of the list Max Scalar Specifies the largest value the Value property can be set to It has however different meaning on each uicontrol CheckBoxes Max is the value the Value property take when control is checked Sliders Maximum value of the slider ListBoxes if MaxMin1 the list allows multiple selection Otherwise not Min Scalar Specifies the lowest value the Value property can be set to It has however different meaning on each uicontrol uicontrol 1188 CheckBoxes Min is the value the Value property take when control is unchecked Sliders Minimum value of the slider ListBoxes if MaxMin1 the list allows multiple selection Otherwise not Parent Handle Handle of the uicontrol parent Changing this property allows to move a control from a figure to another Path This property is no more supported Position 14 real vector or string This property is used to set or get the geometrical configuration of a control It is a vector x y w h where the letters stand for the x location of the left bottom corner the y location of the left bottom corner the width and the height of the uicontrol or a character string where each value is separated by a ie xywh The units are determined by the Units property The width and height values determine the orientation of sliders If width is greater than height then the slider is oriented horizontally otherwise the slider is oriented vertically Relief flat groove raised ridge solid sunken Appearance of the border of the uicontrol PushButtons the default value for Relief property is raised Edits the default value for Relief property is sunken Other styles the default value for Relief property is flat SliderStep 12 real vector small big the small step represents the movement achieved when clicking on the slider trough or tapping on the keyboard arrows when the slider has focus the big step is the amount moved when using Ctrlkeyboardarrows If the big step is omitted it is defaulted to 110 of the scale String String This property represents the text appearing in a uicontrol Except for Frame and Slider styles For ListBoxes and PopupMenus the value can be a vector of string or a string where the items are separated by a For Text uicontrols this string can contain HTML code to format the text Style pushbutton radiobutton checkbox edit text slider frame listbox popupmenu Style of the uicontrol Here is a short description of each one Pushbutton a rectangular button generally used to run a callback Radiobutton a button with to states RadioButtons are intended to be mutually exclusive Your code must implement mutually exclusive behavior Checkbox a button with to states Used for multiple independent choices uicontrol 1189 Edit an editable string zone Text a text control generally static Slider a scale control that is a scrollbar use to set values between in range with the mouse Frame a control representing a zone used to group related controls Listbox a control representing a list of items that can be scrolled The items can be selected with the mouse Popupmenu a button which make a menu appear when clicked Tag String This property is generally used to identify the control It allows to give it a name Mainly used in conjunction with findobj Units points pixels normalized Set the units used to specify the Position property Userdata Scilab data This can be used to associate some Scilab objects stringstring matrix matrix mxn to an uicon trol Value Scalar or vector Value of the uicontrol The exact meaning depends on the style of the uicontrol CheckBoxes Radio buttons value is set to Max see above when on and Min when off ListBoxes PopupMenus value is a vector of indexes corresponding to the indexes of the se lected entries in the list 1 is the first item of the list Sliders value indicated by the slider bar Verticalalignment top middle bottom Set text vertical alignment in the uicontrol This property has only effect with Text and Check Boxes styles Visible on off Set the visibility of the uicontrol If this property is set to on default the uicontrol is visible but if this property is set to off the uicontrol will not appear in its parent figure Examples ffigure create a figure huicontrolfstylelistbox position 10 10 150 160 uicontrol 1190 create a listbox seth string item 1item 2item3 fill the list seth value 1 3 select item 1 and 3 in the list closef close the figure See Also figure set get uimenu Authors Bertrand Guiheneuf Vincent Couvert 1191 Name uigetcolor Opens a dialog for selecting a color uigetcolor RGB uigetcolortitle RGB uigetcolortitle defaultRGB RGB uigetcolortitle defaultRed defaultGreen defaultBlue R G B uigetcolortitle R G B uigetcolortitle defaultRGB R G B uigetcolortitle defaultRed defaultGreen defaultBlue Parameters title String Optional argument the title to display in the dialog Default value is Color Chooser defaultRGB 1x3 vector the default values for Red Green and Blue values given as a vector red green blue defaultRed Scalar the default value for red defaultGreen Scalar the default value for green defaultBlue Scalar the default value for blue RGB 1x3 vector the values for Red Green and Blue values given as a vector red green blue or if the user cancels R Scalar the value for red or if the user cancels G Scalar the value for green or if the user cancels B Scalar the value for blue or if the user cancels Description Creates a dialog window for selecting a color All default and returned values must be in the interval 0 255 Examples uigetcolor R G B uigetcolor255 128 0 RBG uigetcolor0 128 255 RBG uigetcolorMy color chooser 0 128 255 uigetcolor 1192 See Also getcolor Authors Vincent COUVERT 1193 Name uigetdir dialog for selecting a directory directory uigetdir directory uigetdirstartpath title Parameters startpath a character string which gives the initial directory used for search By default uigetdir uses current working directory title the title for the uigetdir window directory is the user selected directory if user answers Ok or the string if user cancels Description Creates a dialog window for selecting a directory Examples uigetdir uigetdirSCImodules uigetdirSCImodules Choose a directory See Also uigetfile uiputfile 1194 Name uigetfile dialog window to get a files names path and filter index FileNamePathNameFilterIndexuigetfilefilemaskdirboxTitlemultipleSelection PathFileNameuigetfilefilemaskdirboxTitlemultiple Input parameters filemask a string matrix which gives the file masks to use for file selection filemask is written with Unix convention The default value is we can also add descriptions for masks for example xX filesbinBIN files dir a character string which gives the initial directory used for file search By default uigetfile uses the previously selected directory boxTitle a character string which gives the title of the uigetfile window By default uigetfiles title is uiget file multipleSelection a boolean which allows to load only one file if it is at f false or multiple files if it is at t true By default uigetfiles multiple file selection is not enable Output parameters FileName matrix of string which give the user selected files path files names if user answers Ok or the string if user answers Cancel PathName is the user selected files path if user answers Ok or the string if user answers Cancel FilterIndex is the user selected filter index on the list box if user answers Ok or 0 string if user answers Cancel Description Creates a dialog window for files selection Comments On Windows java component used by uigetfile browse also zip archive then it is very slow with big zip files To disable this feature if MSDOS then unixREGSVR32 u WINDIRSystem32zipfldrdll end To reenable if MSDOS then unixREGSVR32 WINDIRSystem32zipfldrdll end uigetfile 1195 Examples uigetfilebinscecos uigetfilescibinSCImodulesguimacros uigetfilescbinSCImodulesguimacros uigetfilexX filesbinBIN filesSCImodulesguimacros uigetfilescebinSCImodulesguimacros Choose a file name t uigetfilescebinSCImodulesguimacros Choose a file name f See Also uiputfile uigetdir xdialog file read write exec 1196 Name uigetfont Opens a dialog for selecting a font uigetfont fontname fontsize bold italic uigetfontdefaultfontname defaultfontsize defaultbold defaultitalic fontname fontsize bold italic uigetfontdefaultfontname defaultfontsize defaultbold defaultitalic Parameters defaultfontname String the default font name to select in the dialog defaultfontsize Scalar the default font size to select in the dialog defaultbold Boolean the default bold attribute in the dialog T for bold font F otherwise defaultitalic Boolean the default italic attribute in the dialog T for bold font F otherwise fontname The selected font name if the user cancels fontsize The selected font size if the user cancels bold T if bold attribute has been selected F otherwise if the user cancels italic T if italic attribute has been selected F otherwise if the user cancels Description Creates a dialog window for selecting a font Examples uigetfont uigetfontarial uigetfontarial 24 uigetfontarial 24 T uigetfontarial 24 T F See Also getfont Authors Vincent COUVERT 1197 Name uimenu Create a menu or a submenu in a figure huimenuprop1val1 prop2 val2 huimenuparentprop1 val1 prop2 val2 Parameters parent integer Handle of menus parent prop1 2 string character name of a property to set up val1 2 scilab object value to affect to the corresponding property h integer handle of the corresponding menu Description This allows to create menus in a figure If parent is a figure then the menu item will be added to the menu bar of the figure If parent is a menu item then the new item will be added to the parent item allowing to create cascaded submenu To create a customized menu you can use the properties listed below Properties Callback String Instruction evaluated by the Scilab interpreter when the menu is activated Under MacOSX the callback will not be executed for a button menu a menu without children you must specify at least a child Enable on off Enable or disable the menu If this property is set to on default the menu is operational but if this property is set to off the menu will not respond to the mouse actions and will be grayed out Checked on off Menu check indicator Setting this property to on respectively off places respectively re moves a check mark next to the corresponding menu item This option can be used to create menus that indicate the state of a particular option Please note that a standard menu without the option Checked set has no mechanism to become a menu which will be checked by a user action and conversely This property is ignored for parent menus ForegroundColor 13 real vector or string uimenu 1198 Foreground color of the uimenu font color A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB Label String This property represents the text appearing in the menu Tag String This property is generally used to identify the menu It allows to give it a name Mainly used in conjunction with findobj Visible on off Set the visibility of the uimenu If this property is set to on default the uimenu is visible but if this property is set to off the uimenu will not appear in its parent figure Examples ffigureposition 10 10 300 200 create a figure muimenuflabel windows create an item on the menu bar m1uimenumlabel operations m2uimenumlabel quit scilab callback exit create two items in the menu windows m11uimenum1label new window callbackxselect m12uimenum1label clear window callbackclf create a submenu to the item operations closef close the figure See Also figure uicontrol set get Authors Bertrand Guiheneuf 1199 Name uiputfile Open standard dialog box for selecting and saving file FileNamePathNameFilterIndexuiputfilefilemaskdirboxTitle PathFileNameuiputfilefilemaskdirboxTitle Input parameters filemask a string matrix which gives the file masks to use for file selection filemask is written with Unix convention The default value is we can also add descriptions for masks for example xX filesbinBIN files dir a character string which gives the initial directory used for file search By default uiputfile uses the previously selected directory boxTitle a character string which gives the title of the uiputfile window By default uiputfiles title is uiput file Output parameters FileName string which give the user selected file path file name if user answers Ok or the string if user answers Cancel PathName is the user selected file path if user answers Ok or the string if user answers Cancel FilterIndex is the user selected filter index on the list box if user answers Ok or 0 string if user answers Cancel Description Creates a dialog window for file saving Examples uiputfilebinscecos uiputfilescibinSCImodulesguimacros uiputfilescbinSCImodulesguimacros uiputfilexX filesbinBIN filesSCImodulesguimacros uiputfilescebinSCImodulesguimacros Choose a file name See Also uigetfile uigetdir 1200 Name unsetmenu interactive button or menu or submenu deactivation unsetmenubuttonnsub unsetmenugwinbuttonnsub Parameters button a character string The button name gwin integer The number of graphic window where the button is installed nsub integer The number of submenu to deactivate if any If button has no submenu nsub is ignored Description The function allows the user to desactivate buttons or menus created by addmenu in the main or graphics windows command panels Examples addmenufoo unsetmenufoo unsetmenuFile2 See Also delmenu setmenu addmenu 1201 Name usecanvas GetSet the main component used for Scilab graphics canvasused usecanvasusecanvasfordisplay Parameters canvasused Boolean T if a GLCanvas is used for graphics display Mixing uicontrols and graphics not avail able F if a GLJPanel is used for graphics display Mixing uicontrols and graphics available usecanvasfordisplay Boolean T to use a GLCanvas for graphics display Mixing uicontrols and graphics not available F to use a GLJPanel for graphics display Mixing uicontrols and graphics available Description Scilab uses a GLJPanel a Swing OpenGL component to display graphics plot3d plot This component uses some high level OpenGL primitives which are not correctly supported on some plat forms depending on the operating system video cards drivers GLCanvas AWT OpenGL is an alternative component provided by the Java Framework Scilab can use it to render graphics However using this component disables some capabilities such as mixing plots and uicontrols see demo GUIUIcontrol2 That is why it is not the default behavior In some particular cases the use of the GLCanvas component is forced when Scilab starts a warning message is displayed when a graphics function is used for the first time here is a list of these cases Operating System Video Card Details 64bits Windows All When Scilab is used in a remote session Linux NVIDIA Card With free drivers ATI Card With free drivers or ATIdrivers with version 8523 Installer version 88 OpenGL version 217873 INTEL Card With Direct Rendering activat ed You can also dynamically activate this component through Scilab using usecanvas usecanvasT will use GLCanvas for plot rendering usecanvasF will use GLJPanel for plot rendering If your configuration is known as a one having problems with GLJPanel See table above a warning message will be displayed If you believe your configuration is able to use the GLJPanel and Scilab automatically forces the use of GLCanvas you can test your configuration by swithing to GLJPanel usecanvasF and usecanvas 1202 try to plot something plot3d for example If Scilab graphics work please inform us about it by sending an email to scilabsupportscilaborg and giving us your Operating SystemVideo CardVideo Card driver version this will help use to improve future versions of Scilab Technical Aspects Since version 50 Scilab is doing an advanced use of JOGL the Java Binding for the OpenGL which is using the Java2D OpenGL Pipeline For performance reasons we use the Java2D OpenGL Pipeline From a more technical aspect it uses the internal buffer of the graphic cards called pbuffer Problems may occur when the driver of the graphic card does not support properly this approach As far as we know there is no free driver under Linux handling this feature In the proprietary world the situation is as follows NVIDIA Nvidia provides the appropriate proprietary drivers Scilabs graphics work without any problem with most NVIDIA drivers ATI From the driver version 88 most ATI graphics supports the pbuffer under Linux Intel This is the big drawback of using the pbuffer There is currently no support of pbuffer by any official Intel drivers under Linux There is a workaround for Linux to tackle this issue but a solution is to use a software accelerated driver To do it in etcX11xorgconf look for the Section Device and change the option Driver to vesa Section Device Identifier Your Graphic card Driver vesa EndSection Unfortunately this solution makes Scilab pretty slow Under Windows video cards manufacturers update regularly and pbuffers are managed Please download recent drivers at For ATI cards httpatiamdcomsupportdriverhtml For Intel cards httpwwwintelcomsupportgraphics For Matrox cards httpwwwmatroxcomgraphicsensupportdrivers For NVIDIA cards httpwwwnvidiacomcontentdriversdriversasp For S3 cards httpwwws3graphicscomenresourcesdriversindexjsp For SiS cards httpwwwsiscomdownload For VIA cards httpwwwviaarenacomdefaultaspxPageID2 Some troubles can also occur when using Windows 2000 video drivers are no more updated and no more supported In the cases where pBuffer create a problem waiting for a working pbuffer is not a solution indeed The OpenGL community is moving away from pbuffers and toward the frame buffer object extension which is a more portable and higherperformance solution for offscreen rendering than pbuffers httpsjogldevjavanetissuesshowbugcgiid163 The JOGL team is working to fix this issue usecanvas 1203 For more information about this problem please refer to JoGL bug database Bug 366 httpsjogldevjavanetissuesshowbugcgiid366 Scilab bug database Bug 3525 httpbugzillascilaborgshowbugcgiid3525 Debian bug database Bug 501799 httpbugsdebianorgcgibinbugreportcgibug501799 Freedesktop bug database Bug 17603 httpsbugsfreedesktoporgshowbugcgiid17603 Examples Example using GLJPanel Mixing uicontrols and graphics is available usecanvasF plot2d uicontrolString Close the window Position 10 10 100 25 Callback deletegcf messageboxYou can see the button on the figure Usecanvas example info Example using GLCanvas Mixing uicontrols and graphics is not available uicontrols are not visible usecanvasT plot2d uicontrolString Close the window Position 10 10 100 25 Callback deletegcf messageboxYou cant see any button on the figure Usecanvas example info Authors Vincent COUVERT 1204 Name waitbar Draw a waitbar winIdwaitbarx winIdwaitbarxmes winIdwaitbarmes waitbarxwinId waitbarmeswinId waitbarxmeswinId Parameters x real fraction to display mes string message to display winId integer greater than 0 window identificator Description waitbarx create a new waitbar displaying a fraction x return window identificator waitbarxmes create a new waitbar displaying a fraction x and message mes return window identificator waitbarmes create a new waitbar displaying a fraction 0 and message mes return window iden tificator waitbarxmes create a new waitbar displaying a fraction 0 and message mes return window identificator waitbarxwinId waitbarmeswinId and waitbarxmeswinId update wait bar with window identificator winId Examples winIdwaitbarThis is an example realtimeinit03 for j0011 realtime3j waitbarjwinId end winclosewinId Authors Jaime Urzua 1205 Name xchoices interactive Xwindow choices through toggle buttons repxchoicestitleitems Parameters title vector of strings title for the popup window items a list of items itemslistitem1itemn where each item is also a list of the following type itemlistlabeldefaultchoicechoices defaultchoice is an integer which gives the default toggle on entry and choices is a row vector of strings which gives the possible choices rep an integer vector which gives for each item the number of the selected toggle If user exits dialog with cancel button rep is set to Description Select items through toggle lists and return in rep the selected items Type xchoices to see an example Examples l1 listchoice 11toggle c1toggle c2toggle c3 l2 listchoice 22toggle d1toggle d2toggle d3 l3 listchoice 33toggle e1toggle e2 rep xchoicesToggle Menulistl1l2l3 1206 Name xchoose interactive window choice modal dialog numxchooseitemstitle button Parameters items column vector of string items to choose title column vector of string comment for the dialog button string text to appear in the button Default value is Cancel num integer choosen item number or 0 if dialog resumed with Cancel button Description Returns in num the number of the chosen item WARNING this dialog was not modal before Scilab 50 please use xchoosemodeless for ascendant compatibility Examples n xchooseitem1item2item3that is a commentfor the dialog n xchooseitem1item2item3that is a commentReturn See Also xchoosemodeless xchoices xmdialog getvalue unixg 1207 Name xchoosemodeless interactive window choice not modal dialog numxchoosemodelessitemstitle button Parameters items column vector of string items to choose title column vector of string comment for the dialog button string text to appear in the button Default value is Cancel num integer choosen item number or 0 if dialog resumed with Cancel button Description Returns in num the number of the chosen item Examples n xchoosemodelessitem1item2item3that is a commentfor the dialog n xchoosemodelessitem1item2item3that is a commentReturn See Also xchoose xchoices xmdialog getvalue unixg 1208 Name xdialog Dialog for interactive multilines input resultxdialoglabelsvalueini Parameters labels column vector of strings comment for dialog valueini n column vector of strings initial value suggested result User answer n column vector of strings if returned with Ok button or if returned with Cancel button Description Opens a dialog for interactive multilines input Examples gainevstrxdialogvalue of gain 0235 xdialogMethodenter sampling period1 mevstrxdialogenter a 3x3 matrix 0 0 00 0 00 0 0 See Also xmdialog xmatrix evstr execstr 1209 Name xmatrix Xwindow editing of matrix resultxmatrixlabelmatrixinit Parameters label character string name of matrix matrixinit real matrix Description For reading or editing a matrix Examples mevstrxmatrixenter a 3x3 matrix rand33 See Also xmdialog xdialog 1210 Name xmdialog Dialog for interactive vectormatrix input resultxmdialogtitlelabelsdefaultinputsvector resultxmdialogtitlelabelsvlabelshdefaultinputmatrix Parameters title column vector of strings dialog general comment labels n column vector of strings labelsi is the label of the ith required value defaultinputvector n column vector of strings defaultinputvectori is the initial value of the ith re quired value labelsv n vector of strings labelsvi is the label of the ith line of the required matrix labelsh m vector of strings labelshj is the label of the jth column of the required matrix defaultinputmatrix n x m matrix of strings defaultinputmatrixij is the initial value of the ij ele ment of then required matrix result n x m matrix of string if returned with Ok button or if returned with Cancel button Description Opens a dialog for interactive vectormatrix input Examples txt magnitudefrequencyphase sig xmdialogenter sine signaltxt1100 mag evstrsig1 frq evstrsig2 ph evstrsig3 rep xmdialogSystem Simulationwith PI regulator P gainI gain See Also editvar xdialog xchoose messagebox getvalue evstr execstr editvar 1211 Name xmessagemodeless X window modeless message xmessagemodelessstrings Parameters strings vector of characters strings to be displayed Description for displaying a message information userguide The function returns immediately The message window is killed when Ok button is clicked Examples xmessagemodelessThis is a modeless message Scilab may continue computation Click on Ok to close the message xmessagemodelessNow two message windows are opened See Also xdialog xmdialog messagebox Parte XVI Link Dinâmicoincremental 1213 Name call chamada a rotinas de usuário FORTRAN ou C forma longa out está presente y1ykcallidentx1px1tx1xnpxntxn outny1my1py1ty1nylmylpyltyl forma curta nenhum parâmetro out y1ykcallidentx1xn Parâmetros ident string xi real matrix or string pxi pyi inteiro txi tyi string d r i ou c Descrição Chamada interativa ao programa do usuário FORTRAN ou C do Scilab A rotina deve estar previa mente linkada ligada ao Scilab Este link pode ser feito Com o comando link do Scilab linkagem suave soft incremental durante a sessão Scilab ver link Há duas formas de sintaxe de chamamento uma curta e uma longa A curta fornece um código mais rápido e uma sintaxe de chamamento mais fácil mas devese escrever uma pequena interface C ou FORTRAN para que esta forma seja possível A forma longa torna possível uma chamada a uma rotina FORTRAN ou C sem modificação do código mas a sintaxe é mais complexa e o código interpretado mais devagar O significado de cada parâmetro é descrito abaixo ident é o nome da subrotina chamada x1xn são as variáveis de entrada strings ou matrizes de reais enviados à rotina px1pxn são as respectivas posições destas variáveis na seqüência de chamamento da rotina ident e tx1txn são seus tipos r i d e c para ponto flutuante real inteiro dupla precisão e strings out é a palavrachave usada para separar variáveis de entrada das variáveis de saída Quando esta palavrachave está presente ela indica que a forma longa será usada e quando não está presente indica que a forma curta será usada ny1 my1 são os tamanhos número de linhas e colunas Para argumentos c m1n1 é o número de carac teres das variáveis de saída e call 1214 py1 são as posições das variáveis de saída possivelmente iguais a pxi na seqüência de chamamento da rotina Os inteiros pyis devem estar em ordem crescente ty1 são os tipos FORTRAN das variáveis de saída As k primeiras variáveis de saída são postas em y1 yk Se uma variável de saída coincide com uma variável de entrada ie pyipxj podese apenas passar sua posição pyi O tamanho e tipo de yi são então os mesmos que os dexi Se uma variável de saída coincide com uma variável de entrada e são especificadas as dimensões da variável de saída mylnyl deve satisfazer a condição de compatibilidade mxknxk mylnyl Exemplos Exemplo 1 com um código C simples f1include mathh void fooccabmn double abc int mn int i for i 0 i mn i ci sinai b mputlf1foocc criando a biblioteca compartilhada um gateway ligação um Makefile e um loader carregador são gerados ilibforlinkfoocfooccc carregando a biblioteca compartilhada exec loadersce usando a nova primitiva a123456b pi mnsizea Entradas a está na posição 2 e double b 3 double n 4 integer m 5 integer Saídas c está na posição 1 e double com tamanho mn ccallfooca2db3dm4in5ioutmn1d Exemplo 2 com um código FORTRAN simples f1 subroutine foofcabnm integer nm double precision abc do 10 i1mn ci sinaib 10 continue call 1215 end mputlf1fooff criando a biblioteca compartilhada um gateway um Makefile e um loader são gerados ilibforlinkfooffoofff carrega a biblioteca compartilhada exec loadersce usando a nova primitiva a123456b pi mnsizea ccallfoofa2db3dm4in5ioutmn1d Ver Também link clink intersci addinter 1216 Name Gmake call make or nmake RfilesGmakefilesdllname Parameters files a character string or a vector of character string dllname a character string Rfiles vector of character string Rfiles can be used as a first argument when calling addinter function Description On Unix like systems Gmake calls the make utility for building target files and returns the val ue of files in the variable Rfiles On windows platforms Gmake calls the nmake utility for building target dllname and it returns the value of dllname in the variable Rfiles Of course Gmake will work if apropriate Makefiles are provided in the current Scilab directory Gmake can be used to provide OS independant call to addinter Examples if MSDOS then txt ex1cdll echo echo From Makefilemak echo mputltxtTMPDIRmakefilemak currentdir pwd cd TMPDIR filesGmakeTMPDIRex1cIoTMPDIRex1coex1cdll compilation addinterfilesfoobarfoubare link cdcurrentdir end See Also addinter 1217 Name VCtoLCCLib converts Ms VC libs to LCCWin32 libs VCtoLCCLib Description converts Ms VC libs to LCCWin32 libs Examples bOKchooselcccompiler VCtoLCCLib Authors Allan CORNET 1218 Name addinter new functions interface dynamic link at run time addinterfilesspnamefcts Parameters files a character string or a vector of character string contain object files used to define the new Scilab interface routine interface code user routines or libraries system libraries spname a character string Name of interface routine entry point fcts vector of character strings The name of new Scilab function implemented in the new interface in fin the order Description addinter performs dynamic link of a compiled C or Fortran new Scilab interface routine and define corresponding scilab functions You can use the command linkshow to get the number of the shared libraries And to reload a new version of an interface a call to ulink is necessary to get rid of the old version See link for more precision on use Number of addinter in a scilab session can be limited by the operating system On Windows you cannot load more than 80 dynamic libraries at the same time Number of functions implemented in a interface is limited to 1000 Examples if haveacompiler then chdirTMPDIR mkdirexampleaddinter chdirexampleaddinter src include mathh include stackch include apiscilabh include Scierrorh include localizationh static double fun2double x void fun1double xdouble y yfun2xx static double fun2double x return sinx1 addinter 1219 int scifun1char fname int iType1 0 SciErr sciErr int m1 0 n1 0 double pdVarOne NULL int piAddressVarOne NULL CheckRhs11 CheckLhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddressVarOne ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddressVarOne iType1 ifsciErriErr printErrorsciErr 0 return 0 if iType1 scimatrix Scierror999s Wrong type for input argument d A string expected fname 1 return 0 sciErr getMatrixOfDoublepvApiCtx piAddressVarOne m1 n1 pdVarOne ifsciErriErr printErrorsciErr 0 return 0 fun1pdVarOne pdVarOne LhsVar1 1 return 0 mputlsrcTMPDIR exampleaddinterexampleaddinterc filesexampleaddinterc ilibbuildaddinterfun1inscilabscifun1files dispmgetlloadersce exec loadersce fun1inscilabpi end if haveacompiler addinter 1220 See Also link intersci newfun clearfun Authors Allan CORNET 1221 Name clink check incrementaldynamic link clinkroutinename testilibclinkroutinename testclinkroutinenamenum Parameters routinename a character string num test boolean indicates if there is a shared library which contains routinename ilib a scalar the number of the shared library which contains routinename Description clink is a boolean function which checks if the routine routinename is currently linked This function returns a boolean value true or false When used with two return values the function clink returns a boolean value in test and the number of the shared library which contains routinename in ilib when test is true See Also link fort 1222 Name chooselcccompiler choose LCCWin32 as the default C Compiler bOKchooselcccompiler Parameters bOK returns T if LCCWin32 is the default C Compiler Description choose LCCWin32 as the default C Compiler Examples bOKchooselcccompiler Authors Allan CORNET 1223 Name configurelcc set environments variables for LCCWin32 C Compiler bOKconfigurelcc Parameters bOK returns T if environments variables for LCCWin32 C Compiler are OK Description set environments variables for LCCWin32 C Compiler Examples bOKconfigurelcc Authors Allan CORNET 1224 Name configureifort set environments variables for Intel Fortran Compiler Windows bOKconfiguremsifort Parameters bOK returns T if environments variables for Intel fortran 9 or 10 Compiler are OK Description set environments variables for Intel fortran 9 or 10 Compiler Examples bOK configuremsifort Authors Allan CORNET 1225 Name configuremsvc set environments variables for Microsoft C Compiler bOKconfiguremsvc Parameters bOK returns T if environments variables for Ms C Compiler are OK Description set environments variables for Microsoft C Compiler Examples bOKconfiguremsvc Authors Allan CORNET 1226 Name dllinfo provides information about the format and symbols provided in executable and DLL files Windows infolist dllinfofilenameoption Parameters filename a string a filename dll or exe file option a string machine exports imports infolist a list infolist1 a string name of dll or executable infolist2 a string matrix symbols imported or exported or machine type x86 or x64 Description This tool provides information about the format and symbols imported or exported provided in ex ecutable and DLL files This tool is based on dumpbinexe A tool provided with Visual studio SDK Examples if MSDOS then filename SCIbinlibscilabdll dllinfolist dllinfofilenamemachine printfMachine destination of s s dllinfolist1dllinfolist2 dllinfolist dllinfofilenameimports printfDlls dependencies of s filename for i1sizedllinfolist printfs dllinfolisti1 end dllinfolist dllinfofilenameexports printfDll exports of s filename dispdllinfolist end See Also addinter link ilibcompile ilibgenMake ilibgengateway ilibgenloader ilibforlink Authors Allan CORNET 1227 Name findlcccompiler detects LCCWin32 C Compiler retfindlcccompiler Parameters ret returns T or F Description detects LCCWin32 C Compiler Examples retfindlcccompiler Authors Allan CORNET 1228 Name findmsifortcompiler detects Intel fortran Compiler ifortvfindmsifortcompiler Parameters ifortv returns ifort90ifort10ifort11unknown Description detects Intel fortran Compiler Windows Examples ifortv findmsifortcompiler Authors Allan CORNET 1229 Name findmsvccompiler detects Microsoft C Compiler msvcfindmsvccompiler Parameters msvc returns msvc70msvc71msvc80expressmsvc80stdmsvc80promsvc90expressmsvc90stdmsvc90prounknown Description detects Microsoft C Compiler Examples msvcfindmsvccompiler Authors Allan CORNET 1230 Name fort Fortran or C user routines call long form out is present y1ykfortidentx1px1tx1xnpxntxn outny1my1py1ty1nylmylpyltyl short form no out parameter y1ykfortidentx1xn Parameters ident string xi real matrix or string pxi pyi integers txi tyi character string d r i or c Description Interactive call of Fortran or C user program from Scilab The routine must be previously linked with Scilab This link may be done with Scilab link command dynamic link during the Scilab sessionsee link There are two forms of calling syntax a short one and a long one The short one will give faster code and an easier calling syntax but one has to write a small C or Fortran interface in order to make the short form possible The long one make it possible to call a Fortran routine or a C one whitout modification of the code but the syntax is more complex and the interpreted code slower The meaning of each parameter is described now ident is the name of the called subroutine x1xn are input variables real matrices or strings sent to the routine px1pxn are the respective positions of these variables in the calling sequence of the routine ident and tx1txn are their types r i d and c for real float integer double precision and strings out is a keyword used to separate input variables from output variables when this key word is present it is assumes that the long form will be used and when it is not prsent the short form is used ny1 my1 are the size number of rows and columns For c argumentsm1n1 is the number of charaters of output variables and py1 are the positions of output variables possibly equal to pxi in the calling sequence of the routine The pyis integers must be in increasing order fort 1231 ty1 are the Fortran types of output variables The k first output variables are put in y1 yk If an output variable coincides with an input variable ie pyipxj one can pass only its position pyi The size and type of yi are then the same as those of xi If an output variable coincides with an input variable and one specify the dimensions of the output variable mylnyl must follow the compatibility condition mxknxk mylnyl For example the following program subroutine foofcabnm integer nm double precision abc do 10 i1mn ci sinaib 10 continue end linkfoofgetdynlibextfoof a123456b pi mnsizea Inputs a is in position 2 and double b 3 double n 4 integer m 5 integer Outputs c is in position 1 and double with size mn cfortfoofa2db3dn4im5ioutmn1d returns the matrix c2ab The same example coded in C void fooccabmn double abc int mn double sin int i for i 0 i lt mn i ci sinai b linkfoocgetdynlibextfoocC note the third argument a123456b pi mnsizea cfortfooca2db3dm4in5ioutmn1d See Also call link clink intersci addinter 1232 Name getdynlibext get the extension of dynamic libraries on your operating system retgetdynlibext Description get the extension of dynamic libraries on your operating system retgetdynlibext returns so on linuxsl HPUXdll on Windows Examples getdynlibext Authors Allan CORNET 1233 Name haveacompiler detect if you have a C compiler bOKhaveacompiler Parameters bOK returns T if you have a C compiler Description detect if you have a C compiler Examples bOK haveacompiler See Also findlcccompiler findmsvccompiler 1234 Name ilibbuild utility for shared library management ilibbuildlibnametablefileslibs makenameldflagscflagsfflagsismex cc Parameters libname a character string the generic name of the library without path and extension table 2 column string matrix giving the table of pairs scilabname interface name files string matrix giving source from Scilab 50 or object files needed for shared library creation libs string matrix giving extra libraries needed for shared library creation makename character string The path of the Makefile file without extension ldflagscflagsfflags character strings to provide options for the loader the C compiler and the Fortran compiler ismex Internal variable to specify if we are working with mex or not cc Provide the name of the C compiler Description This tool is used to create shared libraries and to generate a loader file which can be used to dynamically load the shared library into Scilab with addinter Many examples are provided in SCImodulesdynamiclinkexamples directory They are all released into the public domain Note that a compiler must be available on the system to use this function Languages handle by this function are C C Fortran and Fortran 90 Examples C code Here with give a complete example on adding new primitive to Scilab create the procedure files cd TMPDIR mkdirexampleilibbuildc cdexampleilibbuildc f1extern double fun2 void fun1double x double y yfun2xx mputlf1TMPDIR exampleilibbuildcfun1c f2include mathh ilibbuild 1235 double fun2double x return sinx1 mputlf2TMPDIR exampleilibbuildcfun2c creating the interface file iinclude stdlibh include stackch include apiscilabh include Scierrorh include localizationh extern int fun1 double x double y int scifun1char fname int iType1 0 SciErr sciErr int m1 0 n1 0 double pdVarOne NULL int piAddressVarOne NULL CheckRhs11 CheckLhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddressVarOne ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddressVarOne iType1 ifsciErriErr printErrorsciErr 0 return 0 if iType1 scimatrix Scierror999s Wrong type for input argument d A string expected fname 1 return 0 sciErr getMatrixOfDoublepvApiCtx piAddressVarOne m1 n1 pdVarOne ifsciErriErr printErrorsciErr 0 return 0 fun1pdVarOne pdVarOne LhsVar1 1 return 0 mputliTMPDIR exampleilibbuildcscifun1c creating the shared library a gateway a Makefile and a loader are ilibbuild 1236 generated filesfun1cfun2cscifun1c ilibbuildbuildcfun1scifun1files load the shared library exec loadersce using the new primitive fun133 Examples C code previous Scilab API 52 cd TMPDIR mkdirexampleilibbuildcold cdexampleilibbuildcold Here with give a complete example on adding new primitive to Scilab create the procedure files f1extern double fun2 void fun1double x double y yfun2xx mputlf1fun1c f2include mathh double fun2double x return sinx1 mputlf2fun2c creating the interface file iinclude stackch include stackTypeVariableh include versionh if SCIVERSIONMAJOR 5 if SCIVERSIONMINOR 2 error This example is obsolete see help ilibbuid endif endif extern int fun1 double x double y int intfun1char fname int m1n1l1 CheckRhs11 CheckLhs11 GetRhsVar1 MATRIXOFDOUBLEDATATYPE m1 n1 l1 fun1stkl1stkl1 LhsVar1 1 return 0 mputliintfun1c creating the shared library a gateway a Makefile and a loader are generated ilibbuild 1237 filesfun1cfun2cintfun1c ilibbuildilibcoldscifun1intfun1files load the shared library exec loadersce using the new primitive scifun133 Examples C code cd TMPDIR mkdirexampleilibbuildcpp cdexampleilibbuildcpp iinclude string extern C include stdlibh include stackch include apiscilabh include localizationh include Scierrorh int scicppfindchar fname SciErr sciErr int piAddressVarOne NULL char pStVarOne NULL int iType1 0 int lenStVarOne 0 int m1 0 n1 0 int piAddressVarTwo NULL char pStVarTwo NULL int iType2 0 int lenStVarTwo 0 int m2 0 n2 0 int mout 0 int nout 0 sciErr getVarAddressFromPositionpvApiCtx 1 piAddressVarOne ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddressVarOne iType1 ifsciErriErr printErrorsciErr 0 return 0 ilibbuild 1238 if iType1 scistrings Scierror999s Wrong type for input argument d A string expected fname 1 return 0 sciErr getVarAddressFromPositionpvApiCtx 2 piAddressVarTwo ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddressVarTwo iType2 ifsciErriErr printErrorsciErr 0 return 0 if iType2 scistrings Scierror999s Wrong type for input argument d A string expected fname 2 return 0 sciErr getMatrixOfStringpvApiCtx piAddressVarOne m1 n1 lenStVarOne pStVarOne ifsciErriErr printErrorsciErr 0 return 0 pStVarOne new charlenStVarOne 1 if pStVarOne NULL Scierror999s Memory allocation error fname return 0 sciErr getMatrixOfStringpvApiCtx piAddressVarTwo m2 n2 lenStVarTwo pStVarTwo ifsciErriErr printErrorsciErr 0 return 0 pStVarTwo new charlenStVarTwo 1 if pStVarTwo NULL Scierror999s Memory allocation error fname return 0 sciErr getMatrixOfStringpvApiCtx piAddressVarOne m1 n1 lenStVarOne pStVarOne ifsciErriErr ilibbuild 1239 printErrorsciErr 0 return 0 sciErr getMatrixOfStringpvApiCtx piAddressVarTwo m2 n2 lenStVarTwo pStVarTwo ifsciErriErr printErrorsciErr 0 return 0 stdstring myMessagepStVarOne stdstring searchpStVarTwo delete pStVarTwo delete pStVarOne double dOut 00 if myMessagefindsearch stdstringnpos dOut myMessagefindsearch The actual operation else dOut 1 Substring not found mout 1 nout 1 sciErr createMatrixOfDoublepvApiCtx Rhs 1 mout nout dOut ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 extern C mputliTMPDIR exampleilibbuildcppscicppfindcxx creating the shared library a gateway a Makefile and a loader are generated files scicppfindcxx ilibbuildilibbuildcppcppfindscicppfindfiles load the shared library exec loadersce Small test to see if the function is actually working if cppfindmy very long stringlong 8 pause end if cppfindmy very long stringvery 3 pause end if cppfindmy very long stringshort 1 pause end ilibbuild 1240 Examples C code previous Scilab API 52 cd TMPDIR mkdirexampleilibbuildcppold cdexampleilibbuildcppold iinclude string extern C include stackch include versionh if SCIVERSIONMAJOR 5 if SCIVERSIONMINOR 2 error This example is obsolete see help ilibbuid endif endif int scicppfindchar fname int m1 0 n1 0 l1 char inputString1 inputString2 int m2 0 n2 0 l2 int m3 0 n3 0 double position NULL Where we will store the position CheckRhs22 Check the number of input argument CheckLhs11 Check the number of output argument GetRhsVar1 c m1 n1 l1 Retrieve the first input argument inputString1cstkl1 GetRhsVar2 c m2 n2 l2 Retrieve the second input argument inputString2cstkl2 stdstring myMessage inputString1 stdstring search inputString2 m31n31 position new double1 if myMessagefindsearch stdstringnpos position0 myMessagefindsearch The actual operation else position0 1 Substring not found CreateVarFromPtrRhs1dm3n3position Create the output argument LhsVar1 Rhs1 delete position return 0 mputliscicppfindcxx creating the shared library a gateway a Makefile and a loader are generated filesscicppfindcxx ilibbuildfoooldcppfindscicppfindfiles load the shared library exec loadersce ilibbuild 1241 Small test to see if the function is actually working if cppfindmy very long stringlong 8 pause end if cppfindmy very long stringvery 3 pause end if cppfindmy very long stringshort 1 pause end Examples Fortran 90 code cd TMPDIR mkdirexampleilibbuildf90 cdexampleilibbuildf90 sourcecodesubroutine incrdoublef90xy implicit none double precision intentin x double precision intentout y yx1 end subroutine incrdoublef90 mputlsourcecodeincrdoublef90f90 libpathilibforlinkincrdoublef90incrdoublef90f90f exec loadersce n1 mcallincrdoublef90n1dout112d if absm2eps then pauseend n2 mcallincrdoublef90n1dout112d if absm3eps then pauseend See Also addinter link ilibcompile ilibgenMake ilibgengateway ilibgenloader ilibforlink Author Allan CORNET 1242 Name ilibcompile ilibbuild utility executes the Makefile produced by ilibgenMake libnilibcompilelibnamemakename filesldflagscflagsfflagscc Parameters libname a character string the generic name of the library without path and extension makename character string The path of the Makefile file without extension files optionnal vector of character strings If files is given the make is performed on each target con tained in files then a whole make is performed libn character string The path of the actual generated shared library file ldflagscflagsfflagscc character strings to provide optionsflags for the loader the C compiler the Fortran compiler cc provides the name of the compiler Description Utility function used by ilibbuild This executes the Makefile produced by ilibgenMake compiles the C and fortran files and generates the shared library Shared libraries can then be used with the link and addinter Scilab function for incrementaldy namic link Note that a compiler must be available on the system to use this function See Also addinter link ilibbuild ilibgenMake ilibgengateway ilibgenloader ilibforlink 1243 Name ilibforlink utility for shared library management with link libnilibforlinknamesfileslibsflag makename loadername libname ldflags cflags fflags cc Parameters names a string matrix giving the entry names which are to be linked files string matrix giving source from Scilab 50 or object files needed for shared library creation libs string matrix giving extra libraries needed for shared library creation flag a string flag c or f for C or Fortran entry points makename character string The pathname of the Makefile file without extension default value Makelib loadername character string The pathname of the loader file default value is loadersce libname optional character string The name of the generated shared library default value is and in this case the name is derived from names1 ldflags optional character string It can be used to add specific linker options in the generated Makefile Default value is cflags optional character string It can be used to add specific C compiler options in the generated Make file Default value is fflags optional character string It can be used to add specific Fortran compiler options in the generated Makefile Default value is cc optional character string It can be used to specify a C compiler Default value is libn character string The path of the really generated shared library file Description This tool is used to create shared libraries and to generate a loader file which can be used to dynamically load the shared library into Scilab with the link function New entry points given by names are then accessible through the call function or with non linear tools ode optim The file to compile are supposed to be located given by makename If makename sets a path different to the current directory loader script must be located in the same directory using the loadername variable Many examples are provided in SCImodulesdynamiclinkexamples directory They are all released into the public domain ilibforlink 1244 Note that a compiler must be available on the system to use this function Languages handle by this function are C C Fortran and Fortran 90 Examples C code if haveacompiler then chdirTMPDIR f1int ext1cint n double a double b double c int k for k 0 k n k ck ak bk return0 mputlf1fun1c creating the shared library a gateway a Makefile and a loader are generated ilibforlinkext1cfun1cc load the shared library exec loadersce using the new primitive a123b456n3 ccallext1cn1ia2db3dout134d if normcab eps then pauseend end See Also addinter link ilibcompile ilibgenMake ilibgengateway ilibgenloader ilibforlink 1245 Name ilibgenMake utility for ilibbuild produces a Makefile for building shared libraries MakenameilibgenMakenamefileslibsmakename withgatewayldflagscflagsfflagscc Parameters libname a character string the generic name of the library without path and extension files a vector of character string The names of the C or Fortran files without the extension and the path part libs a vector of character string additionnal libraries paths or makename character string The path of the Makefile file withgateway a boolean If true a file with name libnamegateway is added Default value is t ldflags a string It can be used to add specific linker options in the generated Makefile Default value is cflags a string It can be used to add specific C compiler options in the generated Makefile Default value is fflags a string It can be used to add specific Fortran compiler options in the generated Makefile Default value is cc a string The name of the C compiler Default value is the C compiler detected on the host Makename character string The path of the really generated Makefile file Description Utility function used by ilibbuild This function generates a Makefile adapted to the Operating System for building shared libraries to be loaded in Scilab Proper options and paths are set Shared libraries can then be used with the link and addinter scilab function for incrementaldy namic linking The shared library is build from a set of C or Fortran routines stored in a directory and if required from a set of external libraries Files are not required to exist when Makefile is generated but of course are required for executing the Makefile Only use this function is you know what you are doing it is a semiprivate function ilibgenMake 1246 See Also addinter link ilibbuild ilibcompile ilibgengateway ilibgenloader ilibforlink 1247 Name ilibgencleaner utility for ilibbuild generates a cleaner file ilibgencleanermakenameloadernamefiles Parameters makename character string The pathname of the Makefile file without extension default value Makelib loadername character string The pathname of the loader file default value is loadersce files matrix of character string files to delete Description Utility function used by ilibbuild and ilibforlink This function generates a cleaner file See Also ilibgenloader ilibbuild ilibforlink 1248 Name ilibgengateway utility for ilibbuild generates a gateway file ilibgengatewaynametable Parameters name a character string the generic name of the library without path and extension table 2 column string matrix giving the table of pairs scilabname interface name Description Utility function used by ilibbuild This function generates a gateway file used by addinter if WITHOUTAUTOPUTLHSVAR variable is defined and equals to t PutLhsVar will need to manage PutLhsVar in each interface as internal scilab functions In another case default for compatibility with previous version PutLhsVar is added in each interface You can also see SCIcontribtoolboxskeletonscigatewaycbuildergatewaycsce as example about WITHOUTAUTOPUTLHSVAR Example about WITHOUTAUTOPUTLHSVAR t cd TMPDIR WITHOUTAUTOPUTLHSVAR t name gwexample1 table scifunc1 func1 ilibgengatewaynametable generated gateway mgetlTMPDIRgwexample1c int scifunc1char fname your C code you need to add a explicit PutLhsVar as internal all gateways of scilab PutLhsVar return 0 Example about WITHOUTAUTOPUTLHSVAR f default cd TMPDIR WITHOUTAUTOPUTLHSVAR f ilibgengateway 1249 name gwexample2 table scifunc2 func2 ilibgengatewaynametable generated gateway mgetlTMPDIRgwexample2c int scifunc2char fname your code you do NOT need to add a explicit PutLhsVar added by scilab after call to scifunc2 default mode in scilab 4 return 0 See Also addinter link ilibbuild ilibcompile ilibgenMake ilibgenloader ilibforlink 1250 Name ilibgenloader utility for ilibbuild generates a loader file ilibgenloadernametablelibs Parameters name a character string the generic name of the library without path and extension table 2 column string matrix giving the table of pairs scilabname interface name libs a string matrix externals dynamic libraries filenames to load by loader file optional Description Utility function used by ilibbuild This function generates a loader file See Also addinter link ilibbuild ilibcompile ilibgenMake ilibgenloader ilibforlink 1251 Name ilibmexbuild utility for mex library management ilibmexbuildlibnametablefileslibs makenameldflagscflagsfflagscc Parameters libname a character string the generic name of the library without path and extension table 3 column string matrix giving the table of scilabname interface name cmex or fmex files string matrix giving objects files needed for shared library creation libs string matrix giving extra libraries needed for shared library creation makename character string The path of the Makefile file without extension ldflagscflagsfflagscc character strings to provide optionsflags for the loader the C compiler the Fortran compiler cc provides the name of the compiler Description This function is used to create mex libraries and to generate a loader file which can be used to dynam ically load the mex shared library Note that the file name containing the mex code can be set in the third input argument files or the second value of the table input argument Note that a compiler must be available on the system to use this function Examples cdTMPDIR mputlinclude mexh void mexFunctionint nlhs mxArray plhs int nrhs mxArray prhs int dims mxGetDimensionsprhs0 sciprintd d d dims0dims1dims2 mexfunction16c ilibmexbuildlibmexmexf16mexfunction16cmexMakelib execTMPDIRloadersce mexf16rand232 See Also addinter link ilibcompile ilibgenMake ilibgengateway ilibgenloader ilibforlink 1252 Name ilibverbose set level of display used by dynamic link functions level ilibverbose ilibverboselevel Parameters level level of verbose for dynamic link functions 0 no message 1 default level as previous version of scilab 2 maximum verbose level configure makefile debug information Description ilibverbose set level of display used by dynamic link functions All dynamic functions in dynamic link module check this value and display or not some informations Examples if haveacompiler then curverbose ilibverbose ilibverbose0 chdirTMPDIR f1int ext1cint n double a double b double c int k for k 0 k n k ck ak bk return0 mputlf1fun1c ilibforlinkext1cfun1cc exec loadersce using the new primitive a123b456n3 c callext1cn1ia2db3dout134d if normcab eps then pauseend ilibverbose1 f2int ext2cint n double a double b double c int k for k 0 k n k ck ak bk return0 ilibverbose 1253 mputlf2fun2c ilibforlinkext2cfun2cc exec loadersce using the new primitive a 123 b 456n 3 c callext2cn1ia2db3dout134d if normcab eps then pauseend ilibverbosecurverbose end See Also mode link ilibcompile ilibbuild ilibforlink Authors Allan CORNET 1254 Name link dynamic linker xlinkfiles subnamesflag linkx subnames flag ulinkx lstlinkshow lstlink Parameters files a character string or a vector of character strings the files names used to define the new entry point compiled routines user libraries system libraries subnames a character string or a vector of character strings Name of the entry points in files to be linked x an integer which gives the id of a shared library linked into Scilab with a previous call to link flag character string f or c for Fortran default or C code Description link is a incrementaldynamic link facility this command allows to add new compiled Fortran or C routines to Scilab executable code Linked routines can be called interactively by the function call Linked routines can also be used as external for eg non linear problem solvers ode optim intg dassl link returns a string matrix with linked functions a call to link returns an integer which gives the id of the shared library which is loaded into Scilab This number can then be used as the first argument of the link function in order to link additional function from the linked shared library The shared library is removed with the ulink command A routine can be unlinked with ulink If the linked function has been modified between two links it is required to ulink the previous instance before the new link linkshow returns the current linked routines To be able to link routines in a system independent way it is convenient to use the ilibforlink utility function instead of link Experienced users may also link a new Scilab interface routine to add a set of new functions See ilibbuild and addinter functions Number of link in a scilab session can be limited by the operating system On Windows you cannot load more than 80 dynamic libraries at the same time Examples Example of the use of ilibforlink with a simple C code cd TMPDIR f1include mathh link 1255 void foocdouble cdouble adouble bint mint n int i for i 0 i mn i ci sinai b mputlf1foocc creating the shared library a Makefile and a loader are generated the code is compiled and a shared library built ilibforlinkfoocfooccc display the loadersce file which calls link mprintfs mgetlloadersce load the shared library exec loadersce linkshow call the new linked entry point alinspace0pi10b5 y1callfooca2db3dsizea14isizea25ioutsizea1d check y1sinab exec cleanersce See Also call external clink addinter ilibforlink ilibbuild 1256 Name ulink unlink a dynamically linked shared object ulinkx ulink Description see link If you plan to use valgrind to profile your toolbox you must first set the environment variable PROFILESCILABDYNAMICLINK before starting scilab under bash shell export PROFILESCILABDYNAMICLINK1 export SCILABVALGRINDOPTdbattachno showbelowmainyes logfd2 logfilescilabtxt numcallers50 v tracerediryes readvarinfoyes tracechildrenyes showreachableyes smccheckall childsilentafterforkno leakcheckfull trackoriginsyes scilab nwni profile This environment variable force Scilab not to release the loaded dynamic libraries This will allow valgrind to perform its sumup analysis See Also link 1257 Name withlcc returns if LCCWin32 is the default C Compiler bOKwithlcc Parameters bOK returns T if LCCWin32 is the default C Compiler Description checks if LCCWin32 is the default C Compiler Examples bOKwithlcc Authors Allan CORNET Parte XVII Inteiros 1259 Name iconvert conversão para representação inteira de 1 a 4 bytes yiconvertXitype Parâmetros X matriz de floats ou inteiros y matriz de inteiros codificados em 1 2 ou 4 bytes Descrição Converte e armazena dados para inteiros de 1 2 ou 4 bytes itype0 retorna números em ponto flutuante itype1 retorna números int8 no intervalo 128127 itype11 retorna números uint8 no intervalo 0255 itype2 retorna números int16 no intervalo 3276832767 itype12 retorna números uint16 no intervalo 0 65535 itype4 retorna números int32 no intervalo 21474836482147483647 itype14 retorna números uint32 no intervalo 0 4294967295 Exemplos bint321 120 127 312 yiconvertb1 Ver Também double inttype 1260 Name int8 conversão para representação de inteiro de 1 byte int16 conversão para representação de inteiro de 2 bytes int32 conversão para representação de inteiro de 1 byte sem sinal uint8 conversão para representação de inteiro de 2 byte sem sinal uint16 conversão para representação de inteiro de 4 byte sem sinal uint32 conversão para representação de inteiro de 4 byte sem sinal yint8X yint16X yint32X yuint8X yuint16X yuint32X Parâmetros X matriz de números em ponto flutuante ou inteiros y matriz de inteiros codificados em 1 2 ou 4 bytes Descrição Converte e armazena dados em interos de 1 2 ou 4 bytes Estes tipos de dados são especialmente úteis para armazenar objetos grandes como imagens sinais longos yint8X retorna números no intervalo 128127 yuint8X retorna números no intervalo 0255 yint16X retorna números no intervalo 3276832767 yuint16X retorna números no intervalo 0 65535 yint32X retorna números no intervalo 21474836482147483647 yuint32X retorna números no intervalo 0 4294967295 Exemplos int81 120 127 312 uint81 120 127 312 xint32200100400 int8x Ver Também double inttype iconvert 1261 Name inttype tipos de dados inteiros iinttypex Parâmetros x uma matriz de inteiros ver int8 i inteiro Descrição inttypex retorna um inteiro que indica o tipo das entradas de x como segue 1 representação de inteiros de um byte 2 representação de inteiros de dois bytes 4 representação de inteiros de quatro bytes 11 representação de inteiros de um byte sem sinal 12 representação de inteiros de dois bytes sem sinal 14 representação de inteiros de quatro bytes sem sinal Exemplos xuint16110 inttypex Ver Também int8 Parte XVIII Interpolação 1263 Name bsplin3val função de avaliação de derivada arbitrária de spline 3d dfpbsplin3valxpypzptlder Parâmetros xp yp zp vetores ou matrizes de reais de tamanhos iguais tl tlist de tipo splin3d definindo um tensor spline 3d chamado de s a seguir der vetor com três componentes oxoyoz definindo qual derivada de s computar dfp vetor ou matriz de mesmo formato que xp yp e zp avaliação elemento a elemento da derivada especificada de s nesses pontos Descrição Enquanto a função interp3d pode computar apenas o spline s e suas primeiras derivadas bsplin3val pode computar qualquer derivada de s A derivada a ser computada é especificada pelo argumento deroxoyoz ox oy oz d d d dfpi s xpiypizpi ox oy oz dx dy dz Então der0 0 0 corresponde a s der1 0 0 to dsdx der0 1 0 to dsdy der1 1 0 to d2sdxdy etc Para um ponto com coordenadas xpiypizpi fora do grid a função retorna 0 Exemplos deffvfxyzvcosxsinycosz deffvfxxyzvsinxsinycosz deffvfxyxyzvsinxcosycosz deffvfxyzxyzvsinxcosysinz deffvfxxyzxyzvcosxcosysinz n 20 n x n x n pontos de interpolação x linspace02pin yx zx grid de interpolação XYZ ndgridxyz V fXYZ tl splin3dxyzV5 5 5 computando f e algumas derivadas em um ponto e comparando com o spline interpolante xp grand11unf02pi yp grand11unf02pi zp grand11unf02pi bsplin3val 1264 fe fxpypzp fi bsplin3valxpypzptl0 0 0 fxe fxxpypzp fxi bsplin3valxpypzptl1 0 0 fxye fxyxpypzp fxyi bsplin3valxpypzptl1 1 0 fxyze fxyzxpypzp fxyzi bsplin3valxpypzptl1 1 1 fxxyze fxxyzxpypzp fxxyzi bsplin3valxpypzptl2 1 1 Ver Também splin3d interp3d Autores RF Boisvert C De Boor código da biblioteca FORTRAN CMLIB B Pincon interface Scilab 1265 Name cshep2d bidimensional cubic shepard scattered interpolation tlcoef cshep2dxyz Parâmetros xyz uma matriz n x 3 dos pontos de interpolação interpolação sem grid a iésima linha dadas as coordenadas xy e então a altitude z do iésimo ponto de interpolação tlcoef uma estrutura tlist do Scilab do tipo cshep2d Descrição Esta função é útil para definir uma função de interpolação 2d quando os pontos não estão em um grid você pode usála para este caso mas splin2d é melhor para este propósito O interpolante é do tipo cúbico de Shepard e é uma função de duas variáveis de classe C2 duas vezes continuamente diferenciável sxy tal que sxiyizi para todo i1n xiyizi sendo a iésima linha de xyz A avaliação de s em alguns pontos deve ser feita pela função evalcshep2d Observação A função operea se n 10 se os nós não são todos colineares ie as coordenadas xy dos pontos de interpolação não estão na mesma reta e se não há nós duplicados ie dois ou mais pontos de interpolação com as mesmas coordenadas xy Há erro se essas condições não são respeitadas Exemplos interpolação de cosxcosy com pontos de interpolação escolhidos aleatoriamente n 150 número de pontos de interpolação xy grandn2unf02pi z cosxy1cosxy2 xyz xy z tlcoef cshep2dxyz avaliação em um grid m 30 xx linspace02pim XY ndgridxxxx Z evalcshep2dXY tlcoef xbasc plot3dxxxxZflag2 6 4 param3d1xy1xy2listz9 flag0 0 xtitleInterpolação cúbica de Shepard de cosxcosy com pontos de interpolação escolhidos aleatoriamente legendspontos de interpolação91 xselect Ver Também splin2d evalcshep2d cshep2d 1266 Autores Robert J Renka B Pincon interface do Scilab 1267 Name evalcshep2d avaliação por interpolação cúbica bidimensional de Shepard zp dzpdx dzpdy d2zpdxxd2zpdxyd2zpdyy evalcshep2dxp yp tlcoef Parâmetros xp yp dois vetores ou matrizes de mesmo tamanho tlcoef uma estrutura Scilab tlist de tipo cshep2d definindo uma função de interpolação cúbica de Shep ard chamada S a partir daqui zp vetor ou matrizes de mesmo tamanho que xp e yp avaliação do interpolante S nesses pontos dzpdxdzpdy vetores ou matrizes de mesmo tamanho que xp e yp avaliação das derivadas primeiras de S nestes pontos d2zpdxxd2zpdxyd2zpdyy vetores ou matrizes de mesmo tamanho que xp e yp avaliação das derivadas segundas de S nestes pontos Descrição Esta é a rotina de avaliação para a função de interpolação cúbica de Shepard obtida com cshep2d isto é zpi Sxpiypi dzpdxi dSdxxpiypi dzpdyi dSdyxpiypi d2zpdxxi d2Sdx2xpiypi d2zpdxyi d2Sdxdyxpiypi d2zpdyyi d2Sdy2xpiypi Observação O interpolante S é C2 duas vezes continuamente diferenciável mas também é estendido por zero para xy suficientemente longe dos pontos de interpolação Isto leva a uma descontinuidade em regiões exteriores muito longe dos pontos de interpolação e assim a avaliação não se torna incoveniente na prática de um modo geral avaliação fora dos pontos de interpolação ie extrapolação leva a resultados muito inacurados Exemplos ver seção de exemplos em cshep2d este exemplo mostra o comportamento longe dos pontos de interpolação deffzfxyz 1 50x1xy1y2 x linspace0110 XY ndgridxx evalcshep2d 1268 X X Y Y Z fXY S cshep2dX Y Z avaliação dentro e fora do quadrado 01x01 m 40 xx linspace1505m xpyp ndgridxxxx zp evalcshep2dxpypS computando faceta para definir uma cor para a região de extrapolação e outra para a região de interpolação xfyfzf genfac3dxxxxzp color 2ones1sizezf2 índices correspondentes à faceta na região de interpolação indfind meanxfr0 meanxfr1 meanyfr0 meanyfr1 colorind3 xbasc plot3dxfyflistzfcolor flag2 6 4 legendsregião de extrapolaçãoregião de interpolação2 31 xselect Ver Também cshep2d Autores Robert J Renka B Pincon interface Scilab 1269 Name interp função de avaliação de spline cúbico yp yp1 yp2 yp3interpxp x y d outmode Parâmetros xp vetor ou matriz de reais xyd vetores de reais de mesmo tamanho definindo uma função de spline cúbico ou subspline chama do s a partir daqui outmode opcional string definido a avaliação de s fora do intervalo x1xn yp vetor ou matriz de mesmo tamanho que xp avaliação elemento a elemento de s em xp ypisxpi ou ypijsxpij yp1 yp2 yp3 vetores ou matrizes de mesmo tamanho que xp avaliação elemento a elemento das derivadas sucessivas de s em xp Descrição Dados três vetores xyd ddefinindo uma função de spline cúbico ou supspline ver splin com yisxi di sxi esta função avalia s e s s s se necessário em xpi ypi sxpi ou ypij sxpij yp1i sxpi ou yp1ij sxpij yp2i sxpi ou yp2ij sxpij yp3i sxpi ou yp3ij sxpij O parâmetro outmode ajusta a regra de avaliação para extrapolação ie para xpi fora de x1xn byzero uma extrapolação por zero é feita bynan extrapolação por NaN C0 a extrapolação é definida como segue sx y1 para x x1 sx yn para x xn natural a extrapolação é definida como segue pi sendo o polinômio que define s em xixi1 interp 1270 sx p1x para x x1 sx pn1x para x xn linear a extrapolação é definida como segue sx y1 sx1xx1 para x x1 sx yn sxnxxn para x xn periodic s é estendido por periodicidade Exemplos veja os exemplos de splin e lsqsplin um exemplo exibindo as continuidades C2 e C1 de um spline e um subspline a 8 b 8 x linspaceab20 y sincx dk splinxy notaknot df splinxy fast xx linspaceab800 yyk yy1k yy2k interpxx x y dk yyf yy1f yy2f interpxx x y df xbasc subplot311 plot2dxx yyk yyf plot2dx y style9 legendsspline não é um nósubspline rápidopontos de interpolação 1 2 9 urf xtitleinterpolação por spline subplot312 plot2dxx yy1k yy1f legendsspline não é um nósubspline rápido 1 2 urf xtitleinterpolação por spline derivadas subplot313 plot2dxx yy2k yy2f legendsspline não é um nósubspline rápido 1 2 lrf xtitleinterpolação por splines segundas derivadas aqui está um exemplo mostrando as diferentes possibilidades de extrapolação x linspace0111 y coshx05 d splinxy xx linspace0515401 yy0 interpxxxydC0 yy1 interpxxxydlinear yy2 interpxxxydnatural yy3 interpxxxydperiodic xbasc plot2dxxyy0 yy1 yy2 yy3style25frameflag2legC0linearnaturalperiodic xtitle Modos diferentes de avaliar um spline fora de seu domínio interp 1271 Ver Também splin lsqsplin Autor B Pincon 1272 Name interp1 função de interpolação 1d ypinterp1x yxp methodextrapolation Parâmetros xp escalar real vetor ou matriz ou hipermatriz de reais x vetor de reais method opcional string definindo o método de interpolação extrapolation opcional string ou valor real defindo os componentes ypj para os valores xpj fora do intervalo x1xn yp vetor ou matriz ou hipermatriz Descrição Dados xyxp esta função faz corresponder os yp componentes aos xp por interpolação linear por padrão definida por x e y Se yp é um vetor então o comprimento de xp é igual ao comprimento de yp Se yp é uma matriz então xp tem o mesmo comprimento que cada uma das colunas de yp Se yp é uma hipermatriz então o comprimento de xp é o mesmo da primeira dimensão de yp Se sizeyCM1M2M3Mj e sizexp N1N2N3Nk então sizeyp N1N2NkM1M2Mj e o comprimento de x deve ser igual a sizey1 O parâmetro method ajusta a regra avaliação para interpolação linear a interpolação é definida pelo método linear ver interpln spline definição de interpolação por spline cúbico ver splin interp nearest para cada valor xpj ypj toma o valor ou yi correspondente ao xi o vízinho mais próximo de xpj O parâmetro extrapolation ajusta a regra de avaliação para extrapolação ie para xpi fora do intervalo x1xn extrap a extrapolação é realizada pelo método definido ypinterp1xyxpmethodextrap valor real você pode escolher um valor real para extrapolação Deste modo ypi toma este valor para xpi fora do intervalo x1xn por exemplo 0 mas também nan ou inf yiinterp1xyxpmethod 0 interp1 1273 por padrão a extrapolação é realizada pelo método definido para método spline e por nan para os métodos linear e nearest ypinterp1xyxpmethod Exemplos xlinspace0320 yx2 xxlinspace03100 yy1interp1xyxxlinear yy2interp1xyxxspline yy3interp1xyxxnearest plotxxyy1yy2yy3xy xtitleinterpolation of square function legendlinearsplinenearesta2 Ver Também interp interpln splin Autor FB 1274 Name interp2d função de avaliação spline bicúbica 2d zpdzpdxdzpdyd2zpdxxd2zpdxyd2zpdyyinterp2dxpypxyC outmode Parâmetros xp yp vetores ou matrizes de reais de mesmo tamanho xyC vetores de reais definindo uma função de spline bicúbico ou subspline chamada s daqui em diante outmode opcional string definindo a avaliação de s fora de x1xnxxy1yny zp vetor ou matriz com o mesmo formato que xp e yp avaliação elemento a elemento de s nestes pontos dzpdx dzpdy vetores ou matrizes de mesmo formato que xp e yp avaliação elemento a elemento das derivadas primeiras de s nesses pontos d2zpdxx d2zpdxy d2zpdyy vetores ou matrizes de mesmo formato que xp e yp eavaliação elemento a elemento das derivadas segundas de s nesses pontos Descrição Dados três vetores xyC definindo uma função de subspline ou spline bicúbico ver splin2d esta função avalia s e dsdx dsdy d2sdxx d2sdxy d2sdyy se necessário em xpiypi zpi sxpiypi dzpdxi dsdxxpiypi dzpdyi dsdyxpiypi d2zpdxxi d2sdx2xpiypi d2zpdxyi d2sdxdyxpiypi d2zpdyyi d2sdy2xpiypi O parâmetro outmode define a regra de avaliação para extrapolação ie para xpiypi fora de x1xnxxy1yny byzero uma extrapolação por zero é realizada bynan extrapolação por NaN C0 Extrapolação definida como segue sxy sprojxy onde projxy é o ponto mais próximo em x1xnxxy1yny de xy interp2d 1275 natural a extrapolação é realizada utilizando o elemento de área bicúbico mais próximo de xy periodic s é estendida por periodicidade Exemplos veja os exemplos de splin2d este exemplo mostra características de extrapolações diferentes interpolação de cosxcosy n 7 um grid de interpolação n x n x linspace02pin y x z cosxcosy C splin2dx y z periodic agora avaliando em um domínio maior que 02pix 02pi m 80 parâmetro de discretização do grid de avaliação xx linspace05pi25pim yy xx XXYY ndgridxxyy zz1 interp2dXXYY x y C C0 zz2 interp2dXXYY x y C byzero zz3 interp2dXXYY x y C periodic zz4 interp2dXXYY x y C natural xbasc subplot221 plot3dxx yy zz1 flag2 6 4 xtitleExtrapolação com o outmode C0 subplot222 plot3dxx yy zz2 flag2 6 4 xtitleExtrapolação com o outmode byzero subplot223 plot3dxx yy zz3 flag2 6 4 xtitleExtrapolação com o outmode periodic subplot224 plot3dxx yy zz4 flag2 6 4 xtitleExtrapolação com o outmode natural xselect Ver Também splin2d Autor B Pincon 1276 Name interp3d função de avaliação spline 3d fpdfpdxdfpdydfpdzinterp3dxpypzptloutmode Parâmetros xp yp zp vetores ou matrizes de reais de mesmo tamanho tl tlist do tipo splin3d definindo um tensor spline 3d chamado s a partir daqui outmode opcional string definindo a avaliação de s fora do grid xminxmaxxyminymaxxzminzmax fp vetor ou matriz de mesmo formato que xp yp e zp avaliação elemento a elemento de s onesses pontos dfpdx dfpdy dfpdz vetores ou matrizes de mesmo formato que xp yp e zp avaliação elemento a elemento das primeiras derivadas de s nesses pontos Descrição Dada uma tlist tl definindo uma função spline 3d ver splin3d esta função avalia s e dsdx dsdy dsdz se necessário em xpiypizpi zpi sxpiypi dzpdxi dsdxxpiypizpi dzpdyi dsdyxpiypizpi dzpdzi dsdzxpiypizpi O parâmetro outmodedefine a regra de avaliação para extrapolação ie para xpiypizpi fora de xminxmaxxyminymaxxzminzmax byzero uma extrapolação por zero é feita bynan extrapolação por NaN não é número C0 a extrapolação definida como segue sxy sprojxy onde projxy é o ponto mais próximo em x1xnxxy1yny de xy periodic s é estendido por periodicidade interp3d 1277 Exemplos veja exemplos na página da função splin3d Ver Também splin3d bsplin3val Autores RF Boisvert C De Boor código da biblioteca FORTRAN CMLIB B Pincon interface Scilab 1278 Name interpln interpolação linear yinterplnxydx Parâmetros xyd matriz de duas linhas coordenadas xy dos pontos x vetor de abscissas y vetor de ordenadas Descrição Dado xyd um conjunto de pontos no plano xy de abscissas crescentes e x aum conjunto de abscissas esta função computa y os valores correspondentes às ordenadas por interpolação linear Exemplos x1 10 20 30 40 y1 30 10 20 40 plot2dxy3011 10405050 yiinterplnxy445 plot2d445yi3000 Ver Também splin interp smooth 1279 Name intsplin integração de dados experimentais por interpolação por spline v intsplinx s Parâmetros x vetor de dados de coordenadas x crescentes O valor padrão é 1sizey s vetor de dados de coordenadas y v valor da integral Descrição Computa Onde f é uma função descrita por um conjunto de valores experimentais sifxi e x0x1 x1xn Entre os pontos da malha a função é interpolada usandose splines Exemplos t001pi intsplintsint Ver Também intg integrate inttrap splin 1280 Name linearinterpn interpolação linear ndimensional vp linearinterpnxp1xp2xpn x1 xn v outmode Parâmetros xp1 xp2 xpn vetores de reais ou matrizes de mesmo tamanho x1 x2 xn vetores linhas estritamente crescentes com pelo menos 2 elementos definindo o grid de interpolação ndimensional v vetor caso n1 matriz caso n2 ou hipermatriz caso n 2 com valores da função subjacente interpolada nos pontos do grid outmode opcional string definindo a avaliação fora do grid extrapolação vp vetor ou matriz de mesmo tamanho que xp1 xpn Descrição Dado um grid ndimensional definido pelos n vetores x1 x2 xn e os valores v de uma função aqui nomeada f nos pontos do grid vi1i2in fx1i1x2i2 xnin esta função computa o interpolante linear de f do grid chamado de s a partir daqui nos pontos nos quais as coordenadas são definidas pelos vetores ou matrizes xp1 xp2 xpn vpi sxp1ixp2i xpni or vpij sxp1ijxp2ij xpnij caso xpk sejam matrizes O parâmetro outmode ajusta a regra para extrapolação se notarmos Pixp1ixp2ixpni então outmode define a regra de avaliação quando Pi está fora de x11 x1 x x21 x2 x x xn1 xn As escolhas são byzero uma extrapolação por zero é feita bynan uma extrapolação por NaN C0 a extrapolação é definida como segue linearinterpn 1281 sP sprojP onde projP é o ponto mais próximo de P localizado na fronteira do grid natural a extrapolação é feita usando o remendo nlinear mais próximo do ponto periodic s é estendido por periodicidade Exemplos exemplo 1 interpolação linear 1d x linspace02pi11 y sinx xx linspace2pi4pi400 yy linearinterpnxx x y periodic xbasc plot2dxxyystyle2 plot2dxystyle9 strf000 xtitleInterpolação linear de sinx com 11 pontos de interpolação exemplo 2 interpolação bilinear n 8 x linspace02pin y x z 2sinxsiny xx linspace02pi 40 xpyp ndgridxxxx zp linearinterpnxpyp x y z xbasc plot3dxx xx zp flag2 6 4 xgyg ndgridxx param3d1xgyg listz9ones1n flag0 0 xtitleInterpolação bilinear de 2sinxsiny legendspontos de interpolação91 xselect exemplo 3 interpolação bilinear e experimentação com todos os tipos de outmode nx 20 ny 30 x linspace01nx y linspace02 ny XY ndgridxy z 04cos2piXcospiY nxp 60 nyp 120 xp linspace0515 nxp yp linspace0525 nyp XPYP ndgridxpyp zp1 linearinterpnXP YP x y z natural zp2 linearinterpnXP YP x y z periodic zp3 linearinterpnXP YP x y z C0 zp4 linearinterpnXP YP x y z byzero zp5 linearinterpnXP YP x y z bynan xbasc subplot231 plot3dx y z legxyz flag 2 4 4 xtitlefunção inicial 04 cos2 pi x cospi y linearinterpn 1282 subplot232 plot3dxp yp zp1 legxyz flag 2 4 4 xtitleNatural subplot233 plot3dxp yp zp2 legxyz flag 2 4 4 xtitlePeriodic subplot234 plot3dxp yp zp3 legxyz flag 2 4 4 xtitleC0 subplot235 plot3dxp yp zp4 legxyz flag 2 4 4 xtitlebyzero subplot236 plot3dxp yp zp5 legxyz flag 2 4 4 xtitlebynan xselect exemplo 4 interpolação trilinear ver ajuda de splin3d que tem os mesmos exemplos com interpolação por spline tricúbico execSCIdemosinterpinterpdemosci func vx052 y053 z052 deffvfxyzfunc n 5 x linspace01n yx zx XYZ ndgridxyz V fXYZ computando e exibindo o interpolante linear em algumas fatias m 41 dir z z z x y val 01 05 09 05 05 ebox 0 1 0 1 0 1 XF YF ZF VF for i 1lengthval XmXpYmYpZmZp sliceparallelepipeddiri vali ebox m m m Vm linearinterpnXmYmZm x y z V xfyfzfvf nf3dqXmYmZmVm1 XF XF xf YF YF yf ZF ZF zf VF VF vf Vp linearinterpnXpYpZp x y z V xfyfzfvf nf3dqXpYpZpVp1 XF XF xf YF YF yf ZF ZF zf VF VF vf end nbcol 128 vmin minVF vmax maxVF color dsearchVFlinspacevminvmaxnbcol1 xsetcolormapjetcolormapnbcol xbasc xsethidden3dxgetbackground colorbarvminvmax plot3dXF YF listZFcolor flag1 6 4 xtitleInterpolação trilinear defunc xselect Ver Também interpln splin splin2d splin3d Autor 1284 Name lsqsplin ajuste ponderado por spline cúbico de mínimos quadrados y d lsqsplinxd yd wd x Parâmetros xd yd vetores de mesmo tamanho dados a serem ajustados por um spline cúbico wd opcional um vetor de mesmo formato que xd e yd pesos dos ajustes de mínimos quadrados x vetor linha ou coluna estritamente crescente pontos de interrupção do spline cúbico y d vetores de mesmo formato que x a triplaxyd define o spline cúbico aproximado Descrição Esta função computa um spline cúbico aproximado s para os dados xd yd wd a partir daqui m é suposto como o comprimento desses vetores e de uma escolha dos pontos de interrupção do spline o vetor x por exemplo se você deseja n pontos de interrupção uniformemente escolhidos você pode usar xlinspaceminxdmaxxdn Se S é o espaço de todas as funções spline cúbicas com pontos de interrupção x1 x2 xn então o spline resultante s é tal que m m 2 2 wdk sxdk ydk wdk fxdk ydk k1 k1 para todo f em S ie realiza o mínimo da soma de todos os erros quadrados sobre todas as funções de S O spline s é completamente definido pela tripla xyd y e d são os vetores das ordenadas dos splines e das derivadas primeiras nos xi s yisxi e disxi e sua avaliação em alguns pontos deve ser feita pela função interp Observações Quando wd não é dado todos os pontos têm o mesmo peso 1 Um ponto xdkydk é considerado no ajuste se xdk em x1xn e wdk 0 Em particular você pode colocar um peso nulo ou mesmo negativo a todos os pontos que você deseja que sejam igno rados no ajuste Quando o número total de pontos levados em conta no procedure de ajuste é estri tamente menor que 4 ocorre um erro O vetor xd não necessita estar em ordem crescente Dependendo do número e das posições dos xdk s e da escolha dos xi s podem haver várias soluções mas apenas uma é selecionada Quando isso ocorre um aviso é exibido na janela de comando do Scilab Esta função foi feita para ser usada quando m é muito maior que n e neste caso tal tipo de problema não ocorre lsqsplin 1285 Exemplos este é um exemplo artificial onde os dados xd e yd são contruídos a partir de uma função seno perturbada a 0 b 2pi sigma 01 desvio padrão do ruído gaussiano m 200 número de pontos experimentais xd linspaceabm yd sinxd grandxdnor0sigma n 6 número de pontos de interrupção x linspaceabn computando o spline y d lsqsplinxd yd x usando pesos iguais plotando ye sinxd ys interpxd x y d xbasc plot2dxdye yd ysstyle2 2 3 legfunção exatamedidas experimentais perturbação gaussianaspline ajustado xtitleUm spline de mínimos quadrados xselect Ver Também interp splin Autores C De Boor AH Morris código da biblioteca FORTRAN NSWC B Pincon interface Scilab e ligeiras modificações 1286 Name smooth suavização por funções splines ptsmoothptd step Parâmetros ptd vetor de reais 2xn step real passo de discretização das abscissas pt vetor de reais 2xn Descrição Esta função computa a interpolação por funções splines para um dado conjunto de pontos no plano As coordenadas são ptd1iptd2i Os componentes ptd1 devem estar em ordem crescente O valor padrão para o para step é absmaxiptd1miniptd1100 Exemplos x1 10 20 30 40 y1 30 10 20 40 plot2dxy3011 10405050 yismoothxy01 plot2dyi1yi21000 Ver Também splin interp interpln 1287 Name splin interpolação por spline cúbico d splinx y splinetype der Parâmetros x um vetor linha ou coluna estritamente crescente x deve ter pelo menos dois componentes y um vetor com o mesmo formato que x splinetype opcional um string selecionando o tipo de spline a ser computado der optional um vetor com dois componentes com as derivadas nas extremidades a ser fornecido quando splinetypeclamped d vetor com o mesmo formato que x di é a derivada do spline em xi Descrição Esta função computa o spline cúbico ou subspline s que interpola os pontos xiyi ie temos sxiyi para todo i1n O spline resultante s é completamente definido pela tripla xyd onde d é o vetor com as derivadas nos xi sxidi esta forma é chamada de forma de Hermite ou hermitiana A avaliação do spline em alguns pontos deve ser feita pela função interp Vários tipos de splines podem ser computados selecionando o parâmetro splinetype apropriado notaknot este é o caso padrão o spline cúbico é computado sob as seguintes condições considerando n pontos x1xn sx2 sx2 sxn1 sxn1 clamped neste caso o spline cúbico é computado usando derivadas nas extremidades do intervalo que devem ser fornecidas como último argumento der sx1 der1 sxn der2 natural o spline cúbico é computado sob as seguintes condições sx1 0 sxn 0 periodic um spline cúbico periódico é computado y deve verificar y1yn sob as seguintes condições splin 1288 sx1 sxn sx1 sxn monotone neste caso um subspline s é apenas uma vez continuamente diferenciável é computado usando um esquema local para os di tais que s é monótono em cada intervalo if yi yi1 s é crescente em xi xi1 if yi yi1 s é decrescente em xi xi1 fast neste caso um subspline também é computado usando um esquema local simples para os di di é a derivada em xi da interpolação polinomial xi1yi1 xiyixi1yi1 exceto pelas extremidades d1 sendo computado a partir dos 3 pontos mais à esquerda e dn dos 3 pontos mais à direita fastperiodic é o mesmo que o anterior mas também usa uma fórmula centrada para d1 sx1 dn sxn através da periodicidade da função subjacente y deve verificar y1yn Observações De um ponto de vista de precisão use essencialmente o tipo clamped se você conhece as derivadas nas extremidades de outro modo use notaknot Mas se a função subjacente aproximada é periódica use o tipo periodic Sob boas suposições estes tipos de spline têm um comportamento assintótico Oh4 do erro Não use o tipo natural a não ser que a função subjacente possua zero derivadas segundas nas extremidades Os tipos monotone fast ou fastperiodic podem ser úteis e alguns caso por exemplo para limitar oscilações estes tipos de subsplines têm um comportamento assintótico Oh3 do erro Se n2 e splinetype não é clamped é usada interpolação linear Se n3 e splinetype é notaknot então um subspline tipo fast é computado na verdade Exemplos exemplo 1 deffyrungexy1 1 x2 a 5 b 5 n 11 m 400 x linspacea b n y rungex d splinx y xx linspacea b m yyi interpxx x y d yye rungexx xbasc plot2dxx yyi yye style2 5 leginterpolação porfunção exata plot2dx y 9 xtitleIntepolação da função de Runge exemplo 2 mostra comportamento de splines diferentes em dados aleatórios a 0 b 1 intervalo de interpolação n 10 número de pontos de interpolação splin 1289 m 800 discretização para avaliação x linspaceabn abscissas dos pontos de interpolação y randx ordenadas dos pontos de interpolação xx linspaceabm yk interpxx x y splinxynotaknot yf interpxx x y splinxyfast ym interpxx x y splinxymonotone xbasc plot2dxx yf ym yk style5 2 3 strf121 legfastmonotonespline not a knot plot2dxy9 strf000 para mostrar pontos de interpolação xtitleVários splines e subsplines em dados aleatórios xselect Ver Também interp lsqsplin Autores B Pincon F N Fritsch rotina pchimf Slatec é usada para interpolação monótona 1290 Name splin2d interpolação por spline bicúbico em grides 2d C splin2dx y z splinetype Parâmetros xy vetores linhas estritamente crescentes com pelo menos dois componentes definindo o grid de interpolação z nmatriz nx x ny nx sendo o comprimento de x e ny o comprimento de y splinetype opcional um string selecionando o tipo de spline bicúbico a ser computado C um vetor grande com coeficientes dos elementos de área bicúbicos veja detalhes em Observações Descrição Esta função computa um spline ou subspline bicúbico s que interpola os pontos xiyjzij ie temos sxiyjzij para todo i1nx e j1ny O spline resultante s é definido pela tripla xyC onde C é o vetor com comprimento 16nx1ny1 com os coeficientes de cada um dos nx1ny1 elementos de área bicúbicos em xi xi1xyj yj1 s é definido por 4 4 k1 l1 sxy C kl x xi y yj ij k1 l1 A avaliação de s em alguns pontos deve ser feita pela função interp2d Vários tipos de splines podem ser computados selecionando o parâmetro splinetype apropriado O método usada para com putar os splines ou subspline bicúbicos é o mesmo do antigo ie computar em cada ponto do grid xiyj uma aproximação das derivadas primeiras dsdxxiyj e dsdyxiyj e das derivadas cruzadas d2sdxdyxiyj Estas derivadas são computadas pelo modo dos esquemas do spline 1d levando a uma função de classe C2 s é duas vezes continuamente diferenciável ou através de um esquema de aproximação local levando a uma função de classe C1 apenas Este esquema é selecionado através do parâmetro splinetype ver splin para detalhes notaknot é o caso padrão periodic usado se a função subjacente é periódica devese ter z1j znxj para todo j em 1ny e zi1 ziny para i em 1nx mas isto não é verificado pela interface Observações De um ponto de vista de precisão use essencialmente o tipo notaknot ou periodic se a função interpolada subjacente é periódica splin2d 1291 Os tipos natural monotone fast ou fastperiodic podem ser úteis em alguns casos por exemplo para limitar oscilações monotone é o mais poderoso para isso Para obter coeficientes dos remendos bicúbicos de um modo mais amigável você pode usar c hypermat44nx1ny1C então o coeficiente kl do remendo ij ver equação aqui antes é armazenado em cklij Não obstante a função interp2d espera pelo vetor grande C e não pela hipermatriz c note que se pode recuperar facilmente C de c com Cc Exemplos exemplo 1 interpolação de cosxcosy n 7 um grid regular com n x n pontos de interpolação será usado x linspace02pin y x z cosxcosy C splin2dx y z periodic m 50 parâmetro de discretização do grid de avaliação xx linspace02pim yy xx XXYY ndgridxxyy zz interp2dXXYY x y C emax maxabszz cosxxcosyy xbasc plot3dxx yy zz flag2 4 4 XY ndgridxy param3d1XYlistz9ones1n flag0 0 str msprintf com d x d pontos de interpolação ermax gnnemax xtitleInterpolação por spline de cosxcosystr exemplo 2 diferentes funções de interpolação em dados aleatórios n 6 x linspace01n y x z randnn np 50 xp linspace01np yp xp XP YP ndgridxpyp ZP1 interp2dXP YP x y splin2dx y z notaknot ZP2 linearinterpnXP YP x y z ZP3 interp2dXP YP x y splin2dx y z natural ZP4 interp2dXP YP x y splin2dx y z monotone xsetcolormap jetcolormap64 xbasc subplot221 plot3d1xp yp ZP1 flag2 2 4 xtitlenotaknot subplot222 plot3d1xp yp ZP2 flag2 2 4 xtitlebilinear interpolation subplot223 plot3d1xp yp ZP3 flag2 2 4 xtitlenatural subplot224 plot3d1xp yp ZP4 flag2 2 4 xtitlemonotone xselect exemplo 3 spline notaknot e subspline monotone em uma função de degraus splin2d 1292 a 0 b 1 c 025 d 075 criando grid de interpolação n 11 x linspaceabn ind findc lt x amp x lt d z zerosnn zindind 1 um degrau dentro de um quadrado criando grid de avaliação np 220 xp linspaceab np XP YP ndgridxp xp zp1 interp2dXP YP x x splin2dxxz zp2 interp2dXP YP x x splin2dxxzmonotone plot xbasc xsetcolormapjetcolormap128 subplot121 plot3d1xp xp zp1 flag2 6 4 xtitlespline notaknot subplot122 plot3d1xp xp zp2 flag2 6 4 xtitlesubspline monotone Ver Também cshep2d linearinterpn interp2d Autor B Pincon 1293 Name splin3d interpolação spline em grides 3d tl splin3dx y z v order Parâmetros xyz vetores linhas estritamente crescentes cada um com pelo menos três componentes definindo o grid de interpolação 3d v uma hipermatriz nx x ny x nz nx ny nz sendo de comprimentos de x y e z respectivamente order opcional um vetor 1x3 kxkykz dada a ordem do tensor spline em cada direção o padrão é 444 ie spline tricúbico tl um tlist do tipo splin3d definindo o spline Descrição Esta função computa um spline tensor 3d s que interpola os pontos xiyjzkvijk ie temos sxiyjzkvijk para todo i1nx j1ny e k1nz O spline resultante s é definido por tl que consiste em uma representação Btensorspline de s A avaliação de s em alguns pontos deve ser feita pela função interp3d para computar s e suas derivadas primeiras ou pela função bsplin3val para computar uma derivada arbitrária de s Vários tipos de splines podem ser computados selecionando a ordem dos splines em cada direção orderkxkykz Observação Esta função funciona sob as condições nx ny nz 3 2 kx nx 2 ky ny 2 kz nz Há erro quando estas condições não são respeitadas Exemplos exemplo 1 func vcos2pixsin2piycos2piz deffvfxyzfunc n 10 n x n x n pontos de interpolação x linspace01n yx zx grid de interpolação XYZ ndgridxyz V fXYZ tl splin3dxyzV5 5 5 splin3d 1294 m 10000 computando um erro aproximado xp grandm1def yp grandm1def zp grandm1def vpexact fxpypzp vpinterp interp3dxpypzp tl er maxabsvpexact vpinterp tente agora com n20 e veja o erro exemplo 2 veja a página de ajuda de linearinterpn que contém o mesmo exemplo com interpolação trilinear execSCImodulesinterpolationdemosinterpdemosci func vx052 y053 z052 deffvfxyzfunc n 5 x linspace01n yx zx XYZ ndgridxyz V fXYZ tl splin3dxyzV computando e exibindo o spline interpolante 3d em algumas fatias m 41 dir z z z x y val 01 05 09 05 05 ebox 0 1 0 1 0 1 XF YF ZF VF for i 1lengthval XmXpYmYpZmZp sliceparallelepipeddiri vali ebox m m m Vm interp3dXmYmZm tl xfyfzfvf nf3dqXmYmZmVm1 XF XF xf YF YF yf ZF ZF zf VF VF vf Vp interp3dXpYpZp tl xfyfzfvf nf3dqXpYpZpVp1 XF XF xf YF YF yf ZF ZF zf VF VF vf end nbcol 128 vmin minVF vmax maxVF color dsearchVFlinspacevminvmaxnbcol1 xsetcolormapjetcolormapnbcol xbasc xsethidden3dxgetbackground colorbarvminvmax plot3dXF YF listZFcolor flag1 6 4 xtitleinterpolação por spline 3d da função func xselect Ver Também linearinterpn interp3d bsplin3val Autores RF Boisvert C De Boor código da biblioteca FORTRAN CMLIB B Pincon interface Scilab Parte XIX Funções de EntradaSaída 1296 Name file Gerenciamento de arquivos unit errfileopen filename status access recl format fileactionunit units typ nams mod swap fileunit Parâmetros filename string nome o arquivo a ser aberto status string o status do arquivo a ser aberto new o arquivo não deve existir novo arquivo padrão old o arquivo já deve existir unknown status desconhecido scratch o arquivo deve ser deletado ao fim da sessão access string o tipo de acesso ao arquivo sequential acesso seqüencial padrão direct acesso direto format string formatted para um arquivo formatado padrão unformatted registro binário recl inteiro é o tamanho de registros quando accessdirect unit inteiro descritor de unidade lógica do arquivo aberto units vetor de inteiros descritores de unidades lógicas dos arquivos abertos As unidades 5 e 6 são reservadas pelo sistema para dispositivos de entrada e saída typs vetor de strings tipo C ou Fortran dos arquivos abertos nams vetor de strings endereços dos arquivos abertos file 1297 mod modo de abertura de arquivo Formado por três dígitos abc Arquivos Fortran a 0 significa formatado e 1 não formatado binário b 0 significa acesso sequencial e 1 acesso direto c 0 significa new 1 significa old 2 significa scratch e 3 significa unknown Arquivos C a 1 significa r leitura 2 significa w escrita e 3 significa a anexação b é 1 se o arquivo foi aberto pelo modo atualização c é 1 se o arquivo foi aberto pelo modo b binário swap alavanca de troca automática swap1 se a troca automática estiver ativada swap é sempre 0 para arquivos Fortran err inteiro número de mensagem de erro ver error se a abertura falha Se err for omitido uma mensagem de erro aparece action é um dos seguintes strings close fecha os arquivos fornecidos pelos descritores de unidades lógicas fornecidos em units rewind coloca o ponteiro no início do arquivo backspace coloca o ponteiro no início do último registro last coloca o ponteiro após o último registro Descrição Seleciona uma unidade lógica unit e gerencia o arquivo filename unit errfileopen filename status access re clformat permite abrir um arquivo com propriedades especificadas e obter o número de unidade associado unit Este número de unidade pode ser utilizado para ações futuras no arquivo ou como descritor de arquivo em chamadas às funções read write readb writbsave load fileactionunit permite fechar o arquivo ou mover o ponteiro do arquivo corrente file retorna os descritores de unidades lógicas dos arquivos abertos So fileclosefile fecha todos os arquivos do usuário abertos tipo C ou Fortran file 1298 Exemplos ufileopenTMPDIRfoounknown for k14 arand14 writeua end filerewindu xreadu24 filecloseu u1fileopenTMPDIRfoounknown u2mopenTMPDIRfoo1wb unitstypsnamsfile filecloseu1 mcloseu2 Ver Também save load write read writb readb uigetfile mopen mclose 1299 Name getenv retorna o valor de uma variável de ambiente envgetenvstr rep Parâmetros str string especificando o nome da variável de ambiente rep um string opcional Quando este valor opcional é usado a função getenv retorna o valor rep quando a variável de ambiente str não é encontrada env string que contém o valor da variável de ambiente Descrição Retorna o valor de uma variável de ambiente se existir Exemplos getenvSCI getenvFOOfoo 1300 Name getio retorno de unidades lógicas de entradasaída do Scilab iosgetio Parâmetros ios um vetor rio rte wio wte rio unidade lógica corrente para leitura de instruções rte unidade lógica designada para entrada na janela do Scilab wio unidade lógica relativa ao arquivo de diário se houer wio0 significa que nenhum arquivo de diário foi aberto wte unidade lógica designada para saída na janela do Scilab Descrição getio retorna unidades lógicas designadas para entrada e saída principais no Scilab Ver Também file exec 1301 Name getpid Retorna o identificador do processo Scilab idgetpid Descrição Retorna retorna um inteiro correspondente ao identificador do processo Scilab Exemplos dSDstringgetpid 1302 Name getscilabkeywords retorna uma lista com todas as palavraschave do Scilab listkeywordsgetscilabkeywords Parâmetros listkeywords uma lista Descrição listkeywords1 primitivas listkeywords2 comandos listkeywords3 variáveis predefinidas listkeywords4 funções Scilab listkeywords5 funções Scicos Autores AC adaptado do código de Enrico Segres no Scipad 1303 Name halt para execução halt halta message Descrição Para execução até a entrada de algo no teclado Exemplos haltPress a key halt Ver Também pause return exec 1304 Name host execução de comandos do Unix ou DOS stathostcommandname Parâmetros commandname um string contendo uma instrução sh Unix stat um flag indicador inteiro Descrição Envia um string commandname para o Unix para execução pelo interpretador de comando sh em Unix ou commandcom em DOS As saídas e os erros padrões do comando do shell são escritos no shell chamado stat fornece 1 se o host significa anfitrião não pode ser chamado memória disponível do sistema insuficiente ou se o interpretador de comando retorna o código Exemplos criando uma função getdir baseda no host function wdgetdir if MSDOS then hostcdTMPDIRpath else hostpwdTMPDIRpath end wdreadTMPDIRpath11a endfunction chamandoa wdgetdir Ver Também edit manedit unixg unixs unixw unixx 1305 Name input prompt para entrada do usuário x inputmessage string Parâmetros message string string string string pode ser abreviado para s x número real ou string se string estiver na seqüência de chamamento Descrição inputmessage fornece ao usuário o prompt no string de texto e então espera por entrada no teclado A entrada pode ser a expressão avaliada por evstr Se apenas um retornodecarro for fornecido no prompt inputmessage retorna uma matriz vazia Chamado com dois argumentos a saída é um string que é a expressão fornecida pelo teclado Se apenas um retorno de carro for fornecido inputmessage retorna um único espaço em branco Exemplos xinputQuantas iterações xinputQual o seu nomestring Ver Também evstr xdialog xmdialog 1306 Name load carrega variável salva loadfilename x1xn loadfd x1xn Parâmetros filename string contendo o endereço do arquivo fd descritor de arquivo fornecido por uma chamada a mopen xi nomes de variáveis Scilab arbitrárias fornecidos como strings Descrição O comando load pode ser utilizado para recarregar no Scilab variáveis de sessão previamente gravadas com o comando save Se o arquivo contém variáveis correspondentes a manipuladores gráficos as graphicsentities entidades gráficas correspondentes são desenhados Desde o Scilab 50 todos os manipuladores uimenu ou uicontrol também são desenhados loadfilename carrega variáveis no arquivo dado pelo endereço filename loadfd carrega variáveis no arquivo fornecido pelo seu descritor fd loadfilenamexy ou loadfdxy carrega apenas as variáveis xy Mesmo que o formato de arquivo binário tenha mudado na versão 25 loadfilename é capaz de ler formatos antigos Formatos antigos podem ser acessados por enquanto utilizando as funções oldsave e oldload Exemplos aeye22bonesa savevalsdatab clear a clear b loadvalsdatab Ver Também save listvarinfile saveformat exec mopen 1307 Name oldload carrega variáveis salvas em formato 241 e anteriores oldloadfilename x1xn Parâmetros filename string xi nomes de variáveleis arbitrárias do Scilab fornecidos como strings Descrição A função oldload está obsoleta e esta sendo retida apenas para propósitos de compatibilidade O comando oldload pode ser usado para recarregar no Scilab variáveis de sessão previamente salvas em um arquivo através do comando save oldloadfilename carrega as variáveis em um arquivo salvo filename oldloadfilenamexyz carrega apenas variáveis xyz ar mazenadas no arquivo filename Exemplos aeye22bonesa oldsaveTMPDIRvalsdatab clear a clear b oldloadTMPDIRvalsdatab Ver Também save exec 1308 Name oldsave gravação de variáveis em formato 241 e anteriores oldsavefilename x1x2xn Parâmetros filename string ou unidade lógica retornada por fileopen xi variávelis Scilab arbtrárias Descrição A função oldsave está obsoleta e retida apenas por compatibilidade O comando oldsave pode ser usado para salvar variáveis Scilab correntes em forma binária num arquivo oldsavefilename salva todas as variáveis correntes no arquivo definido por filename oldsavefilenamexy salva apenas as variáveis nomeadas x e y Variáveis salvas podem ser recarregadas através dos comandos load ou oldload Exemplos aeye22bonesa oldsaveTMPDIRvaldatab clear a clear b oldloadTMPDIRvaldatab Ver Também load file 1309 Name read Leitura de matrizes xreadfiledescmnformat xreadfiledescmnkformat Parâmetros filedesc string especificando o nome do arquivo ou valor inteiro especificando uma unidade lógica ver file m n inteiros dimensões da matriz x Ajuste m1 se você desconhece o número de linhas para que todo o arquivo seja lido format string especifica um formato Fortran Este string deve começar com um parêntese direito e terminar com um parêntese esquerdo Formatos não podem misturar pontos flutuantes inteiros ou modo de edição de caractere k inteiro ou vetor de inteiros Descrição Lê linha após linha a matriz x mxn n1 para cadeia de caracteres no arquivo filedesc string ou inteiro Cada linha da matriz x começa em uma nova linha do arquivo filedesc Dependendo de format uma dada linha da matriz x pode ser lida de mais de uma linha do arquivo filedesc O tipo do resultado dependerá do formato especificado Se format contém apenas os descritores defg a função tenta ler dados numéricos o resultado é uma matriz de números reais Se format contém apenas o descritor a a função tenta ler strings o resultado é um vetor coluna de strings Neste caso n deve ser igual a 1 Aviso Os strings serão truncados se tiverem tamanho maior que 4093 Exemplos para format 1xe1035x3f30 10xa20 Quando format é o omitido os dados são lidos utilizandose o formato numérico livre espaços em branco vírgulas e barras podem ser utilizados como separadores de dados nv pode ser utilizado para representar n ocorrências do valor n Um arquivo de acesso direto pode ser utilzado na presença de um parâmetro k que é um vetor de números de gravações a serem lidas uma gravação por linha logo m deve ser mprodsizek Para ler no teclado use readio1 Observação A última linha de cada arquivo de dados devemser terminada por uma nova linha newline a ser levada em conta read 1310 Exemplos if MSDOS then unixdel foo else unixrm f foo end Arand35 writefooA Breadfoo35 Breadfoo15 readio111a espera por entrada do usuário Ver Também file readb write xdialog mscanf mfscanf msscanf fscanfMat 1311 Name read4b leitura de arquivo FORTRAN binário xread4bfilenamemn rec Parâmetros filename string ou inteiro m n inteiros dimensões da matriz x Ajuste m1 se você não sabe o número de linhas então todo o arquivo será lido rec vetor de inteiros positivos os registros selecionados para acesso direto O tamanho desejado deve ter o mesmo tamanho de x desejado Descrição Leitura binária da matriz x no arquivo filename Supõese que as entradas da matriz foram ar mazenadas em palavras de quatro bytes Para acesso a registros direto o arquivo deve ter sido previamente aberto com a função file para se ajustar o comprimento do registro filename deve ser o resultado da função file Ver Também file write writb mget write4b 1312 Name readb leitura de arquivo FORTRAN binário xreadbfilenamemn rec Parâmetros filename string ou inteiro m n inteiros dimensões da matriz x Ajuste m1 se o número de linhas não for conhecido então todo arquivo será lido rec vetor de inteiros positivos os registros selecionados para acesso direto O tamanho deste vetor deve ser igual ao número de linhas de x desejado Descrição Leitura binária da matriz x no arquivo filename Supõese que as entradas da matriz tenham sido armazenadas em palavras de 8 bytes Para acesso direto a registros o arquivo deve ter sido aberto previamente com a função file para ajustar o comprimento de registro filename deve ser o resultado da função file Ver Também file write writb mget read4b 1313 Name readc lê um string creadcunit creadc Descrição readc lê um string Esta função permite interromper um arquivo exec sem pause o arquivo exec pára até que seja dado um retorno de carro Ver Também read 1314 Name save salvando variáveis em arquivos binários savefilename x1x2xn savefd x1x2xn Parâmetros filename string contendo o endereço do arquivo fd descritor do arquivo fornecido por uma chamada a mopen xi variávelis Scilab arbitrárias Descrição O comando save pode ser usado para salvar as variáveis Scilab correntes em um arquivo Se uma variável é um manipulador gráfico a função save salva todas as definições de graphicsentities entidades gráficas correspondentes Desde o Scilab 50 todos os manipuladores de uimenu ou uicontrol também são gravados por esta função O arquivo pode ser fornecido tanto pelo seu endereço quanto por seu descritor dado previamente por mopen savefilename salva todas as variáveis correntes definidas por filename savefd salva todas as variáveis correntes definidas pelo descritor fd savefilenamexy ou savefdxy salva apenas as variáveis chamadas x e y Variáveis salvas podem ser recarregadas através do comando load Exemplos aeye22bonesa savevaldatab clear a clear b loadvaldatab gravação seqüêncial em um arquivo fdmopenTMPDIRfoowb for k14 xk2savefdxkend mclosefd fdmopenTMPDIRfoorb for i14 loadfdxkxkend mclosefd anexando variáveis a um arquivo gravado antigo fdmopenTMPDIRfoor mseek0fdend save 1315 lstlist123 savefdlst mclosefd Ver Também load saveformat mopen 1316 Name setenv ajusta o valor de uma variável de ambiente repsetenvname value Parâmetros name aponta para o nome de uma variável de ambiente name é um string value aponta para o valor a ser atribuído à variável de ambiente value é um string rep Retorna T se estiver tudo correto ou F em caso contrário Descrição Ajusta o valor de uma variável de ambiente Exemplos setenvtotoexample getenvtoto Ver Também getenv Autor Allan CORNET 1317 Name unix execução de comando shell sh statunixcommandname Parâmetros commandname string contendo uma instrução Unix sh stat flag inteiro Descrição Envia um string commandname ao Unix para execução com o shell sh Saída e erros padrões do shell de comando são escritos no shell chamado stat retorna 1 se o Unix não pode ser chamado memória do sistema disponível insuficiente ou o código de retorno sh Exemplos if MSDOS then unixls SCIdemos end function wddirectory if MSDOS then unixcdgtTMPDIRpath else unixpwdgtTMPDIRpath end wdreadTMPDIRpath11a endfunction wddirectory Ver Também edit manedit unixg unixs unixw unixx host 1318 Name unixg execução de um comando shell sh saída redirecionada a uma variável repunixgcmd repstatunixgcmd repstatstderrunixgcmd Parâmetros cmd string rep vetor coluna de strings saída padrão stat inteiro o status de erro stat0 se nenhum erro tiver ocorrido err vetor coluna de strings erro padrão Descrição Envia um string cmd ao Unix para execução pelo comando shell sh A saída padrão é redirecionada para a variável Scilab rep O erro padrão é redirecionado à variável Scilab err ou é exibido se você forneceu apenas dois argumentos de saída Erros de execução Unix são detectados Note que apenas o último erro de comando shell é reportado quando uma lista de comandos separados por é enviada Isto não é recomentdado Exemplos function dDIRpath pathpathconvertpathtt if MSDOS then dunixgdir path else dunixgls path end endfunction DIRSCIetc Ver Também unixs unixw unixx unix 1319 Name unixs execução do comando shell sh sem saída unixscmd Parâmetros cmd string Descrição Envia um string cmd ao Unix para execução pelo shell sh A saída padrão é redirecionada para devnull Erros de execução Unix são detectados Note que apenas o último erro de comando shell é reportado quando uma lista de comandos separados por é enviada isto não é recomendado Exemplos if MSDOS then unixsdel foo else unixsrm f foo end Ver Também edit manedit unixg unixw unixx unix 1320 Name unixw execução de comando shell sh saída redirecionada à janela do Scilab unixwcmd Parâmetros cmd string Descrição Envia um string cmd ao Unix para execução com o comando shell sh A saída é redirecionada à janela do Scilab Erros de execução Unix são detectados Note que apenas o último erro de comando shell é reportado quando uma lista de comandos separados por é enviada isto não é recomandado Exemplos if MSDOS then unixwdir WSCImodules else unixwls SCImodules end Ver Também edit manedit unixg unixs unixx unix 1321 Name unixx execução do comando shell sh saída redirecionada a uma janela unixxcmd Parâmetros cmd string Descrição Envia um string cmd ao Unix para uma execução através do shel sh A saída padrão é redirecionada a uma janela Erros de execução Unix são detectados Note que apenas o último erro de comando de shell é reportado quando uma lista de comandos separados por é enviada Isto não é recomendado Exemplos if MSDOS then unixxdir WSCImodulesgraphicsdemos else unixxls SCImodulesgraphicsdemos end Ver Também edit manedit unixg unixs unixw unix 1322 Name writb escrita binária de arquivo FORTRAN writbfilenamea rec Parâmetros filename string ou inteiro rec vetor de inteiros positivos os registros selecionados para acesso direto O tamanho deste vetor deve ser igual ao número de linhas de a Descrição Escreve em formato binário a matriz a no arquivo filename As entradas da matriz são ar mazenadas em palavras de quatro bytes Para registro de acesso direto o arquivo deve ter sido previamente aberto através da função file para se ajustar o comprimento do registro filename deve ser o resultado da função file Ver Também file readb write mput write4b 1323 Name write Escrita em arquivo formatado writefiledescaformat writefiledescakformat Parâmetros filedesc string especificando o nome do arquivo ou valor inteiro especificando a unidade lógica ver file a matriz de reais ou vetor coluna de strings format string especifica um formato Fortran Este string deve começar com um parêntese direito e terminar com um parêntese esquerdo Formatos não podem misturar pontos flutuantes inteiros ou modo de edição de caractere k integer vector Descrição Escreve linha por linha uma matriz de reais ou um vetor coluna de strings em um arquivo formatado Cada linha do argumento a começa em uma nova linha do arquivo filedesc Dependendo de format uma dada linha do argumento a pode ser escrita em mais de uma linha do arquivo file desc Exemplos de formatos 1xe1035x3f30 10xa20 Veja um livro de Fortran para maior precisão Arquivos de acesso direto xwritefiledescakformat Aqui k é o vetor de gravações uma gravação por linha ie mprodsizek writeio2 escreve em uma janela do Scilab Note que neste caso format deve pro duzir uma linha de saída por linha da matriz Se esta restrição não for respeitada um erro imprevisível acontece Exemplos if MSDOS then unixdel asave else unixrm f asave end Arand53 writeasaveA Areadasave53 writeio2A 3f103 writeio2string110 writeio2strcatstring110 writeio211010i23x if MSDOS then unixdel foo else unixrm f foo end writefooA Ver Também file fileinfo writb read print string mfprintf mprintf msprintf fprintfMat 1324 Name write4b escrita binária de arquivo FORTRAN write4bfilenamea rec Parâmetros filename string ou inteiro rec vetor de inteiros positivos os registros selecionados para acesso direto O tamanho deste vetor deve ter o mesmo número de linhas que a Descrição Escreve em formato binário a matriz a no arquivo filename As entradas da matriz são ar mazenadas em palavras de 8 bytes Para acesso direto o arquivo deve ter sido previamente aberto através da função file para se ajustar o comprimento do registro filename deve ser o resultado da função file Ver Também file readb write mput read4b Parte XX Funções de Saída 1326 Name disp exibição de variáveis dispx1x2xn Descrição Exibe xi com o formato corrente xis são objetos arbitrários matrizes de constantes strings funções listas A exibição de objetos definidos por tlists pode ser sobrecarregada pela definição de uma função Esta função não deve ter argumento de saída um único argumento de entrada e seu nome deve ser formado como segue tlisttypep onde tlisttype é a primeira entrada do com ponente de tipo tlist A função lines pode ser usada para controlar a saída Exemplos disp1 23 defftpldispl3l2 disptlistt12 Ver Também lines write read print string tlist 1327 Name print imprime variáveis em um arquivo printfilenamex1x2xn Descrição Imprime xi no arquivo filename com o formato corrente ie o formato utilizado pelo Scilab para exibir variáveis Todos os tipos de variáveis podem ser impressos Note que xi deve ser uma variável nomeada Com expressões a exibição da parte do nome da variável é imprevisível printio2 imprime na janela do Scilab Esta sintaxe pode ser utilizada para exibir variáveis dentro de um macro Exemplos arand33ppoly123sllist1asdf1 2 3 printio2apl writeio2a Ver Também write read format printf disp 1328 Name printf emulador da função da linguagem C printf printfformatvalue1valuen Parâmetros format string Scilab especifica um string combinando caracteres literais com especificações de conversão valuei especifica os dados a serem convertidos de acordo com o parâmetro de formato str vetor coluna de strings file string Scilab especificando um arquivo ou um número de unidade lógica ver file Descrição A função printf converte formata e escreve seus parâmetros value sob controle do parâmetro format para a saída padrão O parâmetro format é um string que contém dois tipos de objetos Caracteres literais que são copiados no fluxo de saída Especificações de conversão cada um dos quais faz com que zero ou mais itens sejam buscados da lista de parâmetros value Ver printfconversion para detalhes Se algum item de values sobrar após todo o format ter sido processado ele é ignorado Exemplos printfO resultado é alphaf0535 Ver Também string print write format disp file fprintf sprintf printfconversion 1329 Name printfconversion Especificações de conversão de printf sprintf fprintf Descrição Cada especificação de conversão no parâmetro format de printf sprintf fprintf possui a seguinte sintaxe Um sinal porcento Zero ou mais options opções que modificam o significado da especificação de conversão A lista seguinte contem os caracteres option e seus significados Alinhe à esquerda dentro do campo o resultado da conversão Comece o resultado de uma conversão com sinal com um sinal ou Prefixe um caractere de espaço ao resultado se o primeiro caractere de uma conversão com sinal não for um sinal Se ambas as opções espaço e aparecerem a opção space é ignorada Converta o valor para uma forma alternativa Para as conversões c d i s e u a opção não possui efeito Para a conversão o aumenta a precisão para forçar o primeiro dígito do resultado a ser 0 zero Para as conversões x e X um valor nãonulo possui 0x ou 0X prefixado a ele Para as conversões e E f g e G o resultado sempre contém ponto decimal Mesmo que nenhum dígito o siga Para as conversões g e G zeros por último não são removidos Aumente a largura do campo utilizando zeros à esquerda seguindo qualquer indicação de sinal ou base para as conversões d i o u x X e E f g e G nenhum aumento de espaço é realizado Se ambos os indicadores 0 e barra aparecerem o indicador 0 é ignorado Para as conversões d i o u x e X se uma precisão for especificada o indicador 0 também é ignorado Um string de dígitos decimais opcional que especifica a largura mínima do campo Se o valor conver tido tiver menos caracteres que a largura do campo o campo é aumentado à esquerda até o compri mento especificado pela largura do campo Se a opção de ajuste à esquerda for especificada o campo é aumentado pela direita Uma precisão opcional A precisão é um ponto seguido por um string de dígito decimal Se nen huma precisão for fornecida o parâmetro é tratado como 0 zero A precisão especifica O número mínimo de dígitos a aparecerem nas conversões d u o x ou X O número de dígitos a aparecerem após o ponto decimal nas conversões e E e f O número máximo de dígitos significativos para as conversões g e G O número máximo de caracteres a serem impressos a partir de um string em uma convesão s O caractere que indica o tipo de conversão a ser aplicada Não realiza conversão Exibe Aceita um valor inteiro e o converte para notação decimal com sinal A precisão especifica o número mínimo de dígitos a aparecer Se o valor sendo convertido puder ser representado em menos dígitos ele é expandido com zeros à esquerda A precisão padrão é 1 O resultado de se converter um valor zero com uma precisão de zero é um string nulo A especificação de uma largura de campo com zero como caractere mais à esquerda faz com que o valor da largura do campo seja preenchido com zeros à esquerda Aceita um valor inteiro e o converte para a notação decimal sem sinal A precisão especifica o número mínimo de dígitos a aparecer Se o valor sendo convertido puder ser representado em menos printfconversion 1330 dígitos ele é expandido com zeros à esquerda A precisão padrão é 1 O resultado de se converter um valor zero com uma precisão de zero é um string nulo A especificação de uma largura de campo com zero como caractere mais à esquerda faz com que o valor da largura do campo seja preenchido com zeros à esquerda Aceita um valor inteiro e o converte para a sua notação octal sem sinal A precisão especifica o número mínimo de dígitos a aparecer Se o valor sendo convertido puder ser representado em menos dígitos ele é expandido com zeros à esquerda A precisão padrão é 1 O resultado de se converter um valor zero com uma precisão de zero é um string nulo A especificação de uma largura de campo com zero como caractere mais à esquerda faz com que o valor da largura do campo seja preenchido com zeros à esquerda Não é implicado um valor octal para a largura do campo Aceita um valor inteiro e o converte para a sua notação hexadecimal sem sinal As letras abcdef são utilizadas para a conversão x as letras ABCDEF são utilizadas para a conversão X A precisão especifica o número mínimo de dígitos a aparecer Se o valor sendo convertido puder ser represen tado em menos dígitos ele é expandido com zeros à esquerda A precisão padrão é 1 O resultado de se converter um valor zero com uma precisão de zero é um string nulo A especificação de uma largura de campo com zero como caractere mais à esquerda faz com que o valor da largura do campo seja preenchido com zeros à esquerda Aceita um valor float ou double e o converte para a sua notação decimal no formato dddddd O número de dígitos após o ponto decimal é igual à especificação de precisão Se nenhuma precisão for especificada a saída possui seis dígitos Se a precisão for zero nenhum ponto decimal aparece e o sistema imprime na saída o valor inteiro mais próximo de value Se a saída possui um ponto decimal pelo menos um dígito é posto antes dele Aceita um real e o converte para a sua forma exponencial ddddedd Há um dígito antes do ponto decimal e o número de dígitos após o ponto decimal é igual à especificação de precisão Se nenhuma precisão for especificada a saída são seis dígitos Se a precisão for zero nenhum ponto decimal aparece A caractere de conversão E produz um número com o caractere E ao invés de e antes do expoente O expoente sempre contém pelo menos dois dígitos Se o valor for zero o expoente é zero Aceita um real e o converte no estilo dos caracteres de conversão e E ou f com a precisão es pecificando o número de dígitos significativos Zeros por último são removidos Um ponto decimal aparece apenas se for seguido de um dígito O estilo depende do valor convertido O resultado é o estilo e E se G é o indicador utilizado apenas se o expoente resultante da conversão for menor do que 4 ou se for maior do que ou igual à precisão Aceita e exibe um valor inteiro convertido em um caractere Aceita um valor string e exibe caracteres do string até o fim ou até que o número de caracteres indicados pela precisão seja alcançado Se nenhuma precisão for especificada todos os caracteres até o fim são exibidos Uma largura de campo ou uma precisão podem ser indicadas por asterísco ao invés de um string de dígito Neste caso um parâmetro de valor inteiro provê a largura do campo ou a precisão O parâmetro de valor convertido para saída não é buscado até que a letra de conversão seja alcançada então os parâmetros especificando o comprimento de campo ou precisão devem aparecer antes do valor a ser convertido se houver algum Se o resultado da conversão for maior que a largura do campo o campo é expandido para conter o resultado convertido printfconversion 1331 A representação do sinal de mais depende da opção de formatação especificada se ou espaço Ver Também printf fprintf sprintf 1332 Name sprintf emulador da função da linguagem C sprintf strsprintfformatvalue1valuen Parâmetros format string Scilab especifica um string combinando caracteres literais com especificações de conversão valuei especifica os dados a serem convertidos de acordo com o parâmetro de formato str vetor coluna de strings Descrição A função sprintf converte formata e escreve seus parâmetros value sob controle do parâmetro format para a saída padrão O parâmetro format é um string que contém dois tipos de objetos Literal characters que são copiados no fluxo de saída Conversion specifications cada um dos quais faz com que zero ou mais itens sejam buscados da lista de parâmetros value parameter list Ver printfconversion para detalhes Se não há itens suficientes para format na lista de parâmetros value sprintf gera um erro Se algum valor de value sobrar após todo format ter sido processado ele é ignorado Nota sprintf é obsoleto use msprintf ao invés Exemplos fahr120 sprintf3d Fahrenheit 61f Celsiusfahr59fahr32 Ver Também string print write format disp file printf fprintf msprintf printfconversion 1333 Name ssprint embelezador de sistemas lineares ssprintsl out Parâmetros sl lista lista syslin out saída valor padrão outio2 Descrição Representação embelezada de uma sistema linear em lista syslin de forma de espaço de estados slABCD Exemplos a1 10 1b0 11 0c11d32 ssprintsyslincabcd ssprintsyslindabcd Ver Também texprint 1334 Name diary diary of session diaryfilename idfilename diaryfilename newappend ids filenames diary ids filenames diary list diary close diary0 diaryfilename close diaryid close diary pauseoff diaryfilename pauseoff diaryid pauseoff diary resumeon diaryfilename resumeon diaryid resumeon diaryfilenames exists diaryids exists diaryfilename newappend prefixYYYYMMDD hhmmss diaryfilename newappend prefixU diaryfilename newappend prefixYYYYMMDD hhmmss prefixonlycommands Parameters filename a character string give the full file name path id a scalar to identify a diary Description diaryffunction creates a log of keyboard input and the resulting text output Start a diary session id filename diaryfilename newappend returns id a positive integer 1 which is the diary session identifier filename A string the absolute path of the effective written file The first input argument is a string that contain the path of the diary file This can be a relative path or a absolute path The 2nd input argument controls if a new file is created new or if diary adds new content at the end of the file append If the 2nd input argument is not present the default value is new diary 1335 When diary is called with new mode If filename already exists and is not empty an effective filename basefilemaneextensionfilename is built used and returned by diaryfilename as a second output argument beside id The rank would be set as the smallest integer for which the resultant filename does not yet exists List diary sessions ids filenames diary ids filenames diarylist returns a column vector of integer identifiers list of opened diary sessions a column vector of strings absolute paths of the files associated with opened diary sessions Close diary sessions diaryclose diary0 diaryfilenameclose diaryidclose The first and second syntaxes close all opened diary sessions The third syntax closes diary sessions identified by filename The fourth syntax closes the diary session identified by id which is a positive integer or a vector of positive integers Remark diary0 is retained as backwards compatibility PauseResume diary sessions diary pauseoff diaryfilenamepauseoff diaryid pauseoff The first syntax suspends all opened diary sessions The second syntax suspend diary sessions identified by filename filename can be a single string or a character string array The third syntax suspend the diary session identified by id which is a positive integer or a vector of positive integers diary resumeon diaryfilenameresumeon diaryid resumeon The first syntax resume all opened diary sessions The second syntax resume diary sessions identified by filename filename can be a single string or a character string array diary 1336 The third syntax resume the diary session identified by id which is a positive integer or a vector of positive integers Does a diary session exists diaryfilenameexists diaryidexists return true if a diary session is currently opened with the file filename if not false Diary and timestamp diaryfilenamenewprefixYYYYMMDD hhmmss diaryfilenamenewprefixU diaryfilenamenew prefixYYYYMMDD hhmmss prefixon lycommands prefixYYYYMMDD hhmmss add date hour prefixU add UNIX time epoch prefixonlycommands add timestamp only as prefix for commands Filtering diary diaryfilenamenewfiltercommand Log only the input commands diaryfilenamenewfilteroutput Log only the text output Examples d1 diaryTMPDIR diary1txt d2 diaryTMPDIR diary2txt some Scilab instructions cd TMPDIR dir returns infos about opened diary ids filenames diary close diary d1 diaryd1close ids filenames diary close diary d2 diaryTMPDIR diary2txt ids filenames diary closes all diary diaryclose ids filenames diary 1337 Name mprintf converts formats and writes data to the main scilab window mprintfformata1an Parameters format a Scilab string describing the format to use to write the remaining operands The format operand follows as close as possible the C printf format operand syntax a1an Specifies the data to be converted and printed according to the format parameter Description The mprintf function is a interface for Ccoded version of printf function The mprintf function writes formatted operands to the standard Scilab output ie the Scilab win dow The argument operands are formatted under control of the format operand Examples mprintfAt iteration i Result is alphaf330535 See Also disp 1338 Name msprintf converts formats and writes data in a string strmsprintfformata1an Parameters format a Scilab string describing the format to use to write the remaining operands str a character string a1an Specifies the data to be converted and printed according to the format parameter Description The msprintf writes formatted operands in its returned value a Scilab string The argument operands are formatted under control of the format operand Note that in this case the escape sequences split string to a matrix of string see example Examples msprintf53f 53f1230732 msprintf53f 53f1230732 msprintfs dhello3 See Also mprintf printfconversion 1339 Name prettyprint From any Scilab datatype and provide a representation to the TeX LaTeX or MathML formats str prettyprinta Show the variable a with the default format LaTeX str prettyprintaexportFormat Show the variable a a with the specified format str prettyprintaexportFormat delim As above but change the delimiter str prettyprintaexportFormat delim processByElement As above but process each element independently str prettyprintaexportFormat delim processByElement isWrapped As above Add the special keyword of Tex or LaTeX export Parameters a is a Scilab variable exportFormat is the format if omitted latex is used by default it can be latex tex or mathml delimiter is a string indicating the delimiter to use for the resulting matrix its only used if isWrapped is true The delimiter can be or processByElement is a boolean to indicate if the resulting matrix must be converted into a single string isWrapped is a boolean to indicate if the result must be wrapped inside delimiters for latex and tex or nothing for mathml to be used with xstring or xtitle str the representation of the variable a Description Taking a variable the prettyprint function will provide a formated representation of it Formats can be TeX LaTeX or MathML They can be used in third party applications but also within Scilab with the most of the Scilab graphic features The following types are handled by this function Real Complex matrices Polynomial types Boolean Integer String Tlist Rationnal Cell Examples prettyprint 1340 str prettyprintrand33 Return the LaTeX representation of a 33 matrix xstring0202str Show the representation in a graphic Windows prettyprintrand34mathml Return the MathML representation of a 34 matrix prettyprintrand34mathml Return the MathML representation of a 34 matrix with as delimiter spoly0s G1s1s23s3 xstring0202prettyprintGs1 Show a polynom through a LaTeX representation See also mathrenderingfeaturesingraphic xtitle axesproperties labelproperties legendproperties textproperties xstringb xstringl xstring Authors Calixte Denizet Parte XXI Intersci 1342 Name intersci scilab tool to interface C of Fortran functions with scilab Description All scilab primitive functions are defined in a set of interface routines For each function the interfacing code checks first number of rhs and lhs arguments Then it get pointers on input arguments in the Scilab data base and checks their types After that it calls procedure associated with Scilab functions checks returned errors flags and set the results in the data base intersci is a program which permits to interface automatically FORTRAN subroutines or C func tions to Scilab With intersci a user can group all his FORTRAN or C code into a same set called an interface and use them in Scilab as Scilab functions The interfacing is made by creating a FORTRAN subroutine which has to be linked to Scilab together with the user code This complex FORTRAN subroutine is automatically generated by intersci from a description file of the interface Refer to intersci documentation for more details See Also fort external addinter Parte XXII JVM 1344 Name javaclasspath set and get dynamic Java class path resjavaclasspath javaclasspathpath Parameters res a string matrix Description set and get the dynamic Java path to one or more directory or file specifications given in path Examples resjavaclasspath javaclasspathSCI javaclasspathSCISCIjava Authors AC 1345 Name javalibrarypath set and get dynamic javalibrarypath resjavalibrarypath javalibrarypathpath Parameters res a string matrix Description set and get the dynamic Java Library path to one or more directory given in path When you use java classes with native methods you need to define path where is dynamic library Examples resjavalibrarypath javalibrarypathSCI javalibrarypathSCISCIlibs See Also javaclasspath Authors AC 1346 Name jrepath returns Java Runtime Environment used by Scilab pjrepath Parameters p a string path of JRE Description returns Java Runtime Environment used by Scilab See Also systemgetproperty Authors AC 1347 Name systemgetproperty gets the system property indicated by a specified key ressystemgetpropertykey Parameters res a string value key a string Description gets the system property indicated by a specified key javaversion Java Runtime Environment version javavendor Java Runtime Environment vendor javavendorurl Java vendor URL javahome Java installation directory javavmspecificationversion Java Virtual Machine specification version javavmspecificationvendor Java Virtual Machine specification vendor javavmspecificationname Java Virtual Machine specification name javavmversion Java Virtual Machine implementation version javavmvendor Java Virtual Machine implementation vendor javavmname Java Virtual Machine implementation name javaspecificationversion Java Runtime Environment specification version javaspecificationvendor Java Runtime Environment specification vendor javaspecificationname Java Runtime Environment specification name javaclassversion Java class format version number javaclasspath Java class path javalibrarypath List of paths to search when loading libraries javaiotmpdir Default temp file path javacompiler Name of JIT compiler to use javaextdirs Path of extension directory or directories osname Operating system name osarch Operating system architecture osversion Operating system version fileseparator File separator on UNIX pathseparator Path separator on UNIX lineseparator Line separator on UNIX username Users account name userhome Users home directory userdir Users current working directory systemgetproperty 1348 Examples systemgetpropertyawttoolkit systemgetpropertyfileencoding systemgetpropertyfileencodingpkg systemgetpropertyjavaawtgraphicsenvsunawtWin32GraphicsEnvironment systemgetpropertyjavaawtprinterjobsunawtwindowsWPrinterJob systemgetpropertyjavaclasspath systemgetpropertyjavaclassversion systemgetpropertyjavaendorseddirs systemgetpropertyjavaextdirs systemgetpropertyjavahome systemgetpropertyjavaiotmpdir systemgetpropertyjavalibrarypath systemgetpropertyjavaruntimename systemgetpropertyjavaruntimeversion systemgetpropertyjavaspecificationname systemgetpropertyjavaspecificationvendor systemgetpropertyjavaspecificationversion systemgetpropertyjavavendor systemgetpropertyjavavendorurl systemgetpropertyjavavendorurlbug systemgetpropertyjavaversion systemgetpropertyjavavminfo systemgetpropertyjavavmname systemgetpropertyjavavmspecificationname systemgetpropertyjavavmspecificationvendor systemgetpropertyjavavmspecificationversion systemgetpropertyjavavmvendor systemgetpropertyjavavmversion systemgetpropertylineseparator systemgetpropertyosarch systemgetpropertyosname systemgetpropertyosversion systemgetpropertypathseparator systemgetpropertysunarchdatamodel systemgetpropertysunbootclasspath systemgetpropertysunbootlibrarypath systemgetpropertysuncpuendian systemgetpropertysuncpuisalist systemgetpropertysundesktop systemgetpropertysuniounicodeencoding systemgetpropertysunjnuencoding systemgetpropertysunmanagementcompiler systemgetpropertysunospatchlevel systemgetpropertyusercountry systemgetpropertyuserdir systemgetpropertyuserhome systemgetpropertyuserlanguage systemgetpropertyusername systemgetpropertyusertimezone systemgetpropertyuservariant Authors AC 1350 Name systemsetproperty set a system property indicated by a specified key and value prev systemsetpropertykeyvalue Parameters prev a string previous value or key a string value a string Description Sets the system property indicated by the specified key Warning change property with precaution Examples systemgetpropertymyproperty systemsetpropertymypropertyhello systemgetpropertymyproperty Authors AC 1351 Name withembeddedjre checks if scilab uses a embedded JRE reswithembeddedjre Parameters res a boolean Description checks if scilab uses a embedded JRE Examples reswithembeddedjre Authors AC Parte XXIII Álgebra Linear 1353 Name aff2ab Conversão de uma função linear afim para forma Ab Abaff2abafunctiondimXD flag Parâmetros afunction uma função do Scilab Y fctXD onde X D Y são lists de matrizes dimX uma matriz de inteiros p x 2 p é o número de matrizes em X D uma list de matrizes de reais ou qualquer outro objeto Scilab válido flag parâmetro opcional flagf ou flagsp A uma matriz de reais b um vetor de reais tendo a mesma dimensão de linha que A Descrição aff2ab retorna a representação matricial de uma função afim na base canônica afunction é uma função com sintaxe imposta YafunctionXD onde XlistX1X2Xp é uma lista de p matrizes de reais e YlistY1Yq é uma lista de q matrizes reais que dependem linearmente das Xis A entrada opcional D contém parâmetros necessários para computar Y como uma função de X geralmente é uma lista de matrizes dimX é uma matriz p x 2 dimXinrinci é o número real de linhas e colunas da matriz Xi Estas dimensões determinam na a dimensão de coluna da matriz resultante A nanr1nc1 nrpncp Se o parâmetro opcional flagsp a matriz resultante A é retornada como uma esparsa Esta função é útil para resolver um sistema de equações lineares onde as incógnitas são matrizes Exemplos solucionador de equação de Lyapunov uma incógnita uma restrição deffYlyapunovXDAQDXmX YlistAXmXmAQ Arand33Qrand33QQQDlistAQdimX33 Alyblyaff2ablyapunovdimXD XlkerAlinsolveAlybly Xvvec2listXldimX lyapunovXvD XmXv AXmXmAQ solucionador de equação de Lyapunov com restrição redundante XX uma variável uma restrição D é variável global deffYly2XDAQDXmX YlistAXmXmAQXmXm Arand33Qrand33QQQDlistAQdimX33 Alyblyaff2ably2dimXD aff2ab 1354 XlkerAlinsolveAlybly Xvvec2listXldimX ly2XvD equações de Francis Achando matrizes X1 e X2 tais que A1X1 X1A2 BX2 A3 0 D1X1 D2 0 deffYbruceXDA1A2A3BD1D2D X1X2XYlistA1X1X1A2BX2A3D1X1D2 A141012A312B01A21D101D21 DlistA1A2A3BD1D2 n1m1sizeA1n2m2sizeA2n3m3sizeB dimXm1n2m3m2 Afbfaff2abbrucedimXD XfKerAflinsolveAfbfXsolvec2listXfdimX bruceXsolD Achando todas as X que comutam com A deffyfXDylistDXXD Arand33dimX33Afbfaff2abfdimXlistA XfKerAflinsolveAfbfpqsizeKerAf Xsolvec2listXfKerAfrandq1dimX CXsol ACCA Ver Também linsolve 1355 Name balanc balanceamento de uma matriz ou de um feixe de matrizes AbXbalancA EbAbXYbalancEA Parâmetros A matriz quadrada de reais X matriz quadrada de reais invertível E matriz quadrada de reais com mesma dimensão que A Y uma matriz quadrada de reais invertível Descrição Balanceia uma matriz quadrada para melhorar seu número de condicionamento AbX balancA acha uma transformação de similaridade X tal que Ab invXAX tem aproximadamente normas iguais de linha e de coluna Para feixes de matrizes o balancemento é feito para melhorar o problema do autovalor generalizado EbAbXY balancEA retorna transformações esquerda e direita X e Y tais que EbinvXEY AbinvXAY Observação O balanceamento é feito nas funções bdiag e spec Exemplos A12101210210210 AbXbalancA normA1normA2 normAb1normAb2 Ver Também bdiag spec schur 1356 Name bdiag diagonalização em blocos autovetores generalizados Ab X bsbdiagA rmax Parâmetros A matriz quadrada de reais ou complexos rmax número real Ab matriz quadrada de reais ou complexos X matriz de reais ou complexos nãosingular bs vetor de inteiros Descrição Ab X bsbdiagA rmax realiza a diagonalização em blocos da matriz A bs fornece a estrutura dos blocos respectivos tamanhos dos blocos X é a matriz mudança de base ie Ab invXAX é diagonal em blocos rmax controla o condicionamento de X o valor padrão é a norma L1 de A Para encontrar a forma diagonal se existir escolha um valor suficientemente grande para rmax rmax1eps por exemplo Genericamente para uma matriz A de reais aleatória os blocos são 1x1 e 2x2 e X é a matriz de autovetores Exemplos No caso de reais blocos 1x1 e 2x2 arand55abxbsbdiagaab No caso de complexos blocos 1x1 complexos abxbsbdiagai0ab Ver Também schur sylv spec 1357 Name chfact fatoração esparsa de Cholesky spchochfactA Parâmetros A uma matriz simétrica positiva e esparsa spcho lista contendo os fatores de Cholesky em forma codificada Descrição spchochfactA computa os fatores esparsos de Cholesky da matriz esparsa A assumida simétrica e positiva definida A função é baseada nos programas NgPeyton ORNL Ver os progra mas FORTRAN para uma completa descrição das variáveis em spcho Esta função deve ser usada com a função chsolve Ver Também chsolve sparse lufact luget spchol 1358 Name chol Cholesky factorization RcholX Parâmetros X uma matriz simétrica e positiva definida de reais ou complexos Descrição Se X é positiva definida então R cholX produz uma matriz triangular superior R tal que RR X cholX usa apenas a diagonal e o triângulo superior de X O triângulo inferior é assumido como sendo a transposta ou complexo conjugado da superior Referências A decomposição de Cholesky é baseada nas rotinas de Lapack DPOTRF para matrizes de reais e ZPOTRF no caso de matrizes de complexos Exemplos Wrand55irand55 XWW RcholX normRRX Ver Também spchol qr svd bdiag fullrf 1359 Name chsolve solucionador esparso de Cholesky solchsolvespchorhs Parâmetros spcho lista contendo os fatores de Cholesky na forma codificada retornados por chfact rhs sol vetores colunas cheios Descrição solchsolvespchorhs computa a solução de rhsAsol com A uma matriz simétrica e positiva definida Esta função é baseada nos programas NgPeyton ORNL Veja os programas FORTRAN para uma descrição completa das variáveis em spcho Exemplos Asprand202001 AAAeye spchochfactA sol120rhsAsol spchochfactA chsolvespchorhs Ver Também chfact sparse lufact luget spchol 1360 Name classmarkov classes transientes e recorrentes da matriz de Markov permrectrindsRecindsTclassmarkovM Parâmetros M matriz de Markov N x N de reais A soma das entradas em cada linha deve ser acrescida em uma unidade perm vetor de permutação de inteiros rec tr vetor de inteiros número número de estados em cada classe recorrente número de estados tran sientes indsRecindsT vetor de inteiros índices dos estados recorrentes e transientes Descrição Retorna um vetor de permutação perm tal que Mpermperm M11 0 0 0 0 0 0 M22 0 0 0 0 0 M33 0 0 0 Mrr 0 Q Cada Mii é uma matriz de Markov de dimensão reci i1r Q é uma submatriz de Markov de dimensão tr Estados de 1 a sumrec são recorrentes e estados de r1 a n são transientes Tem se permindsRecindsT onde indsRec é um vetor de tamanho sumrec e indsT é um vetor de tamanho tr Exemplos P tem 2 classes recorrentes com 2 e 1 estados e 2 estados transientes Pgenmarkov212perm permrectrindsRecindsTclassmarkovP Ppermperm Ver Também genmarkov eigenmarkov 1361 Name cmblin combinação linear simbólica xcmblinalfaxbetay Descrição Avalia alfaxbetay alfa beta x y são strings rotina de baixonível Ver também mulf addf 1362 Name coff resolvente método do cofator NdcoffM var Parâmetros M matriz quadrada de reais var string N matriz de polinômios com o mesmo tamanho que M d polinômio polinômio característico polyAs Descrição coff computa RseyeM1 para M uma matriz de reais R é dado por Nd N matriz de polinômios como numerador d denominador comum var string s se omitido Exemplos M1203 NdcoffM Nd invseyeM Ver Também coffg ss2tf nlev poly 1363 Name colcomp compressão de colunas núcleo WrkcolcompA flag tol Parâmetros A matriz de reais ou complexos flag string tol número real W matriz quadrada nãosingular mudança de base rk inteiro posto de A Descrição Compressão de colunas de A Ac AW é de colunas comprimidas ie Ac0Af com o postocoluna de Af cheio postoAf postoA rk flag e tol são parâmetros opcionais flag qr ou svd o padrão é svd tol parâmetro de tolerância de ordem eps como valor padrão As mark primeiras colunas de W geram o núcleo de A quando sizeAnama Exemplos Arand52rand25 XrcolcompA normAX1r1 Ver Também rowcomp fullrf fullrfk kernel Autor FD 1364 Name companion matriz companheira Acompanionp Parâmetros p polinômio ou vetor de polinômios A matriz quadrada Descrição Retorna uma matriz quadrada A com o polinômio característico igual a p se p é mônico Se p não é mônico o polinômio característico de A é igual a pc onde c é o coeficiente do termo de maior grau em p Se p é um vetor de polinômios mônicos A é diagonal em blocos e o polinômio característico do i ésimo bloco é pi Exemplos spoly0s ppoly12341sc detseyecompanionp rootsp speccompanionp Ver Também spec poly randpencil Autor FD 1365 Name cond número de condicionamento de uma matriz condX Parâmetros X rmatriz quadrada de reais ou complexos Descrição Número de condicionamento em norma2 condX é a razão entre o maior e o menor valor singular de X Exemplos Atestmatrixhilb6 condA Ver Também rcond svd 1366 Name det determinante detX emdetX Parâmetros X matriz quadrada de reais ou complexos matriz de polinômios ou de razões de polinômios m número real ou complexo a mantissa de base 10 do determinante e inteiro o expoente de base 10 do determinante Descrição detX m10e é o determinante da matriz quadrada X Para uma matriz de polinômios detX é equivalente a determX Para matrizes de razões de polinômios detX é equivalente a detrX Referências As computações da função det são baseadas nas rotinas do LAPACK DGETRF para matrizes de reais e ZGETRF para o caso de matrizes de complexos Exemplos xpoly0x detx1x2xx2 wssrand224rootsdetsystmatwtrzerosw zeros do sistema linear Arand33 detA prodspecA Ver Também detr determ 1367 Name eigenmarkov Autovetores esquerdo e direito normalizados de Markov MQeigenmarkovP Parâmetros P matriz de Markov N x N de reais A soma das entradas de cada linha deve ser acrescida de uma unidade M matriz de reais de N colunas Q matriz de reais de N linhas Descrição Retorna os autovetores esquerdo e direito normalizados associados ao autovalor 1 da matriz P de transição de Markov Se a multiplicidade deste autovalor é m e P é N x N M é uma matriz m x N e Q é uma matriz N x m Mk é o vetor de distribuição de probabilidade associado ao késimo conjunto ergódico classe recorrente Mkx é zero se x não está na késima classe recorrente Qxk é a probabilidade de se terminar na késima classe recorrente começando de x Se Pk converge para k sem autovalores no círculo unitário exceto 1 então o limite é QM autoprojeção Exemplos P tem duas classes recorrentes com 2 e 1 estados e 2 estados transientes Pgenmarkov212 MQeigenmarkovP PQQ QMP20 Ver Também genmarkov classmarkov 1368 Name ereduc computa de forma escada de colunas da matriz por transformações qz EQZ stair rkereducXtol Parâmetros X matriz m x n de entradas reais tol escalar real positivo E matriz em forma escada de colunas Q matriz unitária m x m Z matriz unitária n x n stair vetor de índices ISTAIRi j se o elemento da borda Eij é uma quina ISTAIRi j se o elemento da borda Eij não é uma quina i1M rk inteiro posto estimado da matriz Descrição Dada uma matriz X m x n não necessariamente regular a função ereduc calcula a matriz unitária transformada EQXZ que está na forma escada de colunas forma trapezoidal Ainda o posto da matriz X é determinado Exemplos X1 2 34 5 6 EQZ stair rkereducX1d15 Ver Também fstair Autores ThGJ Beelen Philips Glass Eindhoven SLICOT 1369 Name expm exponencial de matriz quadrada matriz exponencial expmX Parâmetros X square matrix with real or complex entries Descrição X é uma matriz quadrada e expmX é a matriz expmX I X X2 2 A computação é realizada primeiro diagonalizando em blocos a matriz X e em seguida aplicando uma aproximação de Pade em cada bloco Exemplos X1 23 4 expmX logmexpmX Ver Também logm bdiag coff log exp 1370 Name fstair computa a forma escada de feixe de colunas por transformações qz AEEEQEZEblcksmuknukmuk0nuk0mneifstairAEQZstairrktol Parâmetros A matriz m x n com entradas reais tol escalar real positivo E matriz de forma escada de colunas Q matriz unitária m x m Z matriz unitária n x n stair vetor de índices ver ereduc rk inteiro posto estimado da matriz AE matriz m x n com entradas reais EE matriz de forma escada de colunas QE matriz unitária m x m ZE matriz unitária n x n nblcks é o número de submatrizes com posto linha completo 0 detectado na matriz A muk array vetor ou matriz de inteiros de dimensão n Contém as dimensões de coluna muk k1nblcks das submatrizes com posto coluna cheio no feixe sEepsAeps nuk array de inteiros de dimensão m1 Contém as dimensões de linha nuk k1nblcks das submatrizes com posto linha cheio no feixe sEepsAeps muk0 array de inteiros de dimensão n Contém as dimensões de coluna muk k1nblcks das submatrizes com o postocoluna cheio no feixe sEepsinfAepsinf nuk array de inteiros de dimensão m1 Contém as dimensões de linha nuk k1nblcks das submatrizes com postolinha cheio no feixe sEepsinfAepsinf fstair 1371 mnei array de inteiros dimensão 4 mnei1 dimensão de linha de sEepsAeps Descrição Dado o feixe sEA onde a matriz E está na forma escada de colunas a função fstair computa de acordo com as necessidades do usuário um feixe unitário transformado QEsEEAEZE que é mais ou menos similar à forma generalizada de Schur do feixe sEA A função também produz parte da estrutura de Kronecker para um dado feixe QZ são as matrizes unitárias usadas para computar o feixe onde E está na forma escada de colunas ver ereduc Ver Também quaskro ereduc Autor ThGJ Beelen Philips Glass Eindhoven SLICOT 1372 Name fullrf fatoração de posto completo ou cheio QMrkfullrfAtol Parâmetros A matriz de reais ou complexos tol número real limiar para determinação do posto QM matriz de reais ou complexos rk inteiroposto de A Descrição Fatoração de posto cheio fullrf retorna Q e M tais que A QM com ImQImA e NucMNucA Q de postocoluna cheio M de postolinha cheio e rk rankA columnsQ rowsM tol é um parâmetro real opcional valor real padrão é sqrteps O posto rk de A é definido como o número de valores singulares maiores que normAtol Se A é simétrica fullrf retorna MQ Exemplos Arand52rand25 QMfullrfA normQMA1 XdrowcompAYX svdAY1dQ spanQ spanA spanY12 span gerado Ver Também svd qr fullrfk rowcomp colcomp Autor FD 1373 Name fullrfk fatoração de posto completo de Ak BkCkfullrfkAk Parâmetros A matriz de reais ou de complexos k inteiro BkCk matrizes de reais ou de complexos Descrição Esta função calcula a fatoração de posto completo ou cheio de Ak ie BkCkAk onde Bk é de postocoluna cheio e Ck de postolinha cheio Temse ImBkImAk e NucCkNucAk Para k1 fullrfk é equivalente a fullrf Exemplos Arand52rand25BkCkfullrfkA3 normBkCkA31 Ver Também fullrf range Autor FD 1990 1374 Name genmarkov gera uma matriz de Markov aleatória com classes recorrentes e transientes Mgenmarkovrectr Mgenmarkovrectrflag Parâmetros rec vetor linha de inteiros sua dimensão é o número de classes recorrentes tr inteiro número de estados transientes M matriz de Markov de reais A soma das entradas de cada linha deve ser acrecsida de uma unidade flag string perm Se fornecido uma permutação dos estados é feita Descrição Retorna em M uma matriz de probabilidade de transição de Markov aleatória com rec1rec entradas respectivamente e tr estados transientes Exemplos P tem duas classes recorrentes com 2 e 1 states e 2 estados transientes Pgenmarkov212perm permrectrindsRecindsTclassmarkovP Ppermperm Ver Também classmarkov eigenmarkov 1375 Name givens transformação de Givens Ugivensxy Ugivensxy Ucgivensxy Ucgivensxy Parâmetros xy dois números reais ou complexos xy vetor coluna de reais ou complexos de tamanho 2 U matriz 2x2 unitária c vetor coluna de reais ou complexos de tamanho 2 Descrição U givensx y ou U givensxy com xy xy retorna uma matriz unitária 2x2 U tal que Uxyr0c Note que givensxy e givensxy são equivalentes Exemplos A3456 UgivensA1 UA Ver Também qr 1376 Name glever inverso do feixe de matrizes BfsBischisgleverEA s Parâmetros E A duas matrizes de reais quadradas de igual dimensão s string o valor padrão é s BfsBis duas matrizes de polinômios chis polinômio Descrição Computação de sEA1 pelo algoritmo generalizado de Leverrier para um feixe de matrizes sEA1 Bfschis Bis chis polinômio característico até uma constante multiplicativa Bfs nmatriz de polinômios como numerador Bis matriz de polinômios expansão de sEA1 ao infinito Note o sinal antes de Bis Cuidado Esta função usa cleanp para simplificar BfsBis e chis Exemplos ssF1s00010000s20000s1 BfsBischisgleverF invFBfschis Bis Ver Também rowshuff det invr coffg pencan penlaur Autor F D 1988 1377 Name gschur forma de Schur generalizada função obsoleta AsEsgschurAE AsEsQZgschurAE AsEsZdim gschurAEflag AsEsZdim gschurAEextern Descrição Esta função é obsoleta e agora está inclusa na função schur function Na maior parte dos casos a função gschur irá ainda trabalhar como antes mas será removida em um lançamento futuro do Scilab As três sintaxes podem ser substituídas por AsEsschurAE AsEsQZschurAEQQ NOTE A TRANSPOSIÇÃO AQUI AsEsZdim schurAEflag A última sintaxe requer algumas adaptações a mais if é uma função do Scilab a nova seqüência de chamamento deve ser AsEsZdim schurAENextern com Nextern definido como segue function tNexternR if R20 then textern1R1R31 else cR1iR2R3 textern2realccrealcc1 end endfunction if é o nome de uma função externa codificada em FORTRAN ou C a nova seqüência de chamamento deve ser AsEsZdim schurAEnextern com nextern definido como segue logical function nexternaraibeta double precision araibeta integer rextern if aieq00d0 then rextern1arbeta00d000d0 else rextern200d000d020d0arararaiai endif nexternreq1 end Ver Também external schur 1378 Name gspec autovalores de feixe de matrizes função obsoleta albegspecAE albeZgspecAE Descrição Esta função está agora inclusa na função spec A seqüência de chamamento deve ser substituida por albespecAE albeZspecAE Ver Também spec 1379 Name hess forma de Hessenberg H hessA UH hessA Parâmetros A matriz quadrada de reais ou complexos H matriz quadrada de reais ou complexos U matriz quadrada ortogonal ou unitária Descrição UH hessA produz uma matriz unitária U e uma matriz de Hessenberg H tais que A UHU e UU Identidade Por si só hessA retorna H A forma de Hessenberg de uma matriz é zero abaixo da primeira subdiagonal Se a matriz é simetrica ou Hermitiana a forma é tridiagonal Referências A função hess é baseada nas rotinas Lapack DGEHRD DORGHR para matrizes de e ZGEHRD ZORGHR para matrizes de complexos Exemplos Arand33UHhessA and absUHUA1d10 Ver Também qr contr schur 1380 Name householder matriz de reflexão ortogonal de Householder uhouseholderv w Parâmetros v vetor coluna de reais ou complexos w vetor coluna de reais ou complexos com o mesmo tamanho que v Valor padrão é eyev u vetor coluna de reais ou complexos Descrição Dados dois vetores coluna v w de mesmo tamanho householdervw retorna um vetor coluna unitário u tal que eye2uuv é proporcional a w eye2uu é a matriz de reflexão ortogonal de Householder O valor padrão de w é eyev Neste caso o vetor eye2uuv é o vetor eyevnormv Ver Também qr givens 1381 Name iminv imagem inversa XdimiminvAB tol XdimYiminvAB tol Parâmetros AB duas matirzes de reais ou complexos com igual número de colunas X matriz quadrada ortogonal ou unitária de ordem igual ao número de colunas de A dim inteiro dimensão do subespaço Y matriz ortogonal de ordem igual ao número de linhas de A e B Descrição XdimiminvAB computaA1B ie vetores cujas imagens através de A estão em ImB As dim primeiras colunas de X geram A1B tol é um limiar usado para testar a inclusão de subespaço o valor padrão é tol 100eps Se Y é retornado então YAXYB é particionado como segue A11A120A22B10 onde B1 tem postolinha cheio igual a postoB e A22 tem postocoluna cheio e tem dim colunas Exemplos Arand25zeros34rand31B1111zeros32 Wrand55AWABWB XdimiminvAB svdAX1dimB vetores AX1dim pertencem a rangeB Imagem de B ImB XdimYiminvABYAXYB Ver Também rowcomp spaninter spanplus linsolve Autor F Delebecque INRIA 1382 Name inv inversa de uma matriz invX Parâmetros X matriz quadrada de reais ou complexos matriz de polinômios matriz de razões de polinômios em representação de transferência ou espaço de estados Descrição invX é a inversa da matriz quadrada X Uma aviso é impresso na tela se X possui má escala ou é quase singular Para matrizes de polinômios ou matrizes razões de polinômios em representação de transferência invX é equivalente a invrX Para sistemas lineares na representação de espaço de estados lista syslin invrX é equivalente a invsyslinX Referências A função inv para matrizes de números é baseada nas rotinas de Lapack DGETRF DGETRI para ma trizes de reais e ZGETRF ZGETRI para o caso de matrizes de complexos Para matrizes de polinômios e matrizes de funções racionais inv é baseado na função invr do Scilab Exemplos Arand33invAA xpoly0x Ax1xx221x123invAA A1x22x21x invAA Assrand223 WinvAA cleanss2tfW Ver Também slash backslash pinv qr lufact lusolve invr coff coffg 1383 Name kernel núcleo de uma matriz WkernelA tolflag Parâmetros A matriz de reais ou complexos completa ou matriz de reais esparsa flag string svd padrão ou qr tol número real W matriz de postocoluna completo Descrição WkernelA retorna o núcleo espaço nulo de A Se A tem postocoluna completo então uma matriz vazia é retornada flag e tol são parâmetros opcionais flag qr ousvd o padrão é svd tol parâmetro de tolerância de ordem eps como valor padrão Exemplos Arand31rand13 AkernelA AsparseA cleanAkernelA Ver Também colcomp fullrf fullrfk linsolve Autor FD 1384 Name kroneck forma de Kronecker de feixe de matrizes QZQdZdnumbepsnumbetakroneckF QZQdZdnumbepsnumbetakroneckEA Parâmetros F feixe de matrizes de reais FsEA EA duas matrizes de reais de mesma dimensão QZ duas matrizes quadradas ortogonais QdZd dois vetores de inteiros numbepsnumeta dois vetores de inteiros Descrição Forma de Kronecker de feixe de matrizes kroneck computa duas matrizes ortogonais Q Z que põem o feixe FsE A na forma triangular superior sEepsAeps X X X O sEinfAinf X X QsEAZ 0 0 sEfAf X 0 0 0 sEetaAeta As dimensões dos quatro blocos são dadas por epsQd1 x Zd1 infQd2 x Zd2 f Qd3 x Zd3 etaQd4xZd4 O bloco inf contém modos infinitos de feixes O bloco f contém modos finitos de feixes A estrutura dos blocos epsilon e eta é dada por numbeps1 de blocos eps de tamanho 0 x 1 numbeps2 de blocos eps de tamanho 1 x 2 numbeps3 de blocos eps de tamanho 2 x 3 etc numbeta1 de blocos eta de tamanho 1 x 0 numbeta2 de blocos eta de tamanho 2 x 1 kroneck 1385 numbeta3 de blocos eta de tamanho 3 x 2 etc O código foi retirado de T Beelen SlicotWGS group Exemplos Frandpencil1122313103 Qrand1717Zrand1818FQFZ feixe aleatório com eps11eps21eps31 2 blocos J infty infinito com dimensões 2 e 3 autovalores finitos em 131 e eta10eta23 QZQdZdnumbepsnumbetakroneckF Qd1Zd1 parte eps é sumepsi x sumepsi número de epsi sumsoma Qd2Zd2 parte infinita Qd3Zd3 parte finita Qd4Zd4 parte eta é sumetai numbereta1 x sumetai numbernúmero numbeps numbeta Ver Também gschur gspec systmat pencan randpencil trzeros 1386 Name linsolve solucionador de equações lineares x0kerAlinsolveAb x0 Parâmetros A uma matriz na x ma de reais possivelmente esparsa b um vetor na x 1 mesma dimensão de linha de A x0 um vetor de reais kerA uma matriz ma x k de reais Descrição linsolve computa todas as soluções para Axb0 x0 é uma solução particular se houver e kerA núcleo de A Qualquer xx0kerAw com w arbitrário satisfaz Axb0 Se um compatible x0 compatível é dado na entrada x0 é retornado Senão um x0 compatível é retornado se houver Exemplos Arand53rand38 bAones81xkerAlinsolveAbAxb b comatível bones51xkerAlinsolveAbAxb b incompatível Arand55xkerAlinsolveAb invAb x é único A benchmark of sparse linear solver Adescrrefmtype ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa b 0onessizeA11 tic res umfpackAb printf time needed to solve the system with umfpack 3f toc tic res linsolveAb printf time needed to solve the system with linsolve 3f toc tic res Ab printf time needed to solve the system with the backslash operator 3f toc linsolve 1387 Ver Também inv pinv colcomp iminv backslash umfpack 1388 Name lsq problemas de mínimos quadrados lineares XlsqAB tol Parâmetros A matriz de reais ou de complexos m x n B matriz de reais ou de complexos m x p tol escalar positivo usado para determinar o posto efetivo de A definido como sendo a ordem da maior submatriz triangular R11 regente na fatoração QR com pivoteamento de A cujo número de condicionamento estimado 1tol O valor padrão de tol é sqrteps X matriz de reais ou complexos n x p Descrição XlsqAB computa a solução de mínimo quadrado de menor norma da equação AXB enquanto XA B computa uma solução de mínimo quadrado com no máximo postoA componentes nãonulos por coluna Referências lsq é baseado nas funções Lapack DGELSY para matrizes de reais e ZGELSY para matrizes de complexos Exemplos Construindo os dados x110 y13x453randxnormal y218x052randxnormal plot2dxy1y223 Achando a regressão linear AxonesxBy1y2 XlsqAB y1eX11xX21 y2eX12xX22 plot2dxy1ey2e23 Diferença entre lsqAb e Ab Arand42rand23uma matriz de posto 2 brand41 X1lsqAb X2Ab AX1b AX2b os resíduos são os mesmos lsq 1389 Ver Também backslash inv pinv rank 1390 Name lu fatores LU de eliminação Gaussiana LU luA LUE luA Parâmetros A matriz de reais ou complexos m x n L matriz de reais ou complexos m x minmn U matriz de reais ou complexos minmn x n E uma matriz de permutação n x n Descrição LU luA produz duas matrizes L e U tais que A LU com U triangular superior e EL triangular infeiror para uma matriz de permutação E Se A tem posto k as linhas de k1 a n de U são zeros LUE luA produz três matrizes L U e E tais que EA LU com U triangular superior e EL l triangular inferior para uma matriz de permutação E Se A é uma matriz de reais usando as funções lufact e luget é possível obter as matrizes de permutação e também quando A não é de posto cheio a compressão de colunas da matriz L Exemplos arand44 lulua normlua hrklufactsparsea função lufact com matrizes esparsas PLUQlugeth ludelh PfullPLfullLUfullUQfullQ normPLUQa P e Q são as matrizes de permutação Ver Também lufact luget lusolve qr svd Função Usada As decomposições de lu são baseadas nas rotinas de Lapack DGETRF para matrizes reais e ZGETRF para o caso de matrizes complexas 1391 Name lyap equação de Lyapunov XlyapACc XlyapACd Parâmetros A C matrizes quadradas de reais C deve ser simétrica Descrição X lyapACflag resolve as equações matriciais de tempo contínuo ou de tempo discreto de Lyapunov AX XA C flagc AXA X C flagd Perceba que existe uma única solução se e só se um autovalor de A não é um autovalor de A flagc ou 1 sobre um autovalor de A flagd Exemplos Arand44CrandACCC XlyapACc AX XA C XlyapACd AXA X C Ver Também sylv ctrgram obsgram 1392 Name nlev algoritmo de Leverrier numdennlevAz rmax Parâmetros A matriz quadrada de reais z string rmax parâmetro opcional ver bdiag Descrição numdennlevAz rmax computa zeyeA1 por diagonalização por blocos de A seguido pelo algoritmo de Leverrier em cada bloco Este algoritmo é melhor que o algoritmo usual de Leverrier mas ainda não está perfeito Exemplos Arand33xpoly0x NUMdennlevAx cleandenpolyAx cleanNUMdeninvxeyeA Ver Também coff coffg glever ss2tf Autores F Delebecque S Steer INRIA 1393 Name orth base ortogonal QorthA Parâmetros A matriz de reais ou complexos Q matriz de reais ou complexos Descrição QorthA retorna Q uma base ortogonal para o gerado de A ImQ ImA e QQeye O número de colunas de Q é o posto de A como determinado pelo algoritmo QR Exemplos Arand53rand34 XdimrowcompAXX svdorthAX1dim Ver Também qr rowcomp colcomp range 1394 Name pbig autoprojeção QMpbigAthresflag Parâmetros A matriz quadrada de reais thres número real flag string c ou d QM matrizes de reais Descrição Projeção sobre um autosubespaço associado aos autovalores de parte real thres flagc ou com magnitude thres flagd A projeção é definida por QM Q tem postocoluna cheio M tem postolinha cheio e MQeye Se flagc os autovalores de MAQ autovalores de A com parte real thres Se flagd os autovalores de MAQ autovalores de A com magnitude thres Se flagc e se Q1M1 fatoração em posto cheio fullrf de eyeQM então os auto valores de M1AQ1 autovalores de A com parte real thres Se flagd e se Q1M1 fatoração em posto cheio fullrf de eyeQM então os auto valores de M1AQ1 autovalores de A com magnitude thres Exemplos Adiag123XrandAAinvXAX QMpbigA15d specMAQ Q1M1fullrfeyeQM specM1AQ1 Ver Também psmall projspec fullrf schur Autor F D 1988 Função Usada pbig é baseada na forma ordenada de Schur função do Scilab schur 1395 Name pencan forma canônica de feixe de matrizes QMi1pencanFs QMi1pencanEA Parâmetros Fs um feixe regular sEA EA duas matrizes quadradas de reais QM duas matrizes nãosingulares de reais i1 inteiro Descrição Dado o feixe regular FssEA pencan retorna as matrizes Q e M tais que MsEAQ está na forma canônica MEQ é uma matriz de blocos I0 0N com N nilpotente e i1 tamanho da matriz acima I MAQ é uma matriz de blocos Ar0 0I Exemplos Frandpencil12123 Frand66Frand66 QMi1pencanF WcleanMFQ rootsdetW1i11i1 detW22 Ver Também glever penlaur rowshuff Autor F D 1396 Name penlaur Laurent coefficients of matrix pencil SiPiDiorderpenlaurFs SiPiDiorderpenlaurEA Parâmetros Fs um feixe regular sEA E A duas matrizes quadradas de reais SiPiDi três matrizes quadradas de reais order inteiro Descrição penlaur computa os primeiros coeficientes de Laurent de sEA1 no infinito sEA1 Sis Pi sDi em s infinito order ordem da singularidade ordemíndice1 O feixe de matrizes FssEA deve ser invertível Para um feixe de índice 0 Pi Di são zero e SiinvE Para um feixe de índice 1 order0Di 0 Para feixes de índices maiores os termos s2 Di2 s3 Di3 são dados por Di2DiADi Di3DiADiADi até Diorder Observação Versão experimental há problemas quando se tem malcondicionamento desoEA Exemplos Frandpencil12123 Frand66Frand66EApen2eaF SiPiDipenlaurF BfsBischisgleverF normcoeffBis1Di1 Ver Também glever pencan rowshuff Autor F Delebecque INRIA19881990 1397 Name pinv pseudoinversa pinvAtol Parâmetros A matriz de reais ou complexos tol número real Descrição X pinvA produz uma matriz X de mesma dimensão que A tal que AXA A XAX X e ambas AX e XA são Hermitianas A computação é baseada em SVD e qualquer valor singular abaixo da tolerância é tratado como zero esta tolerância é acessada por XpinvAtol Exemplos Arand52rand24 normApinvAAA1 Ver Também rank svd qr Função Usada pinv é baseada na decomposição em valores singulares função do Scilab svd 1398 Name polar forma polar RoThetapolarA Parâmetros A matriz quadrada de reais ou complexos Ro matriz de reais Theta matriz de reais ou complexos Descrição RoThetapolarA retorna a forma polar de A ie ARoexpmiThetaRo simétrico 0 e Theta hermitiano 0 Exemplos Arand55 RoThetapolarA normARoexpmiTheta1 Ver Também expm svd Autor F Delebecque INRIA 1399 Name proj projeção P projX1X2 Parâmetros X1X2 duas matrizes reais com igual número de colunas P matriz de projeção de real P2P Descrição P é a projeção sobre X2 paralela a X1 Ver Também X1rand52X2rand53 PprojX1X2 normP2P1 traceP Este é dimX2 QMfullrfP svdQX2 spanQ spanX2 See Also projspec orth fullrf Autor F D 1400 Name projspec operadores espectrais SPDiprojspecA Parâmetros A matriz quadrada S P D matrizes quadradas i inteiro índice do autovalor zero de A Descrição Características espectrais de A em 0 S resolvente reduzido em 0 S InversodeDrazinA P projeção espectral em 0 D operador nilpotente em 0 index índice do autovalor 0 Temse seyeA1 Di1si Ds2 Ps S sS2 ao redor da singularidade s0 Exemplos deffjjdrnnjzerosnnfor k1n1jkk11end Asysdiagjdrn3jdrn2rand22Xrand77 AXAinvX SPDindexprojspecA index tamanho do bloco J traceP soma das dimensões dos blocos J ASeyeP normDindex1 Ver Também coff Autor F D 1401 Name psmall projeção espectral QMpsmallAthresflag Parameters A matriz quadrada de reais thres número real flag string c ou d QM matrizes de reais Description Projeção sobre autosubespaço associado com autovalores com parte real thres flagc ou com módulo thres flagd A projeção é definda por QM Q é de postocoluna cheio M é de postolinha cheio e MQeye Se flagc os autovalores de MAQ autovalores de A com parte real thres Se flagd os autovalores de MAQ autovalores de A com magnitude thres Se flagc e se Q1M1 fatoração em posto cheio fullrf de eyeQMentão os auto valores de M1AQ1 autovalores de A com parte real thres Se flagd e se Q1M1 fatoração em posto cheio fullrf de eyeQM então os auto valores de M1AQ1 autovalores de A com magnitude thres Examples Adiag123XrandAAinvXAX QMpsmallA25d specMAQ Q1M1fullrfeyeQM specM1AQ1 See Also pbig proj projspec Authors F Delebecque INRIA 1988 Used Functions Esta função é baseada na forma de Schur ordenada Função do Scilab schur 1402 Name qr QR decomposição QRqrX e QREqrX e QRrkEqrX tol Parâmetros X matriz de reais ou complexos tol número real nãonegativo Q matriz quadrada ortogonal ou unitária R matriz com as mesmas dimensões de X E matriz de permutação rk inteiro posto QR de X Descrição QR qrX pproduz uma matriz triangular superior R de mesma dimensão que X e uma matriz ortogonal unitária no caso de matriz de complexos Q tais que X QR QR qrXe produz um economia de tamanho Se X é mporn com m n então apenas as primeiras n colunas de Q são computadas assim como as primeiras n linhas de R De QR X segue que a késima coluna da matriz X é expressa como combinação linear das k primeiras colunas de Q com coeficientes R1k Rkk As k primeiras colunas de Q formam uma base ortogonal para o subespaço gerado pelas k priemiras colunas de X Se a coluna k de X ie Xk é uma combinação linear das p primeiras colunas de X então as entradas de Rp1k Rkk são zeros Neste caso R é trapezoidal superior Se X tem posto rk as linhas Rrk1 Rrk2 são zeros QRE qrX produz uma matriz de permutação de colunas E uma matriz triangular superior R com elementos na diagonal decrescentes e uma matriz ortogonal ou unitaria Q tais que XE QR Se rk é o posto de X as rk primeiras entradas ao longo da diagonal de R ie R11 R22 Rrkrk são todas diferentes de zero QRE qrXe produz uma economia de tamanho Se X ié mporn com m n então apenas as n primeiras colunas de Q são computadas tanto quanto as n priemiras linhas de R QRrkE qrX tol retorna rk estimativa do posto de X ie rk é o número elementos da diagonal de R que são maiores que um dado limiar tol QRrkE qrX retorna rk estimativa do posto de X ie rk é o número de elementos da diagonal de R que são maiores que tolR11epsmaxsizeR Veja rankqr para uma fatoração QR que revela o posto usando o número de condicionamento de R qr 1403 Exemplos fatoração QR caso genérico X é alta posto cheio Xrand52QRqrX QX R X é gorda posto cheio Xrand23QRqrX QX R coluna 4 de X é uma combinação linear das colunas 1 e 2 Xrand85X4X1X2 QRqrX R R4 X tem posto 2 linhas 3 a de R são zero Xrand82rand25QRqrX R Avaliando o posto rk pivotação por colunas gt rk primeiras As entradas diagonais de R são nãonulas Arand52rand25 QRrkE qrA1d10 normQAR svdAQ1rk spanA spanQ1rk spangerado Ver Também rankqr rank svd rowcomp colcomp Funções Usadas A decomposição qr é baseada nas rotinas de Lapack DGEQRF DGEQPF DORGQR para as matrizes de reais ZGEQRF ZGEQPF ZORGQR para as matrizes de complexos 1404 Name quaskro forma quasiKronecker QZQdZdnumbepsnumbetaquaskroF QZQdZdnumbepsnumbetaquaskroEA QZQdZdnumbepsnumbetaquaskroFtol QZQdZdnumbepsnumbetaquaskroEAtol Parâmetros F feixe de matrizes de reais FsEA spoly0s EA duas matrizes reais de iguais dimensões tol número real tolerância valor padrão1d10 QZ duas matrizes quadradas ortogonais QdZd dois vetores de inteiros numbeps vetor de inteiros Descrição Forma quasiKronecker de um feixe de matrizes quaskro computa duas matrizes ortogonais Q Z que põem o feixe FsE A na forma triangular superior sEepsAeps X X O sEinfAinf X QsEAZ O sErAr As dimensões dos blocos são dadas por epsQd1 x Zd1 infQd2 x Zd2 r Qd3 x Zd3 O bloco inf contém os modos infinitos do feixe O bloco f contém os modos finitos do feixe A estrutura dos blocos epsilon é dada por numbeps1 de blocos eps de tamanho 0 x 1 numbeps2 de blocos eps de tamanho 1 x 2 numbeps3 de blocos eps de tamanho 2 x 3 etc quaskro 1405 A forma completa de quatro blocos de Kronecker é dada pela função kroneck que chama a função quaskro sobre o feixe pertransposto sErAr O código é retirado de T Beelen Ver Também kroneck gschur gspec 1406 Name randpencil feixe aleatório Frandpencilepsinfifineta Parâmetros eps vetor de inteiros infi vetor de inteiros fin vetor de reais ou polinômio mônico ou vetor de polinômios mônicos eta vetor de inteiros F feixe de matrizes de reais FsEA spoly0s Descrição Função utilitária Frandpencilepsinfifineta retorna um feixe aleatório F com dada estrutura de Kronecker A estrutura é dada por epseps1epsk estrutura de blocos ep silon tamanho eps1xeps11 finl1ln conjunto de autovalores finitos assumidos como reais possivelmente infik1kp tamanho de blocos J no infinito ki1 in fi se não há blocos J etaeta1etap estrutura dos blocos eta size eta11xeta1 epsis devem ser 0 etais devem ser 0 infis devem ser 1 Se fin é um polinômio mônico o bloco finito admite raízes de fin como autovalores Se fin é um vetor de polinômios eles são os divisores elementares finitos de F ie as raízes de pi são autovalores finitos de F Exemplos Frandpencil0121013 QZQdZdnumbepsnumbetakroneckF Qd Zd spoly0s Frandpencil12s32 feixe regular detF Ver Também kroneck pencan penlaur 1407 Name range Imagem gerado de Ak XdimrangeAk Parâmetros A matriz de reais ou complexos que se assume quadrada se k1 k inteiro X matriz ortonormal dim inteiro dimensão de subespaço Descrição Computação da imagem de Ak as primeiras dim colunas de X geram a imagem de Ak As últimas linhas de X geram o complemento ortogonal da imagem XX é a matriz identidade Exemplos Arand42rand24 4 vetores colunas 2 independentes XdimrangeA1dim computando a imagem y1Arand41 um vetor que está na imagem de A y2rand41 um vetor que não está na imagem de A normXdim1y1 as últimas entradas são zeros y1 está na imagem de A normXdim1y2 as últimas entradas não são zeros IX1dim I é uma base para a imagem coeffsX1dimy1 componentes de y1 relativos à base I normIcoeffsy1 verificando Ver Também fullrfk rowcomp Autor F D INRIA Função Usada A função range é baseada na função rowcomp que usa decomposição svd decomposição em valores singulares 1408 Name rank posto irankX irankXtol Parâmetros X matriz de reais ou complexos tol número real nãonegativo Descrição rankX é o posto numérico de X ie o número de valores singulares de X que são maiores que normsizeXinf normX eps rankXtol é o número de valores singulares de X que são maiores que tol Note que o valor padrão de tol é proporcional a normX Como conseqüência rank1d80001d80 é 2 Exemplos rank1d80001d80 rank1001d80 Ver Também svd qr rowcomp colcomp lu 1409 Name rankqr fatoração QR com revelação do posto QRJPVTRANKSVALrankqrA RCONDJPVT Parâmetros A matriz de reais ou complexos RCOND número real usado para determinar o posto efetivo de A que é definido como sendo a ordem da maior submatriz regente triangular R11 na fatoração QR com pivoteamento de A cujo número de condicionamento estimado é 1RCOND JPVT vetor de inteiros nas entradas se JPVTi não é 0 a iésimo coluna de A é permtutada para a frente de AP senão a coluna i é uma coluna livre Na saída se JPVTi k então a i ésima coluna de AP era a késima coluna de A RANK posto efetivo de A ie a ordem da submatriz R11 É o mesmo que a ordem da submatriz T1 na fatoração ortogonal completa de A SVAL vetor de reais com 3 componentes as estimativas de alguns dos valores singulares do fator tri angular R SVAL1 é o maior valor singular de R1RANK1RANK SVAL2 é o menor valor singular de R1RANK1RANK SVAL3 é o menor valor singular de R1RANK11RANK1 se RANK MINMN ou de R1RANK1RANK caso contrário Descrição Computa opcionalmente uma fatoração QR com revelação do posto de uma matriz de reais geral MporN ou de complexos A que pode ser deficiente de posto e estima seu posto efetivo usando estimativa de condição incremental A rotina usa uma fatoração QR com pivoteamento de colunas A P Q R onde R R11 R12 0 R22 com R11 definida como a maior submatriz regente cujo número de condição estimado é menor que 1RCOND A ordem de R11 RANK é o posto efetivo deA Se a fatoração triangular revela o posto que será o caso se as colunas regentes forem bem condi cionadas então SVAL1 também será uma estimativa para o maior valor singular de A e SVAL2 e SVAL3 serão estimativas para o RANKésimo e RANK1ésimo valores singulares de A re spectivamente Examinandose estes valores podese confirmar que o posto é bem definido a respeito do valor es colhido de RCOND A razão SVAL1SVAL2 é uma estimativa do número de condicionamento de R1RANK1RANK rankqr 1410 Exemplos Arand53rand37 QRJPVTRANKSVALrankqrAeps Ver Também qr rank Funções Usadas Rotinas da biblioteca Slicot MB03OD ZB03OD 1411 Name rcond número de condicionamento inverso rcondX Parâmetros X matriz quadrada de reais ou complexos Descrição rcondX é uma estimativa para a recíproca da condição de X na norma1 Se X é bem condicionada rcondX é próximo a 1 Senão rcondX é próximo a 0 rzrcondX ajusta r a rcondX e retorna z tal que normXz1 rnormX1normz1 Portanto se rcond é pequeno z é um vetor do núcleo Exemplos Adiag110 rcondA A110000001 rcondA Ver Também svd cond inv 1412 Name rowcomp compressão de linhas imagem WrkrowcompA flag tol Parâmetros A matriz de reais ou de complexos flag string opcional com valores possíveis svd ou qr O valor padrão é svd tol número real nãonegativo opcional O valor padrão é sqrtepsnormA1 W matriz quadrada nãosingular matriz mudança de base rk inteiro posto de A Descrição Compressão de linhas de A Ac WA é uma matriz de linhas comprimidas ie AcAf0 com Af de postolinha cheio flag e tol são parâmetros opcionais flagqr ou svd o padrão é svd tol é um parâmetro de tolerância As rk primeiras colunas de W geram a imagem de A As rk primeiras linhas do topo de W geram a imagem de linha de A Um vetor não nulo x pertence à ImA see só se Wx é de linhas comprimidas de acordo com Ac ie a norma de seus últimos componentes é pequena com relação a dos seus primeiros componentes Exemplos Arand52rand24 4 vetores colunas 2 independentes XdimrowcompAXpX svdXp1dimA spanA spanXp1dim spangerado xArand41 x pertence a spanA yXx normydim1normy1dim pequeno Ver Também colcomp fullrf fullrfk Autor F D INRIA rowcomp 1413 Função Usada A função rowcomp é baseada nas decomposições svd decomposição em valores singulares ou qr 1414 Name rowshuff algoritmo de embaralhamento WsFs1rowshuffFs alfa Parâmetros Fs feixe quadrado de reais Fs sEA Ws matriz de polinômios Fs1 feixe quadrado de reais F1s sE1 A1 com E1 nãosingular alfa número real alfa 0 é o valor padrão Descrição Algoritmo de embaralhamento dado o feixe FssEA retorna WsWs matriz quadrada de polinômios tal que Fs1 sE1A1 WssEA é um feixe com matriz E1 nãosingular Isto é possível se e só se o feixe Fs sEA é regular ie invertível O grau de Ws é igual ao índice do feixe Os pólos no infinito de Fs asão colocados para alfa e os zeros de Ws estão em alfa Note que sEA1 sE1A11 Ws WssEA1 Ws Exemplos Frandpencil2123 Frand55Frand55 feixe regular 5 x 5 com três avaliações em 123 WsF1rowshuffF1 E1A1pen2eaF1 svdE1 E1 nãosingular rootsdetWs cleaninvFinvF1Ws1d7 Ver Também pencan glever penlaur Autor F D 1415 Name rref computa a matrizlinha reduzida a forma escada por transformações de LU RrrefA Parâmetros A matriz m x n com entradas escalares R matriz m x n forma escada de A Descrição rref computa a forma escada de linhas reduzidas da matriz dada pela decomposição esquerda LU Se for necessária a transformação usada basta chamar XrrefAeyemm A forma escada de linhas reduzidas R é X1n e a transformação esquerda L ié dada por Xn1nm tal como LAR Exemplos A1 23 45 6 XrrefAeye33 RX12 LX35LA Ver Também lu qr 1416 Name schur decomposição ordenada de Schur de matrizes e feixes UT schurA Udim T schurAflag Udim T schurAextern1 AsEs QZschurAE AsEs QZdim schurAEflag Zdim schurAEflag AsEs QZdim schurAEextern2 Zdim schurAEextern2 Parâmetros A matriz quadrada de reais ou complexos E matriz quadrada de reais ou complexos com as mesmas dimensões de A flag string c oud extern1 uma external função externa veja abaixo extern2 uma external veja abaixo U matriz quadrada ortogonal ou unitária Q matriz quadrada ortogonal ou unitária Z matriz quadrada ortogonal ou unitária T matriz quadrada triangular superior ou quasitriangular As matriz quadrada triangular superior ou quasitriangular Es matriz quadrada triangular superior dim inteiro Descrição Formas de Schur formas ordenadas de Schur de matrizes e feixes FORMA DE SCHUR MATRICIAL Forma de Schur usual UT schurA produz uma matriz de Schur T e uma matriz unitária U tais que A UTU e UU eyeU Por si mesmo schurA retorna T Se A é de complexos a schur 1417 Forma de Schur Complexa é retornada na matriz T A Forma de Schur Complexa é triangular superior com os autovalores de A na diagonal Se A é de reais a Forma de Schur Real é retor nada A Forma de Schur Real tem autovalores reais na diagonal e os autovalores complexos em blocos 2por2 na diagonal Formas de Schur ordenadas UdimschurAc rretorna uma matriz unitária U que transforma A em uma forma de Schur Ainda as primeiras dim colunas de U formam uma base para o autoespaço de A associado aos autovalores com partes reais negativas autoespaço de tempo contínuo estável UdimschurAd retorna uma matriz unitária U que transforma A em uma forma de Schur Ainda as primeiras dim colunas de U geram uma base do autoespaço de A associ ado aos autovalores de magnitude menor que 1 autoespaço de tempo discreto estável UdimschurAextern1 retorna uma matriz unitária U que transforma A em uma forma de Schur Ainda as dim primeiras colunas de U geram uma base para o autoespaço de A associado aos autovalores que são selecionados pela external extern1 veja exter nal para detalhes Esta external pode ser descrita por uma função do Scilab ou por um procedure de C ou FORTRAN Uma Função do Scilab Se extern1 é descrita por uma função do Scilab deve ter a seguinte seqüência de chamamento sextern1Ev onde Ev é um autovalor e s um booleano Um Procedure C ou FORTRAN Se extern1 é descrita por uma função de C ou FORTRAN deve ter a seguinte seqüência de chamamento int extern1double EvR double EvI onde EvR e EvI são partes real e complexa de autovalor Valor verdadeiro ou diferente de zero retornado significa autovalor selecionado FORMAS DE SCHUR DE FEIXES Forma de Schur de Feixe Usual AsEs schurAE produz uma matriz As quasitriangular e uma matriz triangular Es que são a forma generalizada de Schur do par A E AsEsQZ schurAE retorna ainda duas matrizes unitárias Q e Z tais que AsQAZ e EsQEZ Formas de Schur Ordenadas AsEsZdim schurAEc retorna a forma real generalizada de Schur do feixe sEA Ainda as primeiras dim colunas de Z geram uma base para o autoespaço di reito associado aos autovalores com partes reais negativas autoespaço de tempo contínuo generalizado AsEsZdim schurAEd retorna a forma real generalizada de Schur do feixe sEA Ainda as dim primeiras colunas de Z formam uma base para o autoespaço direito associado aos autovalores de magnitude menor que 1 autoespaço de tempo discreto generalizado AsEsZdim schurAEextern2 retorna a forma real generalizada de Schur do feixe sEA Ainda as dim primeiras colunas de Z formam uma base para o autoespaço direito associado aos autovalores do feixe que são selecionados de acordo com a regra que é dada pela external extern2 veja external para detalhes Esta external pode ser descrita por uma função do Scilab ou por um proce dure de C ou FORTRAN schur 1418 Função do Scilab Se extern2 é descrita por uma função do Scilab deve ter a seqüência de chamamen to sextern2AlphaBeta onde Alpha e Beta definem um autovalor gener alizado e s um booleano Um Procedure C ou FORTRAN Se a external extern2 é descrita por um procedure C ou FORTRAN deve ter a seqüência de chamamento int extern2double AlphaR double AlphaI double Beta se A e E são matrizes de reais e int extern2double AlphaR double AlphaI double BetaR double BetaI se A ou E é matriz de complexos Alpha e Beta definem o autovalor generalizado Um valor verdadeiro ou diferente de zero siginfica autovalor generalizado selecionado Referências As computações da forma de Schur matricial são baseadas nas rotinas de Lapack DGEES e ZGEES As computações da forma de Schur de feixes são baseadas nas rotinas de Lapack DGGES e ZGGES Exemplos SCHUR FORM OF A MATRIX Adiag092209XrandAAinvXAX UTschurAT UdimTschurAc T1dim1dim stable cont eigenvalues function tmytestEvtabsEv095endfunction UdimTschurAmytest T1dim1dim The same function in C a Compiler is required cd TMPDIR Cint mytestdouble EvR double EvI the C code if EvR EvR EvI EvI 09025 return 1 else return 0 mputlCTMPDIRmytestc build and link lpilibforlinkmytestmytestcc linklpmytestc run it UdimTschurAmytest SCHUR FORM OF A PENCIL F1s 0 1 015s 0 schur 1419 0 02s 0 1 0 0 2s AcoeffF0EcoeffF1 AsEsQZschurAE QFZ It is AssEs AsEsZdim schurAEc function tmytestAlphaBetatrealAlpha0endfunction AsEsZdim schurAEmytest the same function in Fortran a Compiler is required ftninteger function mytestfaraib the fortran code double precision araib mytestf0 ifarlt00d0 mytestf1 end mputl ftnTMPDIRmytestff build and link lpilibforlinkmytestfmytestffF linklpmytestff run it AsEsZdim schurAEmytestf Ver Também spec bdiag ricc pbig psmall 1420 Name spaninter interseção de subespaços XdimspaninterAB tol Parâmetros A B duas matrizes de reais ou de complexos com igual número de linhas X matriz quadrada ortogonal ou unitária dim inteiro dimensão do subesbaço ImA inter ImB Descrição Computa a intereseção de ImA e ImB As primeiras dim colunas de X geram esta interseção ie X1dim é uma base ortogonal para ImA inter ImB Na base X A e B são respectivamente representados por XA e XB tol é um limiar sqrteps é o valor padrão Exemplos Arand53rand34 A é 5 x 4 rank3 BA2rand51rand22 XdimspaninterAB X1X1dim A interseção svdAsvdX1A X1 no geradoA spanA svdBsvdBX1 X1 no geradoB spanB Ver Também spanplus spantwo Autor F D 1421 Name spanplus soma de subespaços XdimdimaspanplusABtol Parâmetros A B duas matrizes de reais ou complexos com igual número de linhas X matriz quadrada ortogonal ou unitária dim dima inteiros dimensões de subespaços tol número real nãonegativo Descrição Computa a base X tal que as primeiras dima colunas de X geram ImA e as dimdima colunas seguintes formam uma base de AB em relação a A As dim primeiras colunas de X formam uma base para AB Temse a seguinte forma canônica para AB dima rows XAB0 dimdima rows 00 tol é um argumento opcional ver código da função Exemplos Arand62rand25 rankA2 postoA2 BA1rand62rand33 dois vetores adicionais independentes XdimdimAspanplusAB dimA dim Ver Também spaninter iminv spantwo Autor F D 1422 Name spantwo soma e interseção de subespaços XpdimadimbdimspantwoAB tol Parâmetros A B duas matrizes de reais ou complexos com igual número de linhas Xp matriz quadrada nãosingular dima dimb dim inteiros dimensões dos subespaços tol número real nãonegativo Descrição Dadas duas matrizes A e B com o mesmo número de linhas retorna uma matriz quadrada Xp não singular mas não necessariamente ortogonal tal que A1 0 dimdimb linhas XpABA2B2 dimadimbdim linhas 0 B3 dimdima linha 0 0 As primeiras dima colunas de invXp geram ImA As colunas de dimdimb1 até dima de invXp geram a interseção de ImA e ImB As primeiras dim colunas de invXp geram ImAImB As colunas de dimdimb1 até dim de invXp geram ImB A matrix A1A2 tem postolinha cheio postoA a matrix B2B3 tem postolin ha cheio postoB a matriz A2B2 tem postolinha postoA inter B e a matriz A10A2B20B3 tem postolinha cheio postoAB Exemplos A1004 5678 001112 00016 B1200C4001 Slss2sssyslincABCrandA noXcontrSlASlBCOX1no Parte controlável uoYunobsSlASlCUOY1uo Parte inobservável XpdimcdimudimspantwoCOUO Decomposição de Kalman Slcanss2ssSlinvXp spantwo 1423 Ver Também spanplus spaninter Autor F D 1424 Name spec autovalores de matrizes e feixes evalsspecA RdiagevalsspecA evalsspecAB alphabetaspecAB alphabetaZspecAB alphabetaQZspecAB Parâmetros A matriz quadrada de reais ou complexos B matriz quadrada de reais ou complexos com as mesmas dimensões que A evals vetor de reais ou complexos os autovalores diagevals matriz diagonal de reais ou complexos autovalores ao longo da diagonal alpha vetor de reais ou complexos albe fornece os autovalores beta vetor de reais albe fornece os autovalores R matriz quadrada de reais ou complexos invertível autovetores direitos da matriz Q matriz quadrada de reais ou complexos invertível autovetores esquerdos do feixe Z matriz quadrada de reais ou complexos invertível autovetores direitos do feixe Descrição evalsspecA retorna no vetor evals os autovalores Rdiagevals specA retorna na matriz diagonal evals os autovalores e em R os autovetores direitos evalsspecAB retorna o espectro do feixe de matrizes A s B ie as raízes da matriz de polinômios s B A alphabeta specAB retorna o espectro do feixe de matrizes A s B ie as raízes da matriz de polinômios A s B Auto valores generalizados alpha e beta são tais que a matriz A alphabeta B é uma matriz singular Os autovalores são dados por albe e se betai 0 o iésimo autovalor está no infinito Para B eyeA alphabeta é specA É usualmente representado pelo par alphabeta já que há uma interpretação razoável para beta0 e até mesmo para os dois sendo zero spec 1425 alphabetaR specAB retorna ainda a matriz R de autovetores direitos generalizados do feixe albeQZ specAB rretorna ainda a matriz Q e Z de autovetores esquerdos e direitos generalizados do feixe Referências As computações de autovalores de matrizes são baseadas nas rotinas Lapack DGEEV e ZGEEV quando as matrizes não são simétricas DSYEV e ZHEEV quando as matrizes são simétricas Uma matriz de complexos simétrica tem termos fora da diagonal conjugados e termos diagonais reais As computações de autovalores de feixes são baseadas nas rotinas Lapack DGGEV e ZGGEV Matrizes de reais e de complexos Devese notar que o tipo das variáveis de saída tais como evals ou R por exemplo não é necessari amente o mesmo das que das matrizes de entrada A e B No parágrafo seguinte análisamos o tipo das variáveis de saída no caso onde nos casos onde se computa os autovalores e autovetores de uma única matriz A Matriz A de reais Simétrica Os autovetores e autovalores são reais Não simétrica Os autovetores e autovalores são complexos Matriz A de complexos Simétrica Os autovalores são reais mas os autovetores são complexos Não simétrica Os autovetores e autovalores são complexos Exemplos AUTOVALORES DA MATRIZ Adiag123 Xrand33 AinvXAX specA xpoly0x poldetxeyeA rootspol SXbdiagA spec 1426 cleaninvXAX AUTOVALORES DO FEIXE Arand33 albeR specAeyeA albe cleaninvRAR exibindo os autovalores matriz genérica AAirandA ErandA rootsdetAsE caso de complexos Ver Também poly det schur bdiag colcomp 1427 Name sqroot fatoração hermitiana WW sqrootX Parâmetros X matriz simétrica nãonegativa definida de reais ou complexos Descrição Retorna W tal que XWW usa SVD Exemplos Xrand52rand25XXX WsqrootX normWWX1 Xrand52irand52XXX WsqrootX normWWX1 Ver Também chol svd 1428 Name squeeze remoção de dimensões singletons hypOut squeezehypIn Parâmetros hypIn hipermatriz ou matriz do tipo constante hypOut hipermatriz ou matriz do tipo constante Descrição Remove dimensões singletons de uma hipermatriz ie qualquer dimensão para a qual o tamanho é 1 Se a entrada é uma matriz ela não é afetada Ver Também hypermat hypermatrices Autores Eric Dubois JeanBaptiste Silvy 1429 Name sva aproximação em valores singulares UsVsvaAk UsVsvaAtol Parâmetros A matriz de reais ou complexos k inteiro tol número real nãonegativo Descrição Aproximação em valores singulares USVsvaAk com k inteiro 1 retorna US e V tais que BUSV é a melhor aproximação L2 de A com postoBk USVsvaAtol com tol real retorna US e V tais que BUSV e a normaL2 de A B é no máximo tol Exemplos Arand54rand45 UsVsvaA2 BUsV svdA svdB cleansvdAB Ver Também svd 1430 Name svd decomposição em valores singulares ssvdX USVsvdX USVsvdX0 obsolete USVsvdXe USVrksvdX tol Parâmetros X matriz de reais ou complexos s vetor de reais valores singulares S matriz diagonal de reais valores singulares UV matrizes quadradas ortogonais ou unitárias vetores singulares tol número real Descrição USV svdX produz uma matriz diagonal S com dimensão igual a de X e com elementos da diagonal nãonegativos em ordem decrescente e matrizes unitárias U e V tais que X USV USV svdX0 produz a decomposição com economia de tamanho Se X é mporn com m n então apenas as primeiras n colunas de U são computadas e S é nporn s svdX por si mesmo retorna um vetor s contendo os valores singulares USVrksvdXtol fornece também rk o posto numérico de X ie ie o número de val ores singulares maiores que tol O valor default de tol é o mesmo que em rank Exemplos Xrand42rand24 svdX sqrtspecXX Ver Também rank qr colcomp rowcomp sva spec Função Usada Decomposições svd são baseadas nas rotinas Lapack DGESVD para matrizes de reais e ZGESVD no caso de matrizes de complexos 1431 Name sylv equação de Sylvester sylvABCflag Parâmetros ABC três matrizes de reais de dimensões apropriadas flag string c ou d Descrição X sylvABCc computa X solução da equação de tempo contínuo de Sylvester AXXBC XsylvABCd computa X solução da equação de tempo discreto de Sylvester AXBXC Exemplos Arand44Crand43Brand33 X sylvABCc normAXXBC XsylvABCd normAXBXC Ver Também lyap 1432 Name trace traço de uma matriz traceX Parâmetros X matriz de reais ou complexos matriz de polinômios ou de razões de polinômios Descrição traceX é o traço da matriz X É o mesmo que sumdiagX Exemplos Arand33 traceAsumspecA Ver Também det Parte XXIV Localização 1434 Name dgettext get text translated into the current locale and a specific domain domain msgdgettextdomain myString Parameters domain The name of the message domain string the message to be translated Description dgettext get the translation of a string to the current locale in a specified message domain Examples dgettextscilabStartup execution See Also gettext Authors Sylvestre Ledru 1435 Name getdefaultlanguage getdefaultlanguage returns the default language used by Scilab getdefaultlanguage Description getdefaultlanguage returns the default language used by Scilab By default this function should return enUS Examples getdefaultlanguage See Also setlanguage getlanguage Authors Sylvestre Ledru 1436 Name getlanguage getlanguage returns current language used by Scilab getlanguage Description getlanguage returns current language used by Scilab Examples setlanguageenUS getlanguage See Also setlanguage Authors AC Sylvestre Ledru 1437 Name gettext get text translated into the current locale and domain msggettextmyString Parameters string the message to be translated Description gettext get the translation of a string to the current locale in the current domain Examples gettextStartup execution See Also dgettext Authors Sylvestre Ledru 1438 Name LANGUAGE Variable defining the language OBSOLETE Description LANGUAGE is obsolete If you need LANGUAGE add LANGUAGEgetlanguage See Also getlanguage 1439 Name setdefaultlanguage sets and saves the internal LANGUAGE value setdefaultlanguagelanguage Parameters language with languagefr en ruRU zhTW Description setdefaultlanguagelanguage changes current language and save this value in scilab You need to restart scilab if you want to use menus setdefaultlanguage resets language to the system value setdefaultlanguage is used only Windows On others operating systems it returns always f Examples setdefaultlanguageenUS restart scilab getlanguage setdefaultlanguagefrFR restart scilab getlanguage setdefaultlanguage restart scilab See Also getlanguage setlanguage Authors AC 1440 Name setlanguage Sets the internal LANGUAGE value setlanguagelanguage Parameters language with languagefr or en Description setlanguagelanguage changes current language in scilab Examples setlanguageenUS getlanguage setlanguageen getlanguage setlanguagefr getlanguage setlanguagefrFR getlanguage See Also getlanguage Authors AC Parte XXV Otimização e Simulação 1442 Índice 2 Neldermead 1443 fminsearch 1444 neldermead 1453 overview 1474 nmplot 1478 optimget 1489 optimplotfunccount 1491 optimplotfval 1492 optimplotx 1493 optimset 1494 3 Optimization base 1498 optimbase 1499 4 Optimization simplex 1513 optimsimplex 1514 Capítulo 2 Neldermead Neldermead 1444 Nom fminsearch Computes the unconstrained minimimum of given function with the NelderMead al gorithm x fminsearch costf x0 x fminsearch costf x0 options xfvalexitflagoutput fminsearch costf x0 options Description This function searches for the unconstrained minimum of a given cost function The provided algorithm is a direct search algorithm ie an algorithm which does not use the derivative of the cost function It is based on the update of a simplex which is a set of kn1 vertices where each vertex is associated with one point and one function value This algorithm is the NelderMead algorithm Design This function is based on a specialized use of the more general neldermead component Users which want to have a more flexible solution based on direct search algorithms should consider using the neldermead component instead of the fminsearch function Parameters costf The cost function x0 The initial guess options A struct which contains configurable options of the algorithm see below for details x The minimum fval The minimum function value exitflag The flag associated with exist status of the algorithm The following values are available 1 The maximum number of iterations has been reached 0 The maximum number of function evaluations has been reached 1 The tolerance on the simplex size and function value delta has been reached This signifies that the algorithm has converged probably to a solution of the problem Neldermead 1445 output A struct which stores detailed information about the exit of the algorithm This struct contains the following fields outputalgorithm A string containing the definition of the algorithm used ie NelderMead simplex direct search outputfuncCount The number of function evaluations outputiterations The number of iterations outputmessage A string containing a termination message Options In this section we describe the options input argument which have an effect on the algorithm used by fminsearch The options input argument is a data structure which drives the behaviour of fminsearch It allows to handle several options in a consistent and simple interface without the problem of managing many input arguments These options must be set with the optimset function See the optimset help for details of the options managed by this function The fminsearch function is sensitive to the following options optionsMaxIter The maximum number of iterations The default is 200 n where n is the number of variables optionsMaxFunEvals The maximum number of evaluations of the cost function The default is 200 n where n is the number of variables optionsTolFun The absolute tolerance on function value The default value is 1e4 optionsTolX The absolute tolerance on simplex size The default value is 1e4 optionsDisplay The verbose level optionsOutputFcn The output function or a list of output functions The default value is empty optionsPlotFcns The plot function or a list of plotput functions The default value is empty Termination criteria In this section we describe the termination criteria used by fminsearch The criteria is based on the following variables ssize the current simplex size Neldermead 1446 shiftfv the absolute value of the difference of function value between the highest and lowest vertices If both the following conditions ssize optionsTolX and shiftfv optionsTolFun are true then the iterations stop The size of the simplex is computed using the sigmaplus method of the optimsimplex component The sigmamplus size is the maximum length of the vector from each vertex to the first vertex It requires one loop over the vertices of the simplex The initial simplex The fminsearch algorithm uses a special initial simplex which is an heuristic depending on the initial guess The strategy chosen by fminsearch corresponds to the simplex0method flag of the nelderme ad component with the pfeffer method It is associated with the simplex0deltausual 005 and simplex0deltazero 00075 parameters Pfeffers method is an heuristic which is presented in Global Optimization Of LennardJones Atomic Clusters by Ellen Fan It is due to L Pfeffer at Stanford See in the help of optimsimplex for more details The number of iterations In this section we present the default values for the number of iterations in fminsearch The options input argument is an optionnal data structure which can contain the optionsMaxIter field It stores the maximum number of iterations The default value is 200n where n is the number of variables The factor 200 has not been chosen by chance but is the result of experiments performed against quadratic functions with increasing space dimension This result is presented in Effect of dimensionality on the neldermead simplex method by Lixing Han and Michael Neumann This paper is based on Lixing Hans PhD Algorithms in Unconstrai ned Optimization The study is based on numerical experiment with a quadratic function where the number of terms depends on the dimension of the space ie the number of variables Their study shows that the number of iterations required to reach the tolerance criteria is roughly 100n Most ite rations are based on inside contractions Since each step of the NelderMead algorithm only require one or two function evaluations the number of required function evaluations in this experiment is also roughly 100n Output and plot functions The optimset function can be used to configure one or more output and plot functions The output or plot function is expected to have the following definition function myfun x optimValues state Neldermead 1447 The input arguments x optimValues and state are described in detail in the optimset help page The optimValuesprocedure field represent the type of step used during the current iteration and can be equal to one of the following strings the empty string initial simplex expand reflect contract inside contract outside Example In the following example we use the fminsearch function to compute the minimum of the Rosenbrock function We first define the function banana and then use the fminsearch function to search the minimum starting with the initial guess 12 10 In this particular case 85 iterations are performed and 159 function evaluations are function y banana x y 100x2x122 1x12 endfunction x fval exitflag output fminsearch banana 12 1 x fval exitflag output Example with customized options In the following example we configure the absolute tolerance on the size of the simplex to a larger value so that the algorithm performs less iterations Since the default value of TolX for the fminse arch function is 1e4 we decide to use 1e2 The optimset function is used to create an optimization data structure and the field associated with the string TolX is set to 1e2 The opt data structure is then passed to the fminsearch function as the third input argument In this particular case the number of iterations is 70 with 130 function evaluations function y banana x y 100x2x122 1x12 endfunction opt optimset TolX 1e2 x fval exitflag output fminsearch banana 12 1 opt x fval exitflag output Neldermead 1448 Example with a predefined plot function In the following example we want to produce a graphic of the progression of the algorithm so that we can include that graphic into a report without defining a customized plot function The fminsearch function comes with the following 3 predefined functions optimplotfval which plots the function value optimplotx which plots the current point x optimplotfunccount which plots the number of function evaluations In the following example we use the three predefined functions in order to create one graphic repre senting the function value depending on the number of iterations function y banana x y 100x2x122 1x12 endfunction opt optimset PlotFcns optimplotfval x fval fminsearch banana 12 1 opt In the previous example we could replace the optimplotfval function with optimplotx or optim plotfunccount and obtain different results In fact we can get all the figures at the same time by setting the PlotFcns to a list of functions as in the following example function y banana x y 100x2x122 1x12 endfunction myfunctions list optimplotfval optimplotx optimplotfunccount opt optimset PlotFcns myfunctions x fval fminsearch banana 12 1 opt Example with an customized output function In the following example we want to produce intermediate outputs of the algorithm We define the outfun function which takes the current point x as input argument The function plots the current point into the current graphic window with the plot function We use the OutputFcn feature of the optimset function and set it to the output function Then the option data structure is passed to the fminsearch function At each iteration the output function is called back which creates and update an interactive plot While this example creates a 2D plot the user may customized the output function so that it writes a message in the console write some data into a data file etc The user can distinguish between the output function associated with the OutputFcn option and the plot function associated with the PlotFcns option See the optimset for more details on this feature function y banana x y 100x2x122 1x12 endfunction function outfun x optimValues state Neldermead 1449 plot x1x2 endfunction opt optimset OutputFcn outfun x fval fminsearch banana 12 1 opt Example with customized Display option The Display option allows to get some input about the intermediate steps of the algorithm as well as to be warned in case of a convergence problem In the following example we present what happens in case of a convergence problem We set the number of iterations to 10 instead of the default 400 iterations We know that 85 iterations are required to reach the convergence criteria Therefore the convergence criteria is not met and the maximum number of iterations is reached function y banana x y 100x2x122 1x12 endfunction opt optimset MaxIter 10 x fval fminsearch banana 12 1 opt Since the default value of the Display option is notify a message is generated which warns the user about a possible convergence problem The previous script produces the following output Exiting Maximum number of iterations has been exceeded increase MaxIter option Current function value 41355598 Notice that if the Display option is now set to off no message is displayed at all Therefore the user should be warned that turning the Display off should be used at your own risk In the following example we present how to display intermediate steps used by the algorithm We simply set the Display option to the iter value ffunction y banana x y 100x2x122 1x12 endfunction opt optimset Display iter x fval fminsearch banana 12 1 opt The previous script produces the following output It allows to see the number of function evaluations the minimum function value and which type of simplex step is used for the iteration Iteration Funccount min fx Procedure 0 3 242 1 3 2005 initial simplex Neldermead 1450 2 5 5161796 expand 3 7 4497796 reflect 4 9 4497796 contract outside 5 11 43813601 contract inside etc Example with customized output option In this section we present an example where all the fields from the optimValues data structure are used to print a message at each iteration function outfun x optimValues state fc optimValuesfunccount fv optimValuesfval it optimValuesiteration pr optimValuesprocedure mprintf d e d s fc fv it pr endfunction opt optimset OutputFcn outfun x fval fminsearch banana 12 1 opt The previous script produces the following output 3 2420000e001 0 3 2005000e001 1 initial simplex 5 5161796e000 2 expand 7 4497796e000 3 reflect 9 4497796e000 4 contract outside 11 4381360e000 5 contract inside 13 4245273e000 6 contract inside 157 1107549e009 84 contract outside 159 8177661e010 85 contract inside 159 8177661e010 85 Some advices In this section we present some practical advices with respect to the NelderMead method A deeper analysis is provided in the bibliography at the end of this help page as well as in the NelderMead Users Manual provided on Scilabs Wiki The following is a quick list of tips to overcome problems that may happen with this algorithm We should consider the optim function before considering the fminsearch function Because optim uses the gradient of the function and uses this information to guess the local curvature of the cost function the number of iterations and function evaluations is much lower with optim when the function is sufficiently smooth If the derivatives of the function are not available it is still possible to use numerical derivatives combined with the optim function this feature is provided by the derivative and numdiff functions If the function has discontinuous derivatives the optim function provides the nd solver which is very efficient Still there are situations where the cost function is discontinuous or noisy In these situations the fminsearch function can perform well Neldermead 1451 We should not expected a fast convergence with many parameters ie more that 10 to 20 parameters It is known that the efficiency of this algorithm decreases rapidly when the number of parameters increases The default tolerances are set to pretty loose values We should not reduce the tolerances in the goal of getting very accurate results Because the convergence rate of NelderMeads algorithm is low at most linear getting a very accurate solution will require a large number of iterations Instead we can most of the time expect a good reduction of the cost function with this algorithm Although the algorithm practically converges in many situations the NelderMead algorithm is not a provably convergent algorithm There are several known counterexamples where the algorithm fails to converge on a stationnary point and instead converge to a nonstationnary point This situation is often indicated by a repeated application of the contraction step In that situation we simply restart the algorithm with the final point as the new initial guess If the algorithm converges to the same point there is a good chance that this point is a good solution Taking into account for bounds constraints or nonlinear inequality constraints can be done by pena lization methods ie setting the function value to a high value when the constraints are not satisfied While this approach works in some situations it may also fail In this case users might be interested in Boxs complex algorithm provided by Scilab in the neldermead component If the problem is really serious Boxs complex algorithm will also fail and a more powerful solver is necessary Bibliography Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation Spendley W and Hext G R and Himsworth F R American Statistical Association and American Society for Quality 1962 A Simplex Method for Function Minimization Nelder J A and Mead R The Computer Journal 1965 Iterative Methods for Optimization C T Kelley SIAM Frontiers in Applied Mathematics 1999 Algorithm AS47 Function minimization using a simplex procedure ONeill R Applied Statistics 1971 Effect of dimensionality on the neldermead simplex method Lixing Han and Michael Neumann Optimization Methods and Software 21 1 116 2006 Algorithms in Unconstrained Optimization Lixing Han PhD The University of Connecticut 2000 Global Optimization Of LennardJones Atomic Clusters Ellen Fan Thesis February 26 2002 Mc Master University TODO implement the interrupt state of the algorithm add a demo with an interactive output function which draws the plot during the optimization implement the stop of an optimization via the stop output argument of the output function Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 Neldermead 1452 Acknowledgements Michael Baudin would like to thank Lixing Han who kindly sent his PhD thesis See Also optim neldermead optimset optimget optimplotfval optimplotx optimplotfunccount Neldermead 1453 Nom neldermead Provides several direct search optimization algorithms based on the simplex method newobj neldermeadnew this neldermeaddestroy this this neldermeadconfigure thiskeyvalue value neldermeadcget thiskey neldermeaddisplay this value neldermeadget this key this neldermeadsearch this this neldermeadrestart this this result neldermeadfunction this x Description This class provides several direct search optimization algorithms based on the simplex method The optimization problem to solve is the minimization of a cost function with bounds and nonlinear constraints min fx li xi hi i 1n gix 0 i 1nbineq where n number of variables nbineq number of inequality constraints The provided algorithms are direct search algorithms ie algorithms which do not use the derivative of the cost function They are based on the update of a simplex which is a set of kn1 vertices where each vertex is associated with one point and one function value The following algorithms are available Spendley Hext and Himsworth fixed size simplex method This algorithm solves an unconstrained optimization problem with a fixed sized simplex made of kn1 vertices Nelder and Mead variable size simplex method This algorithm solves an unconstrained optimization problem with a variable sized simplex made of kn1 vertices Box complex method This algorithm solves an constrained optimization problem with a variable sized simplex made of an arbitrary k number of vertices k2n is recommended by Box Design The neldermead component is built on top of the optimbase and optimsimplex components Neldermead 1454 Functions The following functions are available newobj neldermeadnew Creates a new neldermead object newobj The new object this neldermeaddestroy this Destroy the given object this The current object this neldermeadconfigure thiskeyvalue Configure the current object with the given value for the given key this The current object key the key to configure The following keys are available verbose set to 1 to enable verbose logging default is 0 verbosetermination set to 1 to enable verbose termination logging default is 0 x0 the initial guess as a n x 1 column vector where n is the number of variables maxfunevals the maximum number of function evalutations default is 100 If this criteria is triggered the status of the optimization is set to maxfuneval maxiter the maximum number of iterations default is 100 If this criteria is triggered the status of the optimization is set to maxiter tolfunabsolute the absolute tolerance for the function value default is 00 tolfunrelative the relative tolerance for the function value default is eps tolfunmethod the method used for the tolerance on function value in the termination criteria The following values are available t f default is f If this criteria is triggered the status of the optimization is set to tolf tolxabsolute the absolute tolerance on x default is 00 tolxrelative the relative tolerance on x default is eps tolxmethod the method used for the tolerance on x in the termination criteria Neldermead 1455 The following values are available t f default is t If this criteria is triggered the status of the optimization is set to tolx function the objective function which computes the value of the cost and the non linear constra ints if any See below for the details of the communication between the optimization system and the cost function costfargument an additionnal argument passed to the cost function outputcommand a command which is called back for output See below for the details of the communication between the optimization system and the output command function outputcommandarg an additionnal argument passed to the output command numberofvariables the number of variables to optimize default is 0 storehistory set to 1 to enable the history storing default is 0 boundsmin the minimum bounds for the parameters as an array of values default is empty ie there are no bounds boundsmax the maximum bounds for the parameters as an array of values default is empty ie there are no bounds nbineqconst the number of inequality constraints default is 0 method the name of the algorithm to use The following methods are available fixed the Spendley et al fixed simplex shape algorithm This algorithm is for unconstrai ned problems ie bounds and non linear constraints are not taken into account variable the NelderMead variable simplex shape algorithm This algorithm is for uncons trained problems ie bounds and non linear constraints are not taken into account box the Box complex algorithm This algorithm takes into account bounds and nonlinear inequality constraints mine the userdefined algorithm associated with the mymethodoption See below for details simplex0method the method to use to compute the initial simplex The first vertex in the simplex is always the initial guess associated with the x0 option The following methods are available Neldermead 1456 given the coordinates associated with the coords0 option are used to compute the initial simplex with arbitrary number of vertices This allow the user to setup the initial simplex by a specific method which is not provided by the current component for example with a simplex computed from a design of experiments This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced for example the Mac Kinnon test case The given matrix is expected to have n rows and k columns where n is the dimension of the problem and k is the number of vertices axes the simplex is computed from the coordinate axes and the length associated with the simplex0length option spendley the simplex is computed so that it is regular with the length associated with the simplex0length option ie all the edges have the same length pfeffer the simplex is computed from an heuristic in the neighborhood of the initial guess This initial simplex depends on the simplex0deltausual and simplex0deltazero randbounds the simplex is computed from the bounds and a random number This option is avai lable only if bounds are available if bounds are not available an error is generated This method is usually associated with Boxs algorithm The number of vertices in the simplex is taken from the boxnbpoints option coords0 the coordinates of the vertices of the initial simplex If the simplex0method option is set to given these coordinates are used to compute the initial simplex This matrix is expected to have shape nbve x n where nbve is the number of vertices and n is the number of variables simplex0length the length to use when the initial simplex is computed with the axes or spendley methods If the initial simplex is computed from spendley method the length is expec ted to be a scalar value If the initial simplex is computed from axes method it may be either a scalar value or a vector of values with rank n where n is the number of variables simplex0deltausual the relative delta for nonzero parameters in pfeffer method The default value is 005 simplex0deltazero the absolute delta for nonzero parameters in pfeffer method The default value is 00075 rho the reflection coefficient This parameter is used when the method option is set to fixed or variable The default value is 10 chi the expansion coefficient This parameter is used when the method option is set to va riable The default value is 20 gamma the contraction coefficient This parameter is used when the method option is set to variable The default value is 05 Neldermead 1457 sigma the shrinkage coefficient This parameter is used when the method option is set to fi xed or variable The default value is 05 tolsimplexizemethod set to f to disable the tolerance on the simplex size The default value is t If this criteria is triggered the status of the optimization is set to tolsize When this criteria is enabled the values of the options tolsimplexizeabsolute and tol simplexizerelative are used in the termination criteria The method to compute the size is the sigmaplus method tolsimplexizeabsolute the absolute tolerance on the simplex size The default value is 00 tolsimplexizerelative the relative tolerance on the simplex size The default value is eps tolssizedeltafvmethod set to t to enable the termination criteria based on the size of the simplex and the difference of function value in the simplex The default value is f If this criteria is triggered the status of the optimization is set to tolsizedeltafv This termination criteria uses the values of the options tolsimplexizeabsolute and tol deltafv This criteria is identical to Matlabs fminsearch toldeltafv the absolute tolerance on the difference between the highest and the lowest function values tolvarianceflag set to t to enable the termination criteria based on the variance of the function value If this criteria is triggered the status of the optimization is set to tolvariance This criteria is suggested by Nelder and Mead tolabsolutevariance the absolute tolerance on the variance of the function values of the simplex tolrelativevariance the relative tolerance on the variance of the function values of the simplex kelleystagnationflag set to t to enable the termination criteria using Kelleys stagnation detection based on sufficient decrease condition The default value is f If this criteria is triggered the status of the optimization is set to kelleystagnation kelleynormalizationflag set to f to disable the normalization of the alpha coefficient in Kelleys stagnation detection ie use the value of the option kelleystagnationalpha0 as is Default value is t ie the simplex gradient of the initial simplex is taken into account in the stagnation detection kelleystagnationalpha0 the parameter used in Kelleys stagnation detection The default value is 1e4 restartflag set to t to enable the automatic restart of the algorithm Default value is f restartdetection the method to detect if the automatic restart must be performed The following methods are available Neldermead 1458 oneill the factorial local optimality test by ONeill is used If the test finds a local point which is better than the computed optimum a restart is performed kelley the sufficient decrease condition by ONeill is used If the test finds that the status of the optimization is kelleystagnation a restart is performed This status may be generated if the kelleystagnationflag option is set to t The default method is oneill restartmax the maximum number of restarts when automatic restart is enabled via the restartflag option Default value is 3 restarteps the absolute epsilon value used to check for optimality in the factorial ONeill restart detection The default value is eps restartstep the absolute step length used to check for optimality in the factorial ONeill restart de tection The default value is 10 restartsimplexmethod the method to compute the initial simplex after a restart The following methods are available given the coordinates associated with the coords0 option are used to compute the initial simplex with arbitrary number of vertices This allow the user to setup the initial simplex by a specific method which is not provided by the current component for example with a simplex computed from a design of experiments This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced for example the Mc Kinnon test case The given matrix is expected to have n rows and k columns where n is the dimension of the problem and k is the number of vertices axes the simplex is computed from the coordinate axes and the length associated with the simplex0length option spendley the simplex is computed so that it is regular with the length associated with the simplex0length option ie all the edges have the same length pfeffer the simplex is computed from an heuristic in the neighborhood of the initial guess This initial simplex depends on the simplex0deltausual and simplex0deltazero randbounds the simplex is computed from the bounds and a random number This option is avai lable only if bounds are available if bounds are not available an error is generated This method is usually associated with Boxs algorithm The number of vertices in the simplex is taken from the boxnbpoints option oriented the simplex is computed so that it is oriented as suggested by CT Kelley The default method is oriented Neldermead 1459 scalingsimplex0 the algorithm used to scale the initial simplex into the nonlinear constraints The follo wing two algorithms are provided tox0 scales the vertices toward the initial guess tocentroid scales the vertices toward the centroid as recommended by Box If the centroid happens to be unfeasible because the constraints are not convex the scaling of the initial simplex toward the centroid may fail Since the initial guess is always feasible scaling toward the initial guess cannot fail The default value is tox0 boxnbpoints the number of points in the initial simplex when the simplex0method is set to rand bounds The value of this option is also use to update the simplex when a restart is performed and the restartsimplexmethod option is set to randbounds The default value is so that the number of points is twice the number of variables of the problem boxineqscaling the scaling coefficient used to scale the trial point for function improvement or into the constraints of Boxs algorithm Default value is 05 guinalphamin the minimum value of alpha when scaling the vertices of the simplex into nonlinear constraints in Boxs algorithm Default value is 1e5 boxreflect the reflection factor in Boxs algorithm Default value is 13 boxtermination set to t to enable Box termination criteria Default value is f boxtolf the absolute tolerance on difference of function values in the simplex suggested by Box This tolerance is used if the boxtermination option is set to t Default value is 1e5 boxnbmatch the number of consecutive match of Box termination criteria Default value is 5 boxboundsalpha the parameter used to project the vertices into the bounds in Boxs algorithm Default value is 0000001 mymethod a userderined simplex algorithm See below for details default is empty myterminate a userdefined terminate function See below for details default is empty myterminateflag set to t to enable the userdefined terminate function default is f value the value value neldermeadcget thiskey Get the value for the given key If the key is unknown generates an error this The current object Neldermead 1460 key the name of the key to quiery The list of available keys is the same as for the neldermeadconfigure function value neldermeadget this key Get the value for the given key If the key is unknown generates an error this The current object key the key to get The following keys are available funevals the number of function evaluations iterations the number of iterations xopt the x optimum as a n x 1 column vector where n is the number of variables fopt the optimum cost function value historyxopt an array with nbiter values containing the history of x during the iterations This array is available after optimization if the history storing was enabled with the storehistory option historyfopt an array with nbiter values containing the history of the function value during the ite rations This array is available after optimization if the history storing was enabled with the storehistory option fx0 the function value for the initial guess status a string containing the status of the optimization See below for details about the opti mization status historysimplex a matrix containing the history of the simplex during the iterations This matrix has rank nbiter x nbve x n where nbiter is the number of iterations nbve is the number of vertices in the simplex and n is the number of variables simplex0 the initial simplex This is a simplex object which is suitable for processing with the optimsimplex component simplexopt the optimum simplex This is a simplex object which is suitable for processing with the optimsimplex component restartnb the number of actual restarts performed Neldermead 1461 Most fields are available only after an optimization has been performed with one call to the neldermeadsearch method neldermeaddisplay this Display the current settings in the console this The current object this neldermeadsearch this Performs the optimization associated with the method associated with the method option and find the optimum this The current object If the restartflag option is enabled automatic restarts are performed based on the restartdetection option this neldermeadrestart this Restarts the optimization by updating the simplex and performing a new search this The current object this result neldermeadfunction this x Call the cost function and return the value this The current object x the point where the function is to be evaluated index optionnal a flag to pass to the cost function default 1 See the section The cost function for available values of index The cost function The option function allows to configure the cost function The cost function is used to compute the objective function value f If the nbineqconst option is configured to a nonzero value the cost function must also compute the value of the nonlinear positive inequality constraints c The cost function can also take as inputoutput an additional argument if the costfargument option is configured Depending of these options the cost function can have one of the following headers Without additionnal data f index costf x index f c index costf x index With costfargument f index data costf x index data f c index data costf x index data where x the current point as a column vector index optional an integer representing the value to compute Neldermead 1462 f the value of the cost function c the value of the nonlinear positive inequality constraints data an userprovided inputoutput argument The index input parameter tells to the cost function what is expected in the output arguments It has the following meaning index 2 compute f index 5 compute c index 6 compute f and c In the most simplex case there is no additionnal cost function argument and no nonlinear constraints In this case the cost function is expected to have the following header function f index myfunction x index The data argument is both input and output and the following paragraph explains for what reason and how it works This feature may be used in the situation where the cost function has to update its environment from call to call Its simplest use is to count the number of calls to the cost function but this feature is already available directly Consider the more practical situation where the optimization requires the execution of an underlying Newton method a chemical solver for example This Newton method requires an initial guess x0 If the initial guess for this underlying Newton method is kept constant the Newton method may have problems to converge when the current optimization point get far away from the its initial point If the costfargument option is provided the initial guess for the Newton method can be updated so that it gets the value of the previous call This way the Newton method will have less problems to converge and the cost function evaluation may be faster We now present how the feature works Everytime the cost function is called back the costfar gument option is passed to the cost function as an input argument If the cost function modifies its content in the output argument the content of the costfargument option is updated accordingly Once the optimization is performed the user may call the neldermeadcget function and get back an updated costfargument content The output function The option outputcommand allows to configure a command which is called back at the start of the optimization at each iteration and at the end of the optimization The output function must have the following header function outputcmdstate data myobj where state a string representing the current state of the algorithm Available values are init iter done Neldermead 1463 data a tlist containing at least the following entries x the current optimum fval the current function value iteration the current iteration index funccount the number of function evaluations simplex the current simplex step the previous step in the algorithm The following values are available init done re flection expansion insidecontraction outsidecontraction reflectionnext shrink myobj a userdefined parameter This input parameter is defined with the outputcommandarg option The output function may be used when debugging the specialized optimization algorithm so that a verbose logging is produced It may also be used to write one or several report files in a specialized format ASCII LaTeX Excel Hdf5 etc The userdefined parameter may be used in that case to store file names or logging options The data tlist argument may contain more fields than the current presented ones These additionnal fields may contain values which are specific to the specialized algorithm such as the simplex in a NelderMead method the gradient of the cost function in a BFGS method etc Termination The current component takes into account for several generic termination criterias The following termination criterias are enabled by default maxiter maxfunevals tolxmethod tolsimplexizemethod The optimizationterminate function uses a set of rules to compute if the termination occurs which leads to an optimization status which is equal to one of the following continue maxiter max funevals tolf tolx tolsize tolsizedeltafv kelleystagnation tolboxf tolvariance The value of the status may also be a userdefined string in the case where a userdefined termination function has been set The following set of rules is examined in this order By default the status is continue and the terminate flag is f The number of iterations is examined and compared to the maxiter option if the following condition Neldermead 1464 iterations maxiter is true then the status is set to maxiter and terminate is set to t The number of function evaluations and compared to the maxfunevals option is examined if the following condition funevals maxfunevals is true then the status is set to maxfuneval and terminate is set to t The tolerance on function value is examined depending on the value of the tolfunmethod f then the criteria is just ignored t if the following condition abscurrentfopt tolfunrelative abspreviousfopt tolfunabsolute is true then the status is set to tolf and terminate is set to t The relative termination criteria on the function value works well if the function value at optimum is near zero In that case the function value at initial guess fx0 may be used as previousfopt This criteria is sensitive to the tolfunrelative and tolfunabsolute options The absolute termination criteria on the function value works if the user has an accurate idea of the optimum function value The tolerance on x is examined depending on the value of the tolxmethod f then the criteria is just ignored t if the following condition normcurrentxopt previousxopt tolxrelative normcurrentxopt tolxabsolute is true then the status is set to tolx and terminate is set to t This criteria is sensitive to the tolxrelative and tolxabsolute options The relative termination criteria on x works well if x at optimum is different from zero In that case the condition measures the distance between two iterates The absolute termination criteria on x works if the user has an accurate idea of the scale of the optimum x If the optimum x is near 0 the relative tolerance will not work and the absolute tolerance is more appropriate The tolerance on simplex size is examined depending on the value of the tolsimplexize method option Neldermead 1465 f then the criteria is just ignored t if the following condition ssize tolsimplexizerelative simplexsize0 tolsimplexizeabsolute is true where simplexsize0 is the size of the simplex at iteration 0 then the status is set to tolsize and terminate is set to t The size of the simplex is computed from the sigmaplus method of the optimsimplex component This criteria is sensitive to the tolsimplexizeabsolute and the tol simplexizerelative options The absolute tolerance on simplex size and absolute difference of function value is examined de pending on the value of the tolssizedeltafvmethod option f then the criteria is just ignored t if both the following conditions ssize tolsimplexizeabsolute shiftfv toldeltafv is true where ssize is the current simplex size and shiftfv is the absolute value of the difference of function value between the highest and lowest vertices then the status is set to tolsizedeltafv and terminate is set to t The stagnation condition based on Kelley sufficient decrease condition is examined depending on the value of the kelleystagnationflag option f then the criteria is just ignored t if the following condition newfvmean oldfvmean alpha sg sg is true where newfvmean resp oldfvmean is the function value average in the current iteration resp in the previous iteration then the status is set to kelleystagnation and termi nate is set to t Here alpha is a nondimensional coefficient and sg is the simplex gradient The termination condition suggested by Box is examined depending on the value of the boxtermi nation option f then the criteria is just ignored Neldermead 1466 t if both the following conditions shiftfv boxtolf boxkount boxnbmatch is true where shiftfv is the difference of function value between the best and worst vertices and boxkount is the number of consecutive iterations where this criteria is met then the status is set to tolboxf and terminate is set to t Here the boxtolf parameter is the value associated with the boxtolf option and is a userdefined absolute tolerance on the function value The boxnbmatch parameter is the value associated with the boxnbmatch option and is the userdefined number of consecutive match The termination condition based on the variance of the function values in the simplex is examined depending on the value of the tolvarianceflag option f then the criteria is just ignored t if the following condition var tolrelativevariance variancesimplex0 tolabsolutevariance is true where var is the variance of the function values in the simplex then the status is set to tolvariance and terminate is set to t Here the tolrelativevariance parameter is the value associated with the tolrelativevariance option and is a userdefined relative tolerance on the variance of the function values The tolabsolutevariance parameter is the value associated with the tolabsolutevariance option and is the userdefined absolute tolerance of the variance of the function values The userdefined termination condition is examined depending on the value of the mytermina teflag option f then the criteria is just ignored t if the term output argument boolean returned by the termination function is true then the status is set to the userdefined status and terminate is set to t Kelleys stagnation detection The stagnation detection criteria suggested by Kelley is based on a sufficient decrease condition which requires a parameter alpha 0 to be defined The kelleynormalizationflag option allows to configure the method to use to compute this alpha parameter two methods are available where each method corresponds to a different paper by Kelley constant In Detection and Remediation of Stagnation in the NelderMead Algorithm Using a Sufficient Decrease Condition Kelley uses a constant alpha with the suggested value 1e4 which is is typical choice for line search method Neldermead 1467 normalized in Iterative Methods for Optimization Kelley uses a normalized alpha computed from the fol lowing formula alpha alpha0 sigma0 nsg where sigma0 is the size of the initial simplex and nsg is the norm of the simplex gradient for the initial guess point ONeil factorial optimality test In Algorithm AS47 Function minimization using a simplex procedure R ONeil presents a fortran 77 implementation of the simplex method A factorial test is used to check if the computed optimum point is a local minimum If the restartdetection option is set to oneill that factorial test is used to see if a restart should be performed Spendley et al implementation notes The original paper may be implemented with several variations which might lead to different results This section defines what algorithmic choices have been used The paper states the following rules Rule 1 Ascertain the lowest reading y of yi yk1 Complete a new simplex Sp by excluding the point Vp corresponding to y and replacing it by V defined as above Rule 2 If a result has occurred in k 1 successive simplexes and is not then eliminated by application of Rule 1 do not move in the direction indicated by Rule 1 or at all but discard the result and replace it by a new observation at the same point Rule 3 If y is the lowest reading in So and if the next observation made y is the lowest reading in the new simplex S do not apply Rule 1 and return to So from Sp Move out of S by rejecting the second lowest reading which is also the second lowest reading in So We implement the following rules of the Spendley et al method Rule 1 is strictly applied but the reflection is done by reflection the high point since we minimize a function instead of maximizing it like Spendley Rule 2 is NOT implemented as we expect that the function evaluation is not subject to errors Rule 3 is applied ie reflection with respect to next to high point The original paper does not mention any shrink step When the original algorithm cannot improve the function value with reflection steps the basic algorithm stops In order to make the current imple mentation of practical value a shrink step is included with shrinkage factor sigma This perfectly fits into to the spirit of the original paper Notice that the shrink step make the rule 3 reflection with respect to nexttoworst vertex unnecessary Indeed the minimum required steps are the reflection and shrinkage Never the less the rule 3 has been kept in order to make the algorithm as close as it can be to the original NelderMead implementation notes The purpose of this section is to analyse the current implementation of NelderMeads algorithm Neldermead 1468 The algorithm that we use is described in Iterative Methods for Optimization by C T Kelley The original paper uses a greedy expansion in which the expansion point is accepted whatever its function value The current implementation as most implementations uses the expansion point only if it improves over the reflection point that is if fefr then the expansion point is accepted if not the reflection point is accepted The termination criteria suggested by Nelder and Mead is based on an absolute tolerance on the stan dard deviation of the function values in the simplex We provide this original termination criteria with the tolvarianceflag option which is disabled by default Boxs complex algorithm implementation notes In this section we analyse the current implementation of Boxs complex method The initial simplex can be computed as in Boxs paper but this may not be safe In his paper Box suggest that if a vertex of the initial simplex does not satisfy the non linear constraints then it should be moved halfway toward the centroid of those points already selected This behaviour is available when the scalingsimplex0 option is set to tocenter It may happen as suggested by Guin that the centroid is not feasible This may happen if the constraints are not convex In this case the initial simplex cannot be computed This is why we provide the tox0 option which allows to compute the initial simplex by scaling toward the initial guess which is always feasible In Boxs paper the scaling into the non linear constraints is performed toward the centroid that is by using a scaling factor equal to 05 This default scaling factor might be suboptimal in certain situations This is why we provide the boxineqscaling option which allows to configure the scaling factor In Boxs paper whether we are concerned with the initial simplex or with the simplex at a given iteration the scaling for the non linear constraints is performed without end This is because Boxs hypothesis is that ultimately a satisfactory point will be found As suggested by Guin if the process fails the algorithm goes into an infinite loop In order to avoid this we perform the scaling until a minimum scaling value is reached as defined by the guinalphamin option We have taken into account for the comments by Guin but it should be emphasized that the current implementation is still as close as possible to Boxs algorithm and is not Guins algorithm More pre cisely during the iterations the scaling for the non linear constraints is still performed toward the centroid be it feasible or not Userdefined algorithm The mymethod option allows to configure a userdefined simplexbased algorithm The reason for this option is that many simplexbased variants of NelderMeads algorithm have been developped over the years with specific goals While it is not possible to provide them all it is very convenient to use the current structure without being forced to make many developments The value of the mymethod option is expected to be a Scilab function with the following header function this myalgorithm this endfunction where this is the current object Neldermead 1469 In order to use the userdefined algorithm the method option must be set to mine In this case the component performs the optimization exactly as if the userdefined algorithm was provided by the component The user interested in that feature may use the internal scripts provided in the distribution as templates and tune his own algorithm from that point There is of course no warranty that the userdefined algorithm improves on the standard algorithm so that users use this feature at their own risks Userdefined termination Many termination criteria are found in the bibliography Users which aim at reproducing the results exhibited in a particular paper may find that that none of the provided termination criteria match the one which is used in the paper It may also happen that the provided termination criteria are not suitable for the specific test case In those situation the myterminate option allows to configure a user defined termination function The value of the myterminate option is expected to be a Scilab function with the following header function this terminate status mystoppingrule this simplex endfunction where this is the current object and simplex is the current simplex The terminate output argument is a boolean which is false if the algorithm must continue and true if the algorithm must stop The status output argument is a string which is associated with the current termination criteria In order to enable the use of the userdefined termination function the value of the mytermina teflag must be set to true At each iteration if the myterminateflag option has been set to true the userdefined termination is called If the terminate output argument is true then the algorithm is stopped In that case the value of the status option of the neldermeadget is the value of the status output argument of the userdefined termination function Example 1 basic use In the following example we solve a simple quadratic test case We begin by defining the cost function which takes 2 input arguments and returns the objective The classical starting point 12 10 is used The neldermeadnew creates a new neldermead object Then we use the neldermeadconfigure method to configure the parameters of the problem We use all default settings and perform the search for the optimum The neldermeaddisplay function is used to display the state of the optimization and the neldermeadget is used to retrieve the optimum parameters function f index quadratic x index f x12 x22 endfunction x0 10 10 nm neldermeadnew nm neldermeadconfigurenmnumberofvariables2 nm neldermeadconfigurenmfunctionquadratic nm neldermeadconfigurenmx0x0 nm neldermeadsearchnm neldermeaddisplaynm xopt neldermeadgetnmxopt nm neldermeaddestroynm Neldermead 1470 Example 2 customized use In the following example we solve the Rosenbrock test case We begin by defining the Rosenbrock function which takes 2 input arguments and returns the objective The classical starting point 12 10 is used The neldermeadnew creates a new neldermead object Then we use the neldermeadconfigure method to configure the parameters of the problem The initial simplex is computed from the axes and the single length 10 this is the default but is explicitely written here as an example The va riable simplex algorithm by Nelder and Mead is used which corresponds to the method variable option The neldermeadsearch function performs the search for the minimum Once the minimum is found the neldermeadcontour allows to compute the data required by the contour function This is possible since our problem involves only 2 parameters This function uses the cost function previ ously configured to compute the required data The contour plot is directly drawn from the data pro vided by neldermeadcontour Then we plot the initial guess on the contour plot as a blue dot The neldermeadget function is used to get the optimum which is associated with the xopt option The optimum is plot on the contour plot as a red dot mprintfDefining Rosenbrock function function f index rosenbrock x index y 100x2x1221x12 endfunction x0 12 10 mprintfx0s strcatstringx0 mprintfCreating object nm neldermeadnew mprintfConfiguring object nm neldermeadconfigurenmnumberofvariables2 nm neldermeadconfigurenmfunctionrosenbrock nm neldermeadconfigurenmx0x0 nm neldermeadconfigurenmmaxiter200 nm neldermeadconfigurenmmaxfunevals300 nm neldermeadconfigurenmtolfunrelative10eps nm neldermeadconfigurenmtolxrelative10eps nm neldermeadconfigurenmsimplex0methodaxes nm neldermeadconfigurenmsimplex0length10 nm neldermeadconfigurenmmethodvariable nm neldermeadconfigurenmverbose0 nm neldermeadconfigurenmverbosetermination0 mprintfSearching for minimum nm neldermeadsearchnm mprintfPlot contour xmin 20 xmax 20 ymin 20 ymax 20 nx 100 ny 100 stepx xmax xminnx xdata xminstepxxmax stepy ymax yminny ydata yminstepyymax for ix 1lengthxdata for iy 1lengthydata experiment xdataix ydataiy nm fiexp neldermeadfunction nm experiment zdata ix iy fiexp end end wnum 100001 myhandle scfwnum contour xdata ydata zdata 1 10 100 500 1000 2000 Plot starting point Neldermead 1471 mprintfx0 blue dot plotx01x02 myhandlechildrenchildren1childrenmarkmodeon myhandlechildrenchildren1childrenmarksize 5 myhandlechildrenchildren1childrenmarkforeground 2 mprintfxopt red dot xopt neldermeadgetnmxopt plotxopt1xopt2 myhandlechildrenchildren1childrenmarkmodeon myhandlechildrenchildren1childrenmarksize 5 myhandlechildrenchildren1childrenmarkforeground 5 nm neldermeaddestroynm The verbose option allows to get detailed informations about the current optimization process The following is a sample output for an optimization based on the Nelder and Mead variableshape simplex algorithm Only the output corresponding to the iteration 156 is displayed In order to display specific outputs or to create specific output files and graphics the outputcommand option should be used Iteration 156 total 156 Function Eval 297 Xopt 1 1 Fopt 6871176e027 DeltaFv 2880999e026 Center 1 1 Size 2548515e013 Vertex 13 fv0000000 x1000000 1000000 Vertex 23 fv0000000 x1000000 1000000 Vertex 33 fv0000000 x1000000 1000000 nmplotoutputcmd 1 Reflect xbar1 1 Function Evaluation 298 is 1155D25 at 1 1 xr1 1 fxr0000000 Contract inside Function Evaluation 299 is 6023D27 at 1 1 xc1 1 fxc0000000 Perform Inside Contraction Sort Example 3 use output function In the following example we show how to use the output command to create specialized outputs These outputs may be used to create specific data files or make interactive graphic outputs We define the function myoutputcmd which takes the current state as its first argument The state is a string which can contain init iter or done depending on the status of the optimization The data input argument is a tlist which contains the data associated with the current iteration In this case we use the fields to print a message in the console As another example of use we could format the message so that it uses LaTeX formatting rules which may allow the user to directly copy and paste the output into a LaTeX report Neldermead 1472 function f index rosenbrock x index f 100x2x122 1x12 endfunction myoutputcmd This command is called back by the NelderMead algorithm Arguments state the current state of the algorithm init iter done data the data at the current state This is a tlist with the following entries x the optimal vector of parameters fval the minimum function value simplex the simplex as a simplex object iteration the number of iterations performed funccount the number of function evaluations step the type of step in the previous iteration function myoutputcmd state data iter dataiteration if state init then mprintf mprintf Initialization elseif state done then mprintf mprintf End of Optimization end fc datafunccount fval datafval x datax simplex datasimplex Simplex is a data structure which can be managed by the optimsimplex class ssize optimsimplexsize simplex mprintf Iteration d Feval d Fval e x s Size e iter fc fval strcatstringx ssize endfunction nm neldermeadnew nm neldermeadconfigurenmnumberofvariables2 nm neldermeadconfigurenmfunctionrosenbrock nm neldermeadconfigurenmx012 10 nm neldermeadconfigurenmmaxiter200 nm neldermeadconfigurenmmaxfunevals300 nm neldermeadconfigurenmtolfunrelative10eps nm neldermeadconfigurenmtolxrelative10eps nm neldermeadconfigurenmsimplex0methodaxes nm neldermeadconfigurenmsimplex0length10 nm neldermeadconfigurenmmethodvariable nm neldermeadconfigurenmverbose0 nm neldermeadconfigurenmverbosetermination0 nm neldermeadconfigurenmoutputcommandmyoutputcmd nm neldermeadsearchnm nm neldermeaddestroynm Neldermead 1473 The previous script produces the following output Initialization Iteration 0 Feval 4 Fval 2420000e001 x 12 1 Size 1000000e000 Iteration 1 Feval 4 Fval 2420000e001 x 12 1 Size 1000000e000 Iteration 2 Feval 6 Fval 2420000e001 x 12 1 Size 1000000e000 Iteration 3 Feval 8 Fval 2420000e001 x 12 1 Size 1000000e000 Iteration 4 Feval 10 Fval 9999182e000 x 10125 078125 Size 5970304e001 Iteration 155 Feval 296 Fval 2024754e026 x 1 1 Size 4601219e013 Iteration 156 Feval 298 Fval 6871176e027 x 1 1 Size 2548515e013 Iteration 157 Feval 300 Fval 6023002e027 x 1 1 Size 2814328e013 End of Optimization Iteration 157 Feval 300 Fval 6023002e027 x 1 1 Size 2814328e013 Bibliography Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation Spendley W and Hext G R and Himsworth F R American Statistical Association and American Society for Quality 1962 A Simplex Method for Function Minimization Nelder J A and Mead R The Computer Journal 1965 A New Method of Constrained Optimization and a Comparison With Other Methods M J Box The Computer Journal 1965 814252 1965 by British Computer Society Discussion and correspondence modification of the complex method of constrained optimization J A Guin The Computer Journal 1968 Detection and Remediation of Stagnation in the NelderMead Algorithm Using a Sufficient Decrease Condition Kelley C T SIAM J on Optimization 1999 Iterative Methods for Optimization C T Kelley SIAM Frontiers in Applied Mathematics 1999 Algorithm AS47 Function minimization using a simplex procedure ONeill R Applied Statistics 1971 Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 See Also optimbase optimsimplex nmplot Neldermead 1474 Nom overview An overview of the NelderMead toolbox Purpose The goal of this toolbox is to provide a NelderMead direct search optimization method That Nel derMead algorithm may be used in the following optimization context there is no need to provide the derivatives of the objective function the number of parameters is small up to 1020 there are bounds andor non linear constraints Design This package provides the following components neldermead provides various NelderMead variants and manages for NelderMead specific set tings such as the method to compute the initial simplex the specific termination criteria fminsearch provides a simplified NelderMead algorithm Specific terminations criteria initial simplex and auxiliary settings are automatically configured optimset optimget provide Scilab commands to emulate their Matlab counterparts optimplotfunccount optimplotx and optimplotfval provide plotting features for the fminsearch function nmplot provides a highlevel component which provides directly output pictures for NelderMead algorithm The current component is based on the following components optimbase provides an abstract class for a general optimization component including the number of variables the minimum and maximum bounds the number of non linear inequality constraints the loggin system various termination criteria the cost function etc optimsimplex provides a class to manage a simplex made of an arbitrary number of vertices including the computation of a simplex by various methods axes regular Pfeffers randomized bounds the computation of the size by various methods diameter sigma sigma etc Features The following is a list of features the NelderMead prototype algorithm currently provides Provides 3 algorithms including Spendley et al fixed shaped algorithm NelderMead variable shape algorithm Box complex algorithm managing bounds and nonlinear inequality constraints based on arbi trary number of vertices in the simplex Manage various simplex initializations initial simplex given by user initial simplex computed with a length and along the coordinate axes Neldermead 1475 initial regular simplex computed with Spendley et al formula initial simplex computed by a small perturbation around the initial guess point Manage cost function optionnal additionnal argument direct communication of the task to perform cost function or inequality constraints Manage various termination criteria including maximum number of iterations tolerance on func tion value relative or absolute tolerance on x relative or absolute tolerance on standard deviation of function value original termination criteria in 3 maximum number of evaluations of cost function absolute or relative simplex size Manage the history of the convergence including history of function values history of optimum point history of simplices history of termination criterias Provide a plot command which allows to graphically see the history of the simplices toward the optimum Provide query features for the status of the optimization process number of iterations number of function evaluations status of execution function value at initial point function value at optimal point etc Kelley restart based on simplex gradient ONeill restart based on factorial search around optimum Example Optimizing the Rosenbrock function In the following example one searches the minimum of the 2D Rosenbrock function One begins by defining the function rosenbrock which computes the Rosenbrock function The traditionnal initial guess 12 10 is used The initial simplex is computed along the axes with a length equal to 01 The NelderMead algorithm with variable simplex size is used The verbose mode is enabled so that messages are generated during the algorithm After the optimization is performed the optimum is retrieved with quiery features function y rosenbrock x y 100x2x122 1x12 endfunction nm neldermeadnew nm neldermeadconfigurenmx012 10 nm neldermeadconfigurenmsimplex0methodaxes nm neldermeadconfigurenmsimplex0length01 Neldermead 1476 nm neldermeadconfigurenmmethodvariable nm neldermeadconfigurenmverbose1 nm neldermeadconfigurenmfunctionrosenbrock nm neldermeadsearchnm xopt neldermeadgetnmxopt fopt neldermeadgetnmfopt historyfopt neldermeadgetnmhistoryfopt iterations neldermeadgetnmiterations historyxopt neldermeadgetnmhistoryxopt historysimplex neldermeadgetnmhistorysimplex fx0 neldermeadgetnmfx0 status neldermeadgetnmstatus nm neldermeaddestroynm Authors Michael Baudin 20082009 Bibliography Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation Spendley W and Hext G R and Himsworth F R American Statistical Association and American Society for Quality 1962 A Simplex Method for Function Minimization Nelder J A and Mead R The Computer Journal 1965 A New Method of Constrained Optimization and a Comparison With Other Methods M J Box The Computer Journal 1965 814252 1965 by British Computer Society Convergence Properties of the NelderMead Simplex Method in Low Dimensions Jeffrey C La garias and James A Reeds and Margaret H Wright and Paul E Wright SIAM Journal on Optimiza tion 1998 Compact numerical methods for computers linear algebra and function minimisation Nash J C Hilger Bristol 1979 Iterative Methods for Optimization C T Kelley 1999 Iterative Methods for Optimization Matlab Codes httpwww4ncsueductkmatlabdartshtml Sequential Simplex Optimization A Technique for Improving Quality and Productivity in Research Development and Manufacturing Walters Fred H and Jr Lloyd R and Morgan Stephen L and Deming Stanley N 1991 Numerical Recipes in C Second Edition W H Press and Saul A Teukolsky and William T Vet terling and Brian P Flannery 1992 Detection and Remediation of Stagnation in the NelderMead Algorithm Using a Sufficient Decrease Condition SIAM J on Optimization Kelley C T 1999 Matlab fminsearch httpwwwmathworkscomaccesshelpdeskhelptechdocindexhtmlac cesshelpdeskhelptechdocreffminsearchhtml GAMS A19A20 description httpgamsnistgovservecgiModuleNASHLIBA19A2011238 asa047f httppeoplescfsueduburkardtf77srcasa047asa047f optim1f httpwwwstatuconnedumhchensurvbookexample51optim1f Neldermead 1477 as47f httplibstatcmueduapstat47 Algorithm AS47 Function minimization using a simplex procedure ONeill R 1971 Applied Statistics TODO include MultiDirectionnal Search algorithm in the release include parabolic interpolation in the release provide a neldermeadoutputfunction to make nice and easy outputs provide a stopping feature to the cost function and manage the stop output argument to the output functions of fminsearch provide a quadratic penalized version of neldermead for bound constrained problems Neldermead 1478 Nom nmplot Provides several direct search optimization algorithms based on the simplex method newobj nmplotnew this nmplotdestroy this this nmplotconfigure thiskeyvalue value nmplotcget thiskey this nmplotdisplay this value nmplotget this key this nmplotsearch this this nmplotrestart this this xdata ydata zdata nmplotcontour this xmin xmax ymin ymax nx ny this nmplothistoryplot this datafile mytitle myxlabel myylabel this nmplotsimplexhistory this colorforeground markforeground markstyle Description This class provides several direct search optimization algorithms based on the simplex method The goal of this class is to provide a neldermead component with plotting features It enables to make fast plots of the algorithm progress through the iterations It is a specialized neldermead class with a specific output command This output function allows to store the history of several datas through the iterations of the algorithm These datas are the history of the coordinates of the simplex the history of the function value averaged on the vertices the history of the minimum function value in the simplex the history of the size of the simplex as computed with the sigma method These data are stored into several data files during the optimization process Several methods allows to plot the data stored into these data files Design The nmplot component is built on top of the neldermead component The outputcommand option of the neldermead class is not available since the nmplot class uses its own output function Additionnal options simplexfn fbarfn foptfn and sigmafn are provided which allows to configure the file names where the data is stored The nmplot class can be considered as a sample test case of the outputcommand option of the nel dermead class It gives an example of the situation where the user wants to get specialized outputs out of the neldermead class Functions The following functions are available newobj nmplotnew Creates a new nmplot object newobj The new object this nmplotdestroy this Destroy the given object Neldermead 1479 this The current object this nmplotconfigure thiskeyvalue Configure the current object with the given value for the given key this The current object key the key to configure The following keys are available verbose set to 1 to enable verbose logging default is 0 verbosetermination set to 1 to enable verbose termination logging default is 0 x0 the initial guess as a n x 1 column vector where n is the number of variables maxfunevals the maximum number of function evalutations default is 100 If this criteria is triggered the status of the optimization is set to maxfuneval maxiter the maximum number of iterations default is 100 If this criteria is triggered the status of the optimization is set to maxiter tolfunabsolute the absolute tolerance for the function value default is 00 tolfunrelative the relative tolerance for the function value default is eps tolfunmethod the method used for the tolerance on function value in the termination criteria The following values are available absoluterelative relative absolute disa bled default is disabled If this criteria is triggered the status of the optimization is set to tolf tolxabsolute the absolute tolerance on x default is 00 tolxrelative the relative tolerance on x default is eps tolxmethod the method used for the tolerance on x in the termination criteria The following values are available relative absolute disabled default is relati ve If this criteria is triggered the status of the optimization is set to tolx function the objective function which computes the value of the cost and the non linear constra ints if any See below for the details of the communication between the optimization system and the cost function costfargument an additionnal argument passed to the cost function Neldermead 1480 outputcommand a command which is called back for output See below for the details of the communication between the optimization system and the output command function outputcommandarg an additionnal argument passed to the output command numberofvariables the number of variables to optimize default is 0 storehistory set to 1 to enable the history storing default is 0 boundsmin the minimum bounds for the parameters as an array of values default is empty ie there are no bounds boundsmax the maximum bounds for the parameters as an array of values default is empty ie there are no bounds nbineqconst the number of inequality constraints default is 0 method the name of the algorithm to use The following methods are available fixed the Spendley et al fixed simplex shape algorithm This algorithm is for unconstrai ned problems ie bounds and non linear constraints are not taken into account variable the NelderMead variable simplex shape algorithm This algorithm is for uncons trained problems ie bounds and non linear constraints are not taken into account box the Box complex algorithm This algorithm takes into account bounds and nonlinear inequality constraints simplex0method the method to use to compute the initial simplex The first vertex in the simplex is always the initial guess associated with the x0 option The following methods are available given the coordinates associated with the coords0 option are used to compute the initial simplex with arbitrary number of vertices This allow the user to setup the initial simplex by a specific method which is not provided by the current component for example with a simplex computed from a design of experiments This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced for example the Mac Kinnon test case The given matrix is expected to have n rows and k columns where n is the dimension of the problem and k is the number of vertices axes the simplex is computed from the coordinate axes and the length associated with the simplex0length option Neldermead 1481 spendley the simplex is computed so that it is regular with the length associated with the simplex0length option ie all the edges have the same length pfeffer the simplex is computed from an heuristic in the neighborhood of the initial guess This initial simplex depends on the simplex0deltausual and simplex0deltazero randbounds the simplex is computed from the bounds and a random number This option is avai lable only if bounds are available if bounds are not available an error is generated This method is usually associated with Boxs algorithm The number of vertices in the simplex is taken from the boxnbpoints option coords0 the coordinates of the vertices of the initial simplex If the simplex0method option is set to given these coordinates are used to compute the initial simplex This matrix is expected to have shape nbve x n where nbve is the number of vertices and n is the number of variables simplex0length the length to use when the initial simplex is computed with the axes or spendley methods If the initial simplex is computed from spendley method the length is expec ted to be a scalar value If the initial simplex is computed from axes method it may be either a scalar value or a vector of values with rank n where n is the number of variables simplex0deltausual the relative delta for nonzero parameters in pfeffer method The default value is 005 simplex0deltazero the absolute delta for nonzero parameters in pfeffer method The default value is 00075 rho the reflection coefficient This parameter is used when the method option is set to fixed or variable The default value is 10 chi the expansion coefficient This parameter is used when the method option is set to va riable The default value is 20 gamma the contraction coefficient This parameter is used when the method option is set to variable The default value is 05 sigma the shrinkage coefficient This parameter is used when the method option is set to fi xed or variable The default value is 05 tolfstdeviationmethod set to enabled to enable the termination criteria based on the standard deviation of the function values in the simplex The default value is disabled If this criteria is triggered the status of the optimization is set to tolfstdev This criteria is suggested by Nelder and Mead tolfstdeviation the absolute tolerance on standard deviation The default value is 00 tolsimplexizemethod set to disabled to disable the tolerance on the simplex size The default value is ena bled If this criteria is triggered the status of the optimization is set to tolsize Neldermead 1482 When this criteria is enabled the values of the options tolsimplexizeabsolute and tol simplexizerelative are used in the termination criteria The method to compute the size is the sigmaplus method tolsimplexizeabsolute the absolute tolerance on the simplex size The default value is 00 tolsimplexizerelative the relative tolerance on the simplex size The default value is eps tolssizedeltafvmethod set to enabled to enable the termination criteria based on the size of the simplex and the difference of function value in the simplex The default value is disabled If this criteria is triggered the status of the optimization is set to tolsizedeltafv This termination criteria uses the values of the options tolsimplexizeabsolute and tol deltafv This criteria is identical to Matlabs fminsearch toldeltafv the absolute tolerance on the difference between the highest and the lowest function values kelleystagnationflag set to 1 to enable the termination criteria using Kelleys stagnation detection based on sufficient decrease condition The default value is 0 If this criteria is triggered the status of the optimization is set to kelleystagnation kelleynormalizationflag set to 0 to disable the normalization of the alpha coefficient in Kelleys stagnation de tection ie use the value of the option kelleystagnationalpha0 as is Default value is 1 ie the simplex gradient of the initial simplex is taken into account in the stagnation detection kelleystagnationalpha0 the parameter used in Kelleys stagnation detection The default value is 1e4 restartflag set to 1 to enable the automatic restart of the algorithm Default value is 0 restartdetection the method to detect if the automatic restart must be performed The following methods are available oneill the factorial local optimality test by ONeill is used If the test finds a local point which is better than the computed optimum a restart is performed kelley the sufficient decrease condition by ONeill is used If the test finds that the status of the optimization is kelleystagnation a restart is performed This status may be generated if the kelleystagnationflag option is set to 1 The default method is oneill restartmax the maximum number of restarts when automatic restart is enabled via the restartflag option Default value is 3 restarteps the absolute epsilon value used to check for optimality in the factorial ONeill restart detection The default value is eps Neldermead 1483 restartstep the absolute step length used to check for optimality in the factorial ONeill restart de tection The default value is 10 restartsimplexmethod the method to compute the initial simplex after a restart The following methods are available given the coordinates associated with the coords0 option are used to compute the initial simplex with arbitrary number of vertices This allow the user to setup the initial simplex by a specific method which is not provided by the current component for example with a simplex computed from a design of experiments This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced for example the Mac Kinnon test case The given matrix is expected to have n rows and k columns where n is the dimension of the problem and k is the number of vertices axes the simplex is computed from the coordinate axes and the length associated with the simplex0length option spendley the simplex is computed so that it is regular with the length associated with the simplex0length option ie all the edges have the same length pfeffer the simplex is computed from an heuristic in the neighborhood of the initial guess This initial simplex depends on the simplex0deltausual and simplex0deltazero randbounds the simplex is computed from the bounds and a random number This option is avai lable only if bounds are available if bounds are not available an error is generated This method is usually associated with Boxs algorithm The number of vertices in the simplex is taken from the boxnbpoints option oriented the simplex is computed so that it is oriented as suggested by CT Kelley The default method is oriented boxnbpoints the number of points in the initial simplex when the restartsimplexmethod option is set to randbounds The default value is so that the number of points is twice the number of variables of the problem nbineqloops the number of loops to perform in Box and BoxGuin algorithms to scale the trial point for function improvement or into the constraints Default value is 10 ineqscaling the scaling coefficient used to scale the trial point for function improvement or into the constraints Default value is 05 simplexfn the name of the file containing the history of the simplex Default value is the empty string Neldermead 1484 fbarfn the name of the file containing the history of the function value averaged on the vertices of the simplex Default value is the empty string foptfn the name of the file containing the history of the minimum function value in the simplex Default value is the empty string sigmafn the name of the file containing the history of the size of the simplex Default value is the empty string value the value value nmplotcget thiskey Get the value for the given key If the key is unknown generates an error this The current object key the name of the key to quiery The list of available keys is the same as for the nmplotconfigure function value nmplotget this key Get the value for the given key If the key is unknown generates an error this The current object key the key to get The following keys are available funevals the number of function evaluations iterations the number of iterations xopt the x optimum as a n x 1 column vector where n is the number of variables fopt the optimum cost function value historyxopt an array with nbiter values containing the history of x during the iterations This array is available after optimization if the history storing was enabled with the storehistory option historyfopt an array with nbiter values containing the history of the function value during the ite rations This array is available after optimization if the history storing was enabled with the storehistory option fx0 the function value for the initial guess Neldermead 1485 status a string containing the status of the optimization See below for details about the opti mization status historysimplex a matrix containing the history of the simplex during the iterations This matrix has rank nbiter x nbve x n where nbiter is the number of iterations nbve is the number of vertices in the simplex and n is the number of variables simplexopt the optimum simplex This is a simplex object which is suitable for processing with the simplex interface restartnb the number of actual restarts performed Most fields are available only after an optimization has been performed with one call to the neldermeadsearch method this nmplotdisplay this Display the current settings in the console this The current object this nmplotsearch this Performs the optimization associated with the method associated with the method option and find the optimum this The current object If the restartflag option is enabled automatic restarts are performed based on the restartdetection option this nmplotrestart this Restarts the optimization by updating the simplex and performing a new search this The current object this xdata ydata zdata nmplotcontour this xmin xmax ymin ymax nx ny Plot the contours of the cost function The cost function must be a function with two parameters this The current object xmin xmax ymin ymax the bounds for the contour plot nx ny the number of points in the directions x y xdata ydata zdata vectors of data as required by the contour function nmplotsimplexhistory this colorforeground markforeground markstyle Plots the simplex history on the current graphic window The colorforeground markforeground markstyle options are provided to produce fast plots Specific settings can still be applied with the usual graphic features this The current object Neldermead 1486 colorforeground the color of the foreground for the simplices Default value is 5 markforeground the foreground mark for the simplices Default value is 3 markstyle the mark style for the simplices Default value is 9 nmplothistoryplot this datafile mytitle myxlabel myylabel Plots the history from the given data file on the current graphic window The mytitle myxlabel myylabel options are provided as a way to produce plots faster Specific settings can still be applied with the usual graphic features this The current object datafile the data file which contains the history The file is expected to be formatted in a way similar to the files associated with the fbarfn foptfn and sigmafn files The default value is the value of the foptfn option mytitle the title of the plot Default value is the empty string myxlabel the x label for the plot Default value is the empty string myylabel the y label for the plot Default value is the empty string this result nmplotfunction this x index Call the cost function and return the value this The current object x the point where the function is to be evaluated index optionnal a flag to pass to the cost function default 1 See the section The cost function of the neldermead component for available values of index Example In the following example we use the fixed shape Spendley et al simplex algorithm and find the mini mum of a quadratic function We begin by defining a quadratic function associated with 2 input varia bles We then define an nmplot object and configure the object so that the fixed shape simplex algo rithm is used with the regular initial simplex associated with the spendley key Four files are confi gured which will contain the history of the simplex the history of fbar fopt and sigma through the ite rations The search is performed by the nmplotsearch function which writes the 4 data files during the iterations The nmplotcontour function is called in order to compute the arrays xdata ydata and zdata which are required as input to the contour function The nmplotsimplexhistory then uses the history of the simplex as stored in the rosenbrockfixedhistorysimplextxt data file and plot the various simpli ces on the contour plot The nmplothistoryplot is used with the files rosenbrockfixedhistoryfbartxt rosenbrockfixedhistoryfopttxt and rosenbrockfixedhistorysigmatxt which produces 3 plots of the history of the optimization algorithm through the iterations Neldermead 1487 mprintfDefining quadratic function function y quadratic x y x12 x22 x1 x2 endfunction mprintfCreating nmplot object nm nmplotnew nm nmplotconfigurenmnumberofvariables2 nm nmplotconfigurenmfunctionquadratic nm nmplotconfigurenmx020 20 nm nmplotconfigurenmmaxiter100 nm nmplotconfigurenmmaxfunevals300 nm nmplotconfigurenmtolxrelative1e8 nm nmplotconfigurenmsimplex0methodspendley nm nmplotconfigurenmmethodfixed Setup output files nm nmplotconfigurenmsimplexfnrosenbrockfixedhistorysimplextxt nm nmplotconfigurenmfbarfnrosenbrockfixedhistoryfbartxt nm nmplotconfigurenmfoptfnrosenbrockfixedhistoryfopttxt nm nmplotconfigurenmsigmafnrosenbrockfixedhistorysigmatxt Perform optimization mprintfSearching for minimum nm nmplotsearchnm nmplotdisplaynm Plot the contours of the cost function and the simplex history mprintfPlotting contour nm xdata ydata zdata nmplotcontour nm xmin 20 xmax 40 ymin 20 ymax 40 nx 100 ny 100 f scf contour xdata ydata zdata 01 10 20 50 100 150 200 nmplotsimplexhistory nm mprintfPlotting history of fbar f scf nmplothistoryplot nm rosenbrockfixedhistoryfbartxt mytitle Function Value Average myxlabel Iterations mprintfPlotting history of fopt f scf nmplothistoryplot nm rosenbrockfixedhistoryfopttxt mytitle Minimum Function Value myxlabel Iterations mprintfPlotting history of sigma f scf nmplothistoryplot nm rosenbrockfixedhistorysigmatxt mytitle Maximum Oriented length myxlabel Iterations deletefilerosenbrockfixedhistorysimplextxt deletefilerosenbrockfixedhistoryfbartxt deletefilerosenbrockfixedhistoryfopttxt deletefilerosenbrockfixedhistorysigmatxt nm nmplotdestroynm TODO add an example Neldermead 1488 Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 See Also neldermead Neldermead 1489 Nom optimget Queries an optimization data structure val optimget options key val optimget options key value Description This function allows to make queries on an existing optimization data structure This data structure must have been created and updated by the optimset function The optimget allows to retrieve the value associated with a given key In the following we analyse the various ways to call the optimget function The following calling sequence val optimgetoptions key returns the value associated with the given key The key is expected to be a string We search the key among the list of all possible fields in the options data structure In this search the case is ignored The key which matches a possible field is returned Some letters of the field may be dropped provided that the matching field is unique For example the key MaxF corresponds to the field MaxFunEval But the key Tol corresponds both to the TolX and TolFun fields and therefore will generate an error The following calling sequence val optimgetoptions key value allows to manage default value for optimization parameters Indeed if the field corresponding to the key is empty ie has not been set by the user the input argument value is returned Instead if the field corresponding the the key is not empty ie has been set by the user the parameter stored in the options argument is returned Parameters options A struct which contains the optimization fields key A string corresponding to a field of the optimization structure value A real default value val The real value corresponding to the key Example 1 In the following example we create an optimization structure and set the TolX field to 1e12 Then we use optimget to get back the value Neldermead 1490 op optimset op optimsetopTolX1e12 val optimgetopTolX val is 1e12 Example 2 In the following example we create an empty optimization structure Then we use optimget to get back the value corresponding to the TolX field with 1e5 as the default value Since the field is empty we retrieve 1e5 op optimset val optimgetopTolX 1e5 val 1e5 Example 3 In the following example we create an optimization structure and set the TolX field to 1e12 Then we use optimget to get back the value corresponding to the TolX field with 1e5 as the default value Since the field is not empty we retrieve 1e12 op optimset op optimsetopTolX1e12 val optimgetopTolX 1e5 val 1e12 Example 4 In the following example we create an optimization structure and configure the maximum number of function evaluations to 1000 Then we quiery the data structure giving only the MaxF key to the optimget function Since that corresponds only to the MaxFunEvals field there is only one match and the function returns 10000 op optimset op optimsetop MaxFunEvals 1000 val optimgetop MaxF val 1000 Authors Michael Baudin Digiteo 2009 See Also optimset Neldermead 1491 Nom optimplotfunccount Plot the number of function evaluations of an optimization algorithm optimplotfunccount x optimValues state Description This function creates and updates a plot of the number of function evaluations depending on the num ber of iterations It is a predefined plot function which should be used as an option of the PlotFcns option Example In the following example we use the optimplotfunccount function for use with the fminse arch function function y rosenbrock x y 100x2x122 1x12 endfunction opt optimset PlotFcns optimplotfunccount x fval fminsearch rosenbrock 12 1 opt Authors Michael Baudin Digiteo 2009 See Also optimset fminsearch optimplotx optimplotfval Neldermead 1492 Nom optimplotfval Plot the function value of an optimization algorithm optimplotfval x optimValues state Description This function creates and updates a plot of the function value depending on the number of iterations It is a predefined plot function which should be used as an option of the PlotFcns option Example In the following example we use the optimplotfval function for use with the fminsearch function function y rosenbrock x y 100x2x122 1x12 endfunction opt optimset PlotFcns optimplotfval x fval fminsearch rosenbrock 12 1 opt Authors Michael Baudin Digiteo 2009 See Also optimset fminsearch optimplotx optimplotfunccount Neldermead 1493 Nom optimplotx Plot the value of the parameters of an optimization algorithm optimplotx x optimValues state Description This function creates and updates a plot of the value of the parameters depending on the number of iterations It is a predefined plot function which should be used as an option of the PlotFcns option Example In the following example we use the optimplotx function for use with the fminsearch function function y rosenbrock x y 100x2x122 1x12 endfunction opt optimset PlotFcns optimplotx x fval fminsearch rosenbrock 12 1 opt Authors Michael Baudin Digiteo 2009 See Also optimset fminsearch optimplotfval optimplotfunccount Neldermead 1494 Nom optimset Configures and returns an optimization data structure options optimset options optimset funname options optimset key value options optimset key1 value1 key2 value2 options optimset oldoptions key value Description This function creates or updates a data structure which can be used on modify the behaviour of opti mization methods The goal of this function is to manage the options data structure which is a struct with a set of fields for example MaxFunEvals MaxIter etc The user can create a new struc ture with empty fields or create a new structure with default fields which correspond to a particular algorithm The user can also configure each field and set it to a particular value Finally the user pass the structure to an optimization function so that the algorithm uses the options configured by the user In the following we analyse the various ways to call the optimset function The following calling sequence options optimset creates a new data structure where the fields have been set to the empty matrix ie The following calling sequence options optimset funname creates a new data structure where the default parameters which correspond to the funname function have been set For example options optimset fminsearch returns a new data structure where the default parameters which correspond to the fminsearch func tion have been set The following calling sequence options optimset oldoptions key value creates a new data structure where all fields from the oldoptions structure have been copied except the field corresponding to the key which has been set to value Parameters key a string The following keys are available Neldermead 1495 Display FunValCheck MaxFunEvals MaxIter OutputFcn PlotFcns value the value of the parameter options A struct which contains the following fields By default all fields are empty Specific settings are associated with a particular function name optionsDisplay The verbose level The default value is notify The following is a list of available verbose levels optionsDisplay off the algorithm displays no message at all optionsDisplay notify the algorithm displays message if the termination criteria is not reached at the end of the optimization This may happen if the maximum number of iterations of the maximum number of function evaluations is reached and warns the user of a convergence problem optionsDisplay final the algorithm displays a message at the end of the optimization showing the number of iterations the number of function evaluations and the status of the optimization This option includes the messages generated by the notify option ie warns in case of a convergence problem optionsDisplay iter the algorithm displays a oneline message at each iteration This option includes the messages generated by the notify option ie warns in case of a con vergence problem It also includes the message generated by the final option optionsFunValCheck A boolean to enable the checking of function values optionsMaxFunEvals The maximum number of evaluations of the cost function optionsMaxIter The maximum number of iterations optionsOutputFcn A function which is called at each iteration to print out intermediate state of the optimization algorithm for example into a log file optionsPlotFcns A function which is called at each iteration to plot the intermediate state of the optimization algorithm for example into a 2D graphic optionsTolFun The absolute tolerance on function value optionsTolX The absolute tolerance on the variable x Neldermead 1496 funname A string containing the name of an optimization function which takes the options structure as input argument Currently the only possible value is fminsearch Design Most optimization algorithms require many algorithmic parameters such as the number of iterations or the number of function evaluations If these parameters are given to the optimization function as input parameters this forces both the user and the developper to manage many input parameters For example the optim function provides more than 20 input arguments The goal of the optimset function is to simplify the management of input arguments by gathering all the parameters into a single data structure While the current implementation of the optimset function only supports the fminsearch function it is designed to be extended to as many optimization function as required Because all optimization algorithms do not require the same parameters the data structure aims at remaining flexible But most of the time most parameters are the same from algorithm to algorithm for example the tolerance parameters which drive the termination criteria are often the same even if the termination criteria itself is not the same Output and plot functions The OutputFcn and PlotFcns options accept as argument a function or a list of functions In the client optimization algorithm this output or plot function is called back once per iteration It can be used by the user to display a message in the console write into a file etc The output or plot function is expected to have the following definition function myfun x optimValues state where the input parameters are x the current point optimValues a struct which contains the following fields optimValuesfunccount the number of function evaluations optimValuesfval the best function value optimValuesiteration the current iteration number optimValuesprocedure the type of step performed This string depends on the specific algorithm see fminsearch for details state the state of the algorithm The following states are available init iter and done init when the algorithm is initializing iter when the algorithm is performing iterations done when the algorithm is terminated Example 1 In the following example we create an empty optimization structure Neldermead 1497 op optimset Example 2 In the following example we create an optimization structure with all fields set to specific settings op optimset Displayiter FunValCheckon MaxFunEvals100 MaxIter110 OutputFcnmyoutputfun PlotFcnsmyplotfun TolFun1e12 TolX1e13 Example 3 In the following example we create an optimization structure with all fields set to the default settings for the fminsearch optimization function op optimset fminsearch Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 See Also optimget Capítulo 3 Optimization base Optimization base 1499 Nom optimbase Provides an abstract class for a general optimization component newobj optimbasenew this optimbasedestroy this this optimbaseconfigure thiskeyvalue value optimbasecget thiskey value optimbaseget thiskey this optimbaseset this key value this isok optimbasecheckbounds this opt isok optimbasecheckx0 this this optimbasedisplay this this f index data optimbasefunction this x index data this f c index data optimbasefunction this x index data this f g index data optimbasefunction this x index data this f g c gc index data optimbasefunction this x index data this hasbounds optimbasehasbounds this this hascons optimbasehasconstraints this this hasnlcons optimbasehasnlcons this value optimbasehistget this iter key this optimbasehistset this iter key value this optimbaseincriter this this isfeasible optimbaseisfeasible this x this optimbaselog thismsg optimbaseoutputcmd this state data data optimbaseoutstruct this this p optimbaseproj2bnds this x this optimbasestoplog this msg this terminate status optimbaseterminate this previousfopt currentfopt previousxopt currentxopt this optimbasecheckcostfun this this isfeasible optimbaseisinbounds this x this isfeasible optimbaseisinnonlinconst this x Purpose The goal of this component is to provide a building block for optimization methods The goal is to pro vide a building block for a large class of specialized optimization methods This component manages the number of variables the minimum and maximum bounds the number of non linear inequality constraints the cost function the logging system various termination criteria etc Design This toolbox is designed with Oriented Object ideas in mind Optimization base 1500 Features The following is a list of features the Optimbase toolbox currently provides Manage cost function optionnal additionnal argument direct communication of the task to perform cost function or inequality constraints Manage various termination criteria including maximum number of iterations tolerance on function value relative or absolute tolerance on x relative or absolute maximum number of evaluations of cost function Manage the history of the convergence including history of function values history of optimum point Provide query features for the status of the optimization process the number of iterations the number of function evaluations function value at initial point function value at optimal point the optimum parameters etc Description This set of commands allows to manage an abstract optimization method The goal is to provide a building block for a large class of specialized optimization methods This component manages the number of variables the minimum and maximum bounds the number of non linear inequality cons traints the logging system various termination criteria the cost function etc The optimization problem to solve is the following min fx li xi hi i 1n gix 0 i 1nbineq where n number of variables Optimization base 1501 nbineq number of inequality constraints Functions The following functions are available newobj optimbasenew Creates a new optimization object newobj The new object this optimbasedestroy this Destroy the given object this The current object this optimbaseconfigure thiskeyvalue Configure the current object with the given value for the given key this The current object key the key to configure The following keys are available verbose set to 1 to enable verbose logging default is 0 verbosetermination set to 1 to enable verbose termination logging default is 0 x0 the initial guess maxfunevals the maximum number of function evalutations default is 100 If this criteria is triggered the status of the optimization is set to maxfuneval maxiter the maximum number of iterations default is 100 If this criteria is triggered the status of the optimization is set to maxiter tolfunabsolute the absolute tolerance for the function value default is 00 tolfunrelative the relative tolerance for the function value default is eps tolfunmethod the method used for the tolerance on function value in the termination criteria The following values are available t f default is f If this criteria is triggered the status of the optimization is set to tolf tolxabsolute the absolute tolerance on x default is 00 tolxrelative the relative tolerance on x default is eps Optimization base 1502 tolxmethod the method used for the tolerance on x in the termination criteria The following values are available t f default is t If this criteria is triggered the status of the optimization is set to tolx function the objective function which computes the value of the cost and the non linear constra ints if any See below for the details of the communication between the optimization system and the cost function costfargument an additionnal argument passed to the cost function outputcommand a command which is called back for output See below for the details of the communication between the optimization system and the output command function outputcommandarg an additionnal argument passed to the output command numberofvariables the number of variables to optimize default is 0 storehistory set to t to enable the history storing default is f boundsmin the minimum bounds for the parameters as an array of values default is empty ie there are no bounds boundsmax the maximum bounds for the parameters as an array of values default is empty ie there are no bounds nbineqconst the number of inequality constraints default is 0 logfile the name of the log file withderivatives set to t if the algorithm uses derivatives Default is f value the value value optimbasecget thiskey Get the value for the given key If the key is unknown generates an error this The current object key the name of the key to quiery The list of available keys is the same as for the optimbaseconfigure function Optimization base 1503 this isok optimbasecheckbounds this Check if the bounds are consistent and puts an error message if not One could generate an error but errors are not testable with the current system this The current object opt isok optimbasecheckx0 this Returns T if the initial guess is consistent with the bounds and the non linear inequality cons traints if any this The current object this optimbasedisplay this Display the current settings in the console this The current object this f index data optimbasefunction this x index data this f c index data optimbasefunction this x index data this f g index data optimbasefunction this x index data this f g c gc index data optimbasefunction this x index data Call the cost function and return the required results If a cost function additionnal argument is defined in current object pass it to the function as the last argument See below for details this The current object x the current point as a column vector index what value to compute See below in the section Cost function for details on this index f the value of the cost function g the gradient of the cost function c the nonlinear positive inequality constraints gc the gradient of the nonlinear positive inequality constraints data an optionnal userprovided argument this optimbaseset this key value Set the value for the given key If the key is unknown generates an error this The current object Optimization base 1504 key the key to set The following keys are available funevals the number of function evaluations iterations the number of iterations xopt the x optimum fopt the optimum cost function value historyxopt an array with nbiter values containing the history of x during the iterations This array is available after optimization if the history storing was enabled with the storehistory option historyfopt an array with nbiter values containing the history of the function value during the ite rations This array is available after optimization if the history storing was enabled with the storehistory option fx0 the function value for the initial guess status a string containing the status of the optimization value the value to set value optimbaseget thiskey Get the value for the given key If the key is unknown generates an error This command corres ponds with options which are not available directly to the optimbaseconfigure function but are computed internally this The current object key the name of the key to quiery The list of available keys is the same as the optimbaseset function this hasbounds optimbasehasbounds this Returns T if current problem has bounds this The current object this hascons optimbasehasconstraints this Returns T if current problem has bounds constraints linear constraints or non linear constraints this The current object Optimization base 1505 this hasnlcons optimbasehasnlcons this Returns T if current problem has non linear constraints this The current object this optimbasehistset this iter key value Set the history value at given iteration for the given key If the key is unknown generates an error this The current object iter the iteration number to get key the name of the key to quiery The list of available keys is the following xopt fopt value the value to set value optimbasehistget this iter key Returns the history value at the given iteration number for the given key If the key is unknown generates an error this The current object iter the iteration number to get key the name of the key to quiery The list of available keys is the same as the optimbasehistset function this optimbaseincriter this Increments the number of iterations this The current object this isfeasible optimbaseisfeasible this x Returns 1 if the given point satisfies bounds constraints and inequality constraints Returns 0 if the given point is not in the bounds Returns 1 if the given point does not satisfies inequality constraints this The current object x the current point this optimbaselog thismsg If verbose logging is enabled prints the given message in the console If verbose logging is di sabled does nothing If the lofgile option has been set writes the message into the file instead of writing to the console If the console is too slow writing into a file can be a solution since it is very fast Optimization base 1506 this The current object msg the message to print optimbaseoutputcmd this state data Calls back users output command this The current object data optimbaseoutstruct this Returns a tlist with basic optimization fields This tlist is suitable for use as an input argument of the output function This tlist may be enriched by children specialize optimization methods this The current object this p optimbaseproj2bnds this x Returns a point which is the projection of the given point into the bounds this The current object x the current point this optimbasestoplog this msg Prints the given stopping rule message if verbose termination is enabled If verbose termination is disabled does nothing this The current object msg the message to print this terminate status optimbaseterminate this previousfopt currentfopt previousxopt currentxopt Returns 1 if the algorithm terminates Returns 0 if the algorithm must continue If the verbose termination option is enabled messages are printed detailing the termination intermediate steps The optimbaseterminate function takes into account the number of iterations the number of eva luations of the cost function the tolerance on x and the tolerance on f See below in the section Termination for more details this The current object previousfopt the previous value of the cost function currentfopt the current value of the cost function previousxopt the previous x optimum currentxopt the current x optimum Optimization base 1507 terminate t if the algorithm must terminate f if the algorithm must continue status if terminate t the detailed status of the termination as a string If terminate f the status is continue The following status are available maxiter the maximum number of iterations provided by the maxiter option is reached maxfuneval the maximum number of function evaluations provided by the maxfunevals option is reached tolf the tolerance on the function value is reached This status is associated with the tolfun method tolfunabsolute and tolfunrelative options tolx the tolerance on x is reached This status is associated with the tolxmethod tolxabsolute and tolxrelative options this optimbasecheckcostfun this Check that the cost function is correctly connected Generate an error if there is one Takes into account for the cost function at the initial guess x0 only Checks that all values of the index argument are valid If there are nonlinear constraints check that the matrix has the correct shape This function requires at least one call to the cost function to make the necessary checks this The current object this isfeasible optimbaseisinbounds this x Returns isfeasible t if the given point satisfies bounds constraints Returns isfeasible f if the given point is not in the bounds this The current object isfeasible a boolean this isfeasible optimbaseisinnonlinconst this x Returns isfeasible t if the given point satisfies the nonlinear constraints Returns isfeasible f if the given point does not satisfy the nonlinear constraints this The current object isfeasible a boolean The cost function The function option allows to configure the cost function The cost function is used depending on the context to compute the cost the nonlinear inequality positive constraints the gradient of the function and the gradient of the nonlinear inequality constraints The cost function can also be used to produce outputs and to terminate an optimization algorithm Optimization base 1508 In the following the variables are f scalar the objective g row matrix the gradient of the objective c row matrix the constraints gc matrix the gradient of the constraints Each calling sequence of the optimbasefunction function corresponds to a specific calling sequence of the userprovided cost function If the withderivatives is false and there is no nonlinear constraint the calling sequence is this f index optimbasefunction this x index which corresponds to the cost functions function f index costf x index function f index data costf x index data if there is a costfargument If the withderivatives is false and there are nonlinear constraints the calling sequence is this f c index optimbasefunction this x index which corresponds to the cost functions function f c index costf x index function f c index data costf x index data if there is a costfargument If the withderivatives is true and there is no nonlinear constraint the calling sequence is this f g index optimbasefunction this x index which corresponds to the cost functions function f g index costf x index function f g index data costf x index data if there is a costfargument If the withderivatives is true and there is are nonlinear constraints the calling sequence is this f g c gc index optimbasefunction this x index which corresponds to the cost functions function f g c gc index costf x index Optimization base 1509 function f g c gc index data costf x index data if there is a costfargument Each calling sequence corresponds to a particular class of algorithms including for example unconstrained derivativefree algorithms nonlinearily constrained derivativefree algorithms unconstrained derivativebased algorithms nonlinearilyconstrained derivativebased algorithms etc The current component is designed in order to be able to handle many situations The index input parameter has the following meaning index 1 nothing is to be computed the user may display messages for example index 2 compute f index 3 compute g index 4 compute f and g index 5 compute c index 6 compute f and c index 7 compute f g c and gc The index output parameter has the following meaning index 0 everything is fine index 0 the optimization must stop index 0 one function could not be avaluated The output function The option outputcommand allows to configure a command which is called back at the start of the optimization at each iteration and at the end of the optimization The output function must have the following header function outputcmdstate data myobj where state a string representing the current state of the algorithm Available values are init iter done data a tlist containing at least the following entries x the current optimum Optimization base 1510 fval the current function value iteration the current iteration index funccount the number of function evaluations myobj a userdefined parameter This input parameter is defined with the outputcommandarg option The output function may be used when debugging the specialized optimization algorithm so that a verbose logging is produced It may also be used to write one or several report files in a specialized format ASCII LaTeX Excel Hdf5 etc The userdefined parameter may be used in that case to store file names or logging options The data tlist argument may contain more fields than the current presented ones These additionnal fields may contain values which are specific to the specialized algorithm such as the simplex in a NelderMead method the gradient of the cost function in a BFGS method etc Termination The current component takes into account for several generic termination criterias Specialized ter mination criterias should be implemented in specialized optimization algorithms by calling the optimbasetermination function and adding external criterias rather than by modification of this func tion The optimbaseterminate function uses a set of rules to compute if the termination occurs which leads to an optimization status which is equal to one of the following continue maxiter maxfunevals tolf tolx The set of rules is the following By default the status is continue and the terminate flag is 0 The number of iterations is examined and compared to the maxiter option if the following con dition iterations maxiter is true then the status is set to maxiter and terminate is set to t The number of function evaluations and compared to the maxfunevals option is examined if the following condition funevals maxfunevals is true then the status is set to maxfuneval and terminate is set to t The tolerance on function value is examined depending on the value of the tolfunmethod disabled then the tolerance on f is just skipped enabled if the following condition Optimization base 1511 abscurrentfopt tolfunrelative abspreviousfopt tolfunabsolute is true then the status is set to tolf and terminate is set to t The relative termination criteria on the function value works well if the function value at optimum is near zero In that case the function value at initial guess fx0 may be used as previousfopt The absolute termination criteria on the function value works if the user has an accurate idea of the optimum function value The tolerance on x is examined depending on the value of the tolxmethod f then the tolerance on x is just skipped t if the following condition normcurrentxopt previousxopt tolxrelative normcurrentxopt tolxabsolute is true then the status is set to tolx and terminate is set to t The relative termination criteria on x works well if x at optimum is different from zero In that case the condition measures the distance between two iterates The absolute termination criteria on x works if the user has an accurate idea of the scale of the optimum x If the optimum x is near 0 the relative tolerance will not work and the absolute tolerance is more appropriate Example Setting up an optimization In the following example one searches the minimum of the 2D Rosenbrock function One begins by defining the function rosenbrock which computes the Rosenbrock function The traditionnal initial guess 12 10 is used The initial simplex is computed along the axes with a length equal to 01 The NelderMead algorithm with variable simplex size is used The verbose mode is enabled so that messages are generated during the algorithm After the optimization is performed the optimum is retrieved with quiery features function f index rosenbrock x index f 100x2x122 1x12 endfunction opt optimbasenew opt optimbaseconfigureoptnumberofvariables2 nbvar optimbasecgetoptnumberofvariables opt optimbaseconfigureoptfunctionrosenbrock this f index optimbasefunction opt 00 00 index opt optimbasedestroyopt Authors Michael Baudin 20082009 Optimization base 1512 TODO manage equality constraints manage linear constraints manage quadratic objective manage linear objective manage linear inequality constraints manage non linear equality constraints manage linear equality constraints rename outputcommand to outputfunction 1513 Capítulo 4 Optimization simplex Optimization simplex 1514 Nom optimsimplex Manage a simplex with arbitrary number of points newobj data optimsimplexnew coords fun data newobj data optimsimplexnew axes x0 fun len data newobj data optimsimplexnew spendley x0 fun len data newobj data optimsimplexnew pfeffer x0 fun deltausual deltazero data newobj data optimsimplexnew randbounds x0 fun boundsmin boundsmax nbve data newobj data optimsimplexnew oriented simplex0 fun data this optimsimplexdestroy this this optimsimplexsetall this simplex this optimsimplexsetallfv this fv this optimsimplexsetallx this x this optimsimplexsetfv this ive fv this optimsimplexsetn this n this optimsimplexsetnbve this nbve this optimsimplexsetve this ive fv x this optimsimplexsetx this ive x simplex optimsimplexgetall this fv optimsimplexgetallfv this x optimsimplexgetallx this fv optimsimplexgetfv this ive n optimsimplexgetn this nbve optimsimplexgetnbve this vertex optimsimplexgetve this ive x optimsimplexgetx this ive sicenter optimsimplexcenter this optimsimplexcheck this this data optimsimplexcomputefv this fun data df optimsimplexdeltafv this dfm optimsimplexdeltafvmax this m optimsimplexdirmat this m optimsimplexfvmean this sd optimsimplexfvstdev this v optimsimplexfvvariance this g data optimsimplexgradientfv this fun method data optimsimplexprint this r data optimsimplexreflect this fun data this data optimsimplexshrink this fun sigma data ssize optimsimplexsize this method this optimsimplexsort this str optimsimplextostring this cen optimsimplexxbar this iexcl Purpose The goal of this component is to provide a building block for optimization algorithms based on a simplex The optimsimplex package may be used in the following optimization methods the Spendley et al simplex method the NelderMead method the Box algorithm for constrained optimization the multidimensional search by Virginia Torczon etc Optimization simplex 1515 Design This toolbox is designed with Oriented Object ideas in mind Features The following is a list of features the NelderMead prototype algorithm currently provides Manage various simplex initializations initial simplex given by user initial simplex computed with a length and along the coordinate axes initial regular simplex computed with Spendley et al formula initial simplex computed by a small perturbation around the initial guess point initial simplex computed from randomized bounds sort the vertices by increasing function values compute the standard deviation of the function values in the simplex compute the simplex gradient with forward or centered differences shrink the simplex toward the best vertex etc Description This set of commands allows to manage a simplex made of kn1 points in a ndimensional space This component is the building block for a class of direct search optimization methods such as the NelderMead algorithm or Torczons MultiDimensionnal Search A simplex is designed as a collection of kn1 vertices Each vertex is made of a point and a function value at that point The simplex can be created with various shapes It can be configured and quieried at will The simplex can also be reflected or shrinked The simplex gradient can be computed with a order 1 forward formula and with a order 2 centered formula The optimsimplexnew function allows to create a simplex If vertices coordinates are gi ven there are registered in the simplex If a function is provided it is evaluated at each vertex The optimsimplexdestroy function destroys the object and frees internal me mory Several functions allow to create a simplex with special shapes including axesbyaxes optimsimplexaxes regular optimsimplexspendley randomized bounds simplex with arbitrary nbve vertices optimsimplexrandbounds and an heuristical small variation around a given point optimsimplexpfeffer In the following functions simplices and vertices are depending on the functions either input or output arguments The following general principle have been used to manage the storing of the coordinates of the points The vertices are stored row by row while the coordinates are stored column by column This implies the following rules The coordinates of a vertex are stored in a row vector ie a 1 x n matrix where n is the dimension of the space Optimization simplex 1516 The function values are stored in a column vector ie a nbve x 1 matrix where nbve is the number of vertices Functions The following functions are available newobj optimsimplexnew Creates a new simplex object All input arguments are optional If no input argument is provided returns an empty simplex object The following is a complete list of available calling sequences newobj optimsimplexnew coords newobj optimsimplexnew coords fun newobj data optimsimplexnew coords fun data newobj The new object coords optional matrix of point coordinates in the simplex The coords matrix is expected to be a nbve x n matrix where n is the dimension of the space and nbve is the number of vertices in the simplex with nbve n1 fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x where x is a row vector data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexnew axes x0 Creates a new simplex object so that it is computed axis by axis with the given length The following is a complete list of available calling sequences this optimsimplexnew axes x0 fun this optimsimplexnew axes x0 fun len Optimization simplex 1517 this data optimsimplexnew axes x0 fun len data this The current simplex object x0 the initial point as a row vector fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x len optional the length of the simplex The default length is 10 If length is a value that unique length is used in all directions If length is a vector with n values each length is used with the corresponding direction data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexnew pfeffer x0 Creates a new simplex so that it is computed from Pfeffers method ie a relative delta for non zero values and an absolute delta for zero values The following is a complete list of available calling sequences this optimsimplexnew pfeffer x0 fun this optimsimplexnew pfeffer x0 fun deltausual this optimsimplexnew pfeffer x0 fun deltausual deltazero this data optimsimplexnew pfeffer x0 fun deltausual deltazero data this The current simplex object x0 the initial point as a row vector fun optional the function to compute at vertices The function is expected to have the following input and output arguments Optimization simplex 1518 function y myfunction x deltausual optional the absolute delta for nonzero values The default value is 005 deltazero optional the absolute delta for zero values The default value is 00075 data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexnew randbounds x0 fun boundsmin boundsmax nbpoints Creates a new simplex so that it is computed by taking the bounds into account with random scaling The number of vertices in the simplex is arbitrary The following is a complete list of available calling sequences this data optimsimplexnew randbounds x0 fun boundsmin boundsmax nbpoints data this The current simplex object x0 the initial point as a row vector It is the first vertex in the simplex fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x boundsmin array of minimum bounds boundsmax array of maximum bounds Each component ix 1n of the vertex k 2nbve is computed from the formula x k ix boundsmin ix rand boundsmax ix boundsmin ix Optimization simplex 1519 nbpoints total number of points in the simplex data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexnew spendley x0 Creates a new simplex so that it is computed from Spendleys et al method ie a regular simplex made of nbve n1 vertices The following is a complete list of available calling sequences this optimsimplexnew spendley x0 fun this optimsimplexnew spendley x0 fun len this data optimsimplexnew spendley x0 fun len data this The current simplex object x0 the initial point as a row vector fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x len optional the length of the simplex The default length is 10 data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called Optimization simplex 1520 this optimsimplexnew oriented simplex0 fun Returns a new oriented simplex in sorted order The new simplex has the same sigma length of the base simplex but is oriented depending on the function value The created simplex may be used as Kelley suggests for a restart of NelderMead algorithm The following is a complete list of available calling sequences this data optimsimplexnew oriented simplex0 fun data this The current simplex object simplex0 the base simplex fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexdestroy this Destroy the given object this The current simplex object this optimsimplexsetall this simplex Set all the coordinates and and the function values of all the vertices this The current simplex object simplex the simplex to set The given matrix is expected to be a nbve x n1 matrix where n is the dimension of the space nbve is the number of vertices and with the following content where the data is organized by row with function value first and x coordinates simplexk1 is the function value of the vertex k with k 1 nbve Optimization simplex 1521 simplexk2n1 is the coordinates of the vertex k with k 1 nbve this optimsimplexsetallfv this fv Set all the function values of all the vertices The vertex k is expected to be stored in fvk with k 1 nbve The fv input argument is expected to be a row vector this The current simplex object fv the array of function values this optimsimplexsetallx this x Set all the coordinates of all the vertices The vertex k is expected to be stored in xk1n with k 1 nbve this The current simplex object x the coordinates of the vertices this optimsimplexsetfv this ive fv Set the function value at given index and returns an updated simplex this The current simplex object ive vertex index fv the function value this optimsimplexsetn this n Set the dimension of the space of the simplex this The current simplex object n the dimension this optimsimplexsetnbve this nbve Set the number of vertices of the simplex this The current simplex object nbve the number of vertices this optimsimplexsetve this ive fv x Sets the coordinates of the vertex and the function value at given index in the current simplex this The current simplex object ive the vertex index fv the function value Optimization simplex 1522 x the coordinates of the point as a row vector this optimsimplexsetx this ive x Set the coordinates of the vertex at given index as a row vector into the current simplex this The current simplex object ive the vertex index x the coordinates of the point as a row vector simplex optimsimplexgetall this Returns all the coordinates of all the vertices and the function values in the same matrix this The current simplex object simplex the simplex data The simplex matrix has size nbve x n1 and is organized by row by row as follows simplexk1 is the function value of the vertex k with k 1 nbve simplexk2n1 is the coordinates of the vertex k with k 1 nbve fv optimsimplexgetallfv this Returns all the function values of all the vertices as a row vector this The current simplex object fv The array of function values The function value of vertex k is stored in fvk with k 1 nbve x optimsimplexgetallx this Returns all the coordinates of all the vertices this The current simplex object x the coordinates The vertex k is stored in xk1n with k 1 nbve fv optimsimplexgetfv this ive Returns the function value at given index this The current simplex object ive the vertex index n optimsimplexgetn this Returns the dimension of the space of the simplex Optimization simplex 1523 this The current simplex object nbve optimsimplexgetnbve this Returns the number of vertices in the simplex this The current simplex object vertex optimsimplexgetve this ive Returns the vertex at given index as a tlist with fields n x and fv this The current simplex object ive the vertex index x optimsimplexgetx this ive Returns the coordinates of the vertex at given index as a row vector this The current simplex object ive the vertex index sicenter optimsimplexcenter this Returns the center of the given simplex this The current simplex object optimsimplexcheck this Check the consistency of the internal data Generates an error if necessary this The current simplex object this data optimsimplexcomputefv this fun data Set the values of the function at vertices points this The current simplex object fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data Optimization simplex 1524 The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called df optimsimplexdeltafv this Returns the vector of difference of function values with respect to the function value at vertex 1 this The current simplex object dfm optimsimplexdeltafvmax this Returns the difference of function value between the high and the low vertices It is expected that the vertex 1 is associated with the smallest function value and that the vertex nbve is associated with the highest function value Since vertices are ordered the high is greater than the low this The current simplex object m optimsimplexdirmat this Returns the n x n matrix of simplex directions ie the matrix of differences of vertices coordinates with respect to the vertex 1 this The current simplex object m optimsimplexfvmean this Returns the mean of the function value on the simplex this The current simplex object sd optimsimplexfvstdev this Returns the standard deviation of the function value on the simplex this The current simplex object v optimsimplexfvvariance this Returns the variance of the function value on the simplex this The current simplex object g optimsimplexgradientfv this fun method Returns the simplex gradient of the function The following is a complete list of available calling sequences g optimsimplexgradientfv this fun method g data optimsimplexgradientfv this fun method data this The current simplex object fun optional the function to compute at vertices The function is expected to have the following input and output arguments Optimization simplex 1525 function y myfunction x method optional the method to use to compute the simplex gradient Two methods are available forward or centered The forward method uses the current simplex to compute the simplex gradient The centered method creates an intermediate reflected simplex and computes the average If not provided the default method is forward data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called optimsimplexprint this Display the current simplex with coordinates and function values this The current simplex object r data optimsimplexreflect this fun data Returns a new simplex by reflexion of current simplex by reflection with respect to the first vertex in the simplex This move is used in the centered simplex gradient this The current simplex object fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing Optimization simplex 1526 the function value This feature may be used for example to count the number of times that the function has been called this data optimsimplexshrink this fun sigma data Shrink the simplex with given coefficient sigma and returns an updated simplex The shrink is performed with respect to the first point in the simplex this The current simplex object fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x sigma optional the shrinkage coefficient The default value is 05 data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called ssize optimsimplexsize this method Returns the size of the simplex this The current simplex object method optional the method to use to compute the size The available methods are the following sigmaplus this is the default The sigmamplus size is the maximum 2norm length of the vector from each vertex to the first vertex It requires one loop over the vertices sigmaminus The sigmaminus size is the minimum 2norm length of the vector from each vertex to the first vertex It requires one loop over the vertices Nash The Nash size is the sum of the norm of the norm1 length of the vector from the given vertex to the first vertex It requires one loop over the vertices Optimization simplex 1527 diameter The diameter is the maximum norm2 length of all the edges of the simplex It requires 2 nested loops over the vertices this optimsimplexsort this Sorts the simplex with increasing function value order so that the smallest function value is at vertex 1 this The current simplex object str optimsimplextostring this Returns the current simplex as a string this The current simplex object cen optimsimplexxbar this iexcl Returns the center of n vertices by excluding the vertex with index iexcl Returns a row vector this The current simplex object iexcl the index of the vertex to exclude in center computation The default value of iexcl is the number of vertices in that case if the simplex is sorted in increasing function value order the worst vertex is excluded Example Creating a simplex with given vertices coor dinates In the following example one creates a simplex with known vertices coordinates The function values at the vertices are unset coords 0 0 1 0 0 1 s1 optimsimplexnew coords computed optimsimplexgetallx s1 computed optimsimplexgetns1 computed optimsimplexgetnbve s1 s1 optimsimplexdestroys1 Example Creating a simplex with randomized bounds In the following example one creates a simplex with in the 2D domain 5 52 with 12 10 as the first vertex One uses the randomized bounds method to generate a simplex with 5 vertices The function takes an additionnal argument mystuff which is counts the number of times the function is called After the creation of the simplex the value of mystuffnb is 5 which is the expected result because there is one function call by vertex Optimization simplex 1528 function y rosenbrock x y 100x2x1221x12 endfunction function y mystuff mycostf x mystuff y rosenbrockx mystuffnb mystuffnb 1 endfunction mystuff tlistTMYSTUFFnb mystuffnb 0 s1 optimsimplexnew s1 mystuff optimsimplexrandbounds s1 x0 12 10 fun mycostf boundsmin 50 50 boundsmax 50 50 nbve5 data mystuff mprintfFunction evaluations d mystuffnb s1 optimsimplexdestroy s1 Initial simplex strategies In this section we analyse the various initial simplex which are provided in this component It is known that direct search methods based on simplex designs are very sensitive to the initial simplex This is why the current component provides various ways to create such an initial simplex The first historical simplexbased algorithm is the one presented in Sequential Application of Sim plex Designs in Optimisation and Evolutionary Operation by W Spendley G R Hext and F R Himsworth The spendley simplex creates the regular simplex which is presented in the paper The randbounds simplex is due to MJ Box in A New Method of Constrained Optimization and a Comparison With Other Methods Pfeffers method is an heuristic which is presented in Global Optimization Of LennardJones Atomic Clusters by Ellen Fan It is due to L Pfeffer at Stanford and it is used in fminsearch TODO implement reflection and expansion as in multidimensional search by Torczon turn optimsimplexreflect into a proper constructor ie an option of the the optimsimplexnew function Another possibility is to reflect in place as in the optimsimplexshrink function but in this case we must provide a copy constructor from current simplex before reflecting it Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 Bibliography Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation Spendley W and Hext G R and Himsworth F R American Statistical Association and American Society for Quality 1962 A Simplex Method for Function Minimization Nelder J A and Mead R The Computer Journal January 1965 308313 Optimization simplex 1529 A New Method of Constrained Optimization and a Comparison With Other Methods M J Box The Computer Journal 1965 814252 1965 by British Computer Society Iterative Methods for Optimization CT Kelley 1999 Chapter 6 section 62 Compact Numerical Methods For Computers Linear Algebra and Function Minimization JC Nash 1990 Chapter 14 Direct Search Methods Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation W Spend ley G R Hext F R Himsworth Technometrics Vol 4 No 4 Nov 1962 pp 441461 Section 31 A New Method of Constrained Optimization and a Comparison With Other Methods M J Box The Computer Journal 1965 814252 1965 by British Computer Society Detection and Remediation of Stagnation in the NelderMead Algorithm Using a Sufficient Decrease Condition SIAM J on Optimization Kelley C T 1999 MultiDirectional Search A Direct Search Algorithm for Parallel Machines by E Boyd Kenneth W Kennedy Richard A Tapia Virginia Joanne Torczon Virginia Joanne Torczon 1989 Phd Thesis Rice University Grid Restrained NelderMead Algorithm Árpád Brmen Janez Puhan Tadej Tuma Computational Optimization and Applications Volume 34 Issue 3 July 2006 Pages 359 375 A convergent variant of the NelderMead algorithm C J Price I D Coope D Byatt Journal of Optimization Theory and Applications Volume 113 Issue 1 April 2002 Pages 5 19 Global Optimization Of LennardJones Atomic Clusters Ellen Fan Thesis February 26 2002 Mc Master University 1530 Name NDcost generic external for optim computing gradient using finite differences fgindNDcostxindfunvarargin Parameters x real vector or matrix ind integer parameter see optim fun Scilab function with calling sequence Ffunxvarargin varargin may be use to pass pa rameters p1pn f criterion value at point x see optim g gradient value at point x see optim Description This function can be used as an external for optim to minimize problem where gradient is too com plicated to be programmed only the function fun which computes the criterion is required This function should be used as follow fxoptgoptoptimlistNDcostfunp1pnx0 Examples example 1 a simple one function to minimize function frosenbrockxvarargin pvarargin1 f1sum px2x1122 1x22 endfunction x01234 fxoptgoptoptimlistNDcostrosenbrock200x0 example 2 This example by Rainer von Seggern shows a quick way to identify the parameters of a linear differential equation with the help of scilab The model is a simple damped linear oscillator xt c xt k xt 0 and we write it as a system of two differential equations of first order with y1 x and y2 x dy1dt y2 dy2dt cy2 ky1 We suppose to have m measurements of x that is y1 at different times NDcost 1531 tobs1 tobsm called xobs1 xobsm in this example these measuresments will be simulated and we want to identify the parameters c and k by minimizing the sum of squared errors between xobs and y1tobsp This method is not the most efficient but it is easy to implement function dy DEQtyp The rhs of our first order differential equation system c p1kp2 dyy2cy2ky1 endfunction function yuNp t t0 y0 Numerical solution obtained with ode In this linear case an exact analytic solution can easily be found but ode would also work for any system Note the ode output must be an approximation of the solution at times given in the vector tt1t y odey0t0tlistDEQp endfunction function r costfuncp tobs xobs t0 y0 This is the function to be minimized that is the sum of the squared errors between what gives the model and the measuments sol uNp tobs t0 y0 e sol1 xobs r sumee endfunction Data y0 100 t0 0 Initial conditions y0 for initial time t0 T 30 Final time for the measurements Here we simulate experimental data from which the parameters should be identified pe 023 Exact parameters m 80 tobs linspacet02Tm Observation times Noise each measurement is supposed to have a gaussian random error of mean 0 and std deviation proportional to the magnitude of the value sigmaxexacttobsi sigma 01 yexact uNpe tobs t0 y0 xobs yexact1 grand1mnor0 sigmaabsyexact1 Initial guess parameters p0 05 5 The value of the cost function before optimization cost0 costfuncp0 tobs xobs t0 y0 mprintf r The value of the cost function before optimization g r Solution with optim costoptpoptoptimlistNDcostcostfunc tobs xobs t0 y0p0 ar40401e3 mprintf r The value of the cost function after optimization gcostopt mprintf r The identified values of the parameters c g k g r popt1popt2 NDcost 1532 A small plot t linspace0T400 y uNpopt t t0 y0 clf plot2dty1style5 plot2dtobsxobs1style5 legendmodelmeasurements xtitleLeast square fit to identify ode parameters See Also optim external derivative 1533 Name aplat Flattens a list lfind aplatlr Parameters l a list r an optional flat list lf a flat list a single hierachical level ind a list each entry give the path of the corresponding lf entry in the original list Description Creates a flat list built with the initial l list leaves and if given prepended by the r list entries Examples lfindaplatlist12list31xxxlist321 See Also recons Authors FD and SS INRIA 1534 Name datafit Parameter identification based on measured data perrdatafitimp G DGZ Wcontrp0algodf0mem workstopin Parameters imp scalar argument used to set the trace mode imp0 nothing execpt errors is reported imp1 initial and final reports imp2 adds a report per iteration imp2 add reports on linear search Warning most of these reports are written on the Scilab standard output G function descriptor eGpz e ne x 1 p np x 1 z nz x 1 DG partial of G wrt p function descriptor optional SDGpz S ne x np Z matrix z1z2zn where zi nz x 1 is the ith measurement W weighting matrix of size ne x ne optional defaut no ponderation contr bbinfbsup with binf and bsup real vectors with same dimension as p0 binf and bsup are lower and upper bounds on p p0 initial guess size np x 1 algo qn or gc or nd This string stands for quasiNewton default conjugate gradient or nondifferentiable respectively Note that nd does not accept bounds on x df0 real scalar Guessed decreasing of f at first iteration df01 is the default value mem integer number of variables used to approximate the Hessian algogc or nd Default value is around 6 stop sequence of optional parameters controlling the convergence of the algorithm stop arnap iter epsg epsf epsx ar reserved keyword for stopping rule selection defined as follows nap maximum number of calls to fun allowed iter maximum number of iterations allowed epsg threshold on gradient norm datafit 1535 epsf threshold controlling decreasing of f epsx threshold controlling variation of x This vector possibly matrix of same size as x0 can be used to scale x in reserved keyword for initialization of parameters used when fun in given as a Fortran routine see below p Column vector optimal solution found err scalar least square error Description datafit is used for fitting data to a model For a given function Gpz this function finds the best vector of parameters p for approximating Gpzi0 for a set of measurement vectors zi Vector p is found by minimizing Gpz1WGpz1Gpz2WGpz2 GpznWGpzn datafit is an improved version of fitdat Examples generate the data function yFFxpyp1xp2p3xxendfunction XY pg341214 parameter used to generate data for x013 YYFFxpg100rand5XXxend ZYX The criterion function function eGpz yz1xz2 eyFFxp endfunction Solve the problem p03510 perrdatafitGZp0 scf0clf plot2dXFFXpg5 the curve without noise plot2dXY1 the noisy data plot2dXFFXp12 the solution the gradient of the criterion function function sDGpz ap1bp2cp3yz1xz2 sxbaxx endfunction perrdatafitGDGZp0 datafit 1536 scf1clf plot2dXFFXpg5 the curve without noise plot2dXY1 the noisy data plot2dXFFXp12 the solution Add some bounds on the estimate of the parameters We want positive estimation the result will not change perrdatafitGDGZb000infinfinfp0algogc scf1clf plot2dXFFXpg5 the curve without noise plot2dXY1 the noisy data plot2dXFFXp12 the solution See Also lsqrsolve optim leastsq 1537 Name derivative approximate derivatives of a function derivativeFx J H derivativeFx h order Hform Q Parameters F a Scilab function F Rn Rm or a listFp1pk where F is a scilab function in the form yFxp1pk p1 pk being any scilab objects matrices lists x real column vector of dimension n h optional real the stepsize used in the finite difference approximations order optional integer the order of the finite difference formula used to approximate the derivatives order 12 or 4 default is order2 Hform optional string the form in which the Hessean will be returned Possible forms are Hformdefault H is a m x n2 matrix in this form the kth row of H corresponds to the Hessean of the kth component of F given as the following row vector gradFk being a row vector Hformblockmat H is a mxn x n block matrix the classic Hessean matrices of each component of F are stacked by row H H1 H2 Hm in scilab syntax Hformhypermat H is a n x n matrix for m1 and a n x n x m hypermatrix otherwise Hk is the classic Hessean matrix of the kth component of F Q optional real matrix orthogonal default is eyenn Q is added to have the possibility to remove the arbitrariness of using the canonical basis to approximate the derivatives of a function and it should be an orthogonal matrix It is not mandatory but better to recover the derivative as you need the inverse matrix and so simply Q instead of invQ J approximated Jacobian H approximated Hessian Description Numerical approximation of the first and second derivatives of a function F Rn Rm at the point x The Jacobian is computed by approximating the directional derivatives of the components of derivative 1538 F in the direction of the columns of Q For m1 vQk gradFxv DvFx The second derivatives are computed by composition of first order derivatives If H is given in its default form the Taylor series of Fx up to terms of second order is given by JHderivativeFxHformdefault JJx HHx Performances If the problem is correctly scaled increasing the accuracy reduces the total error but requires more function evaluations The following list presents the number of function evaluations required to com pute the Jacobian depending on the order of the formula and the dimension of x denoted by n order1 the number of function evaluations is n1 order2 the number of function evaluations is 2n order4 the number of function evaluations is 4n Computing the Hessian matrix requires square the number of function evaluations as detailed in the following list order1 the number of function evaluations is n12 order2 the number of function evaluations is 4n2 order4 the number of function evaluations is 16n2 Remarks The step size h must be small to get a low error but if it is too small floating point errors will dominate by cancellation As a rule of thumb do not change the default step size To work around numerical difficulties one may also change the order andor choose different orthogonal matrices Q the default is eyenn especially if the approximate derivatives are used in optimization routines All the optional arguments may also be passed as named arguments so that one can use calls in the form derivativeF x Hform hypermat derivativeF x order 4 etc Examples function yFx ysinx1x2expx2x3x1 sumx3 endfunction function yGxp ysinx1x2pexpx2x3x1 sumx3 endfunction x123 JHderivativeFxHformblockmat n3 derivative 1539 form an orthogonal matrix Q qrrandnn Test order 1 2 and 4 formulas for i124 JHderivativeFxorderiHformblockmatQQ mprintforder d i H end p1 h1e3 JHderivativelistGpxh2Hformhypermat H JHderivativelistGpxh4QQ H Taylor series example dx1e3111 JHderivativeFx Fxdx FxdxFx FxdxFxJdx FxdxFxJdx12Hdx dx A trivial example function yfxApw yxAxpxw endfunction with Jacobian and Hessean given by JxxAAp and HxAA A rand33 p rand31 w 1 x rand31 JHderivativelistfApwxh1Hformblockmat Since fx is quadratic in x approximate derivatives of order2 or 4 by finite differences should be exact for all h0 The apparent errors are caused by cancellation in the floating point operations so a big h is choosen Comparison with the exact matrices Je xAAp He AA cleanJe J cleanHe H Accuracy issues The derivative function uses the same step h whatever the direction and whatever the norm of x This may lead to a poor scaling with respect to x An accurate scaling of the step is not possible without many evaluations of the function Still the user has the possibility to compare the results produced by the derivative and the numdiff functions Indeed the numdiff function scales the step depending on the absolute value of x This scaling may produce more accurate results especially if the magnitude of x is large In the following Scilab script we compute the derivative of an univariate quadratic function The exact derivative can be computed analytically and the relative error is computed In this rather extreme case the derivative function produces no significant digits while the numdiff function produces 6 significant digits derivative 1540 Difference between derivative and numdiff when x is large function y myfunction x y xx endfunction x 1e100 fe 20 x fp derivativemyfunctionx e absfpfefe mprintfRelative error with derivative e e fp numdiffmyfunctionx e absfpfefe mprintfRelative error with numdiff e e The previous script produces the following output Relative error with derivative 1000000e000 Relative error with numdiff 7140672e006 In a practical situation we may not know what is the correct numerical derivative Still we are warned that the numerical derivatives should be used with caution in this specific case See Also numdiff derivat Authors Rainer von Seggern Bruno Pincon 1541 Name fitdat Parameter identification based on measured data perrfitdatGp0Z W pminpmax DG Parameters G Scilab function eGpz e nex1 p npx1 z nzx1 p0 initial guess size npx1 Z matrix z1z2zn where zi nzx1 is the ith measurement W weighting matrix of size nexne optional default 1 pmin lower bound on p optional size npx1 pmax upper bound on p optional size npx1 DG partial of G wrt p optional SDGpz S nexnp Description fitdat is used for fitting data to a model For a given function Gpz this function finds the best vector of parameters p for approximating Gpzi0 for a set of measurement vectors zi Vector p is found by minimizing Gpz1WGpz1Gpz2WGpz2 GpznWGpzn Examples deffyFFxyaxbcxx XY a34b12c14for x013 YYFFx100rand5XXxend ZYX deffeGpzap1bp2cp3yz1xz2eyFFx perrfitdatG3510Z xsetwindow0 clf plot2dXY1 plot2dXFFX5002 ap1bp2cp3plot2dXFFX12002 a34b12c14 deffsDGpzyz1xz2sxp2p1xx perrfitdatG3510ZDG fitdat 1542 xsetwindow1 clf plot2dXY1 plot2dXFFX5002 ap1bp2cp3plot2dXFFX12002 See Also optim datafit 1543 Name fsolve find a zero of a system of n nonlinear functions x v infofsolvex0fct fjac tol Parameters x0 real vector initial value of function argument fct external ie function or list or string fjac external ie function or list or string tol real scalar precision tolerance termination occurs when the algorithm estimates that the relative error between x and the solution is at most tol tol1d10 is the default value x real vector final value of function argument estimated zero v real vector value of function at x info termination indicator 0 improper input parameters 1 algorithm estimates that the relative error between x and the solution is at most tol 2 number of calls to fcn reached 3 tol is too small No further improvement in the approximate solution x is possible 4 iteration is not making good progress Description find a zero of a system of n nonlinear functions in n variables by a modification of the powell hybrid method Jacobian may be provided 0 fctx wrt x fct is an external This external returns vfctx given x The simplest calling sequence for fct is fsolve 1544 vfctx If fct is a character string it refers to a C or Fortran routine which must be linked to Scilab Fortran calling sequence must be fctnxviflag integer niflag double precision xnvn and C Calling sequence must be fctint n double xdouble vint iflag Incremental link is possible help link jac is an external This external returns vdfctdx x given x The simplest calling sequence for jac is vjacx If jac is a character string it refers to a to a C or Fortran routine which must be linked to Scilab calling sequences are the same as those for fct Note however that v must be a nxn array Examples A simple example with fsolve a1728b1011 deffyfsol1xyaxb deffyfsolj1xya xresfsolve100100fsol1 axresb xresfsolve100100fsol1fsolj1 axresb See SCImodulesoptimizationscigatewayfortranExfsolvef xresfsolve100100fsol1fsolj11e7 axresb For some starting points and some equations system the fsolve method can fail The fsolve method is a local search method So to have a good chance to find a solution to your equations system you must ship a good starting point to fsolve Here is an example on which fsolve can fail Another example with fsolve function Ffeulerxr fsolve 1545 Fxrdtx2x3 endfunction function JdFdxx definition de la derivee de F J1dt2x3x2 endfunction r 004257794928862307 dt 10 xvinfofsolverlistfeulerrdFdx fsolve dont find the solution dispv The residual dispinfo The termination indicator xvinfofsolve1listfeulerrdFdx fsolve find the solution dispv The residual dispinfo The termination indicator clfxlinspace011000plotxfeulerx agcaagrid5 5 So each time you use fsolve be sure to check the termination indicator and the residual value to see if fsolve has converged See Also external qpsolve optim 1546 Name karmarkar karmarkar algorithm x1karmarkarabcx0 Parameters a matrix np b n vector c p vector x0 initial vector eps threshold default value 1d5 gamma descent step 0gamma1 default value 14 x1 solution crit value of cx1 Description Computes x which minimizes Examples n10p20 arandnp crandp1 x0absrandp1 bax0 x1karmarkarabcx0 1547 Name leastsq Solves nonlinear least squares problems foptxoptgrdoptleastsqfun x0 foptxoptgrdoptleastsqfun dfun x0 foptxoptgrdoptleastsqfun cstr x0 foptxoptgrdoptleastsqfun dfun cstr x0 foptxoptgrdoptleastsqfun dfun cstr x0 algo foptxoptgrdoptleastsqimp fun dfun cstrx0 algodf0memstop Parameters fopt value of the function fxfunx2 at xopt xopt best value of x found to minimize funx2 grdopt gradient of f at xopt fun a scilab function or a list defining a function from Rn to Rm see more details in DESCRIP TION x0 real vector initial guess of the variable to be minimized dfun a scilab function or a string defining the Jacobian matrix of fun see more details in DESCRIP TION cstr bound constraints on x They must be introduced by the string keyword b followed by the lower bound binf then by the upper bound bsup so cstr appears as bbinfbsup in the calling sequence Those bounds are real vectors with same dimension than x0 inf and inf may be used for dimension which are unrestricted algo a string with possible values qn or gc or nd These strings stand for quasiNewton default conjugate gradient or nondifferentiable respectively Note that nd does not accept bounds on x imp scalar argument used to set the trace mode imp0 nothing except errors is reported imp1 initial and final reports imp2 adds a report per iteration imp2 add reports on linear search Warning most of these reports are written on the Scilab standard output df0 real scalar Guessed decreasing of fun2 at first iteration df01 is the default value mem integer number of variables used to approximate the Hessean second derivatives of f when algoqn Default value is around 6 stop sequence of optional parameters controlling the convergence of the algorithm They are intro duced by the keyword ar the sequence being of the form arnap iter epsg epsf epsx leastsq 1548 nap maximum number of calls to fun allowed iter maximum number of iterations allowed epsg threshold on gradient norm epsf threshold controlling decreasing of f epsx threshold controlling variation of x This vector possibly matrix of same size as x0 can be used to scale x Description fun being a function from Rn to Rm this routine tries to minimize wrt x the function which is the sum of the squares of the components of fun Bound constraints may be imposed on x How to provide fun and dfun fun can be either a usual scilab function case 1 or a fortran or a C routine linked to scilab case 2 For most problems the definition of fun will need supplementary parameters and this can be done in both cases case 1 when fun is a Scilab function its calling sequence must be yfunx optpar1optpar2 When fun needs optional parameters it must appear as listfunoptpar1optpar2 in the calling sequence of leastsq case 2 when fun is defined by a Fortran or C routine it must appear as listfunnamem optpar1optpar2 in the calling sequence of leastsq funname a string being the name of the routine which must be linked to Scilab see link The generic calling se quences for this routine are In Fortran subroutine funm n x params y integer mn double precision xn params ym In C void funint m int n double x double params double y where n is the dimension of vector x m the dimension of vector y which must store the evaluation of fun at x and params is a vector which contains the optional parameters optpar1 optpar2 each parameter may be a vector for instance if optpar1 has 3 components the description of optpar2 begin from params4 fortran case and from params3 C case etc Note that even if fun doesnt need supplementary parameters you must anyway write the fortran code with a params argument which is then unused in the subroutine core In many cases it is adviced to provide the Jacobian matrix dfun dfunijdfidxj to the optimizer which uses a finite difference approximation otherwise and as for fun it may be given as a usual scilab function or as a fortran or a C routine linked to scilab leastsq 1549 case 1 when dfun is a scilab function its calling sequence must be ydfunx optional parameters notes that even if dfun needs optional parameters it must appear simply as dfun in the calling sequence of leastsq case 2 when dfun is defined by a Fortran or C routine it must appear as dfunname a string in the calling sequence of leastsq dfunname being the name of the routine which must be linked to Scilab The calling sequences for this routine are nearly the same than for fun In Fortran subroutine dfunm n x params y integer mn double precision xn params ymn In C void funint m int n double x double params double y in the C case dfunijdfidxj must be stored in ymj1i1 Remarks Like datafit leastsq is a front end onto the optim function If you want to try the LevenbergMar quard method instead use lsqrsolve A least squares problem may be solved directly with the optim function in this case the function NDcost may be useful to compute the derivatives see the NDcost help page which provides a simple example for parameters identification of a differential equation Examples We will show different calling possibilities of leastsq on one trivial example which is non linear but doesnt really need to be solved with leastsq applying log linearizes the model and the problem may be solved with linear algebra In this example we look for the 2 parameters x1 and x2 of a simple exponential decay model x1 being the unknow initial value and x2 the decay constant function y ytht x y x1expx2t endfunction we have the m measures ti yi m 10 tm 025 05 075 10 125 15 175 20 225 25 ym 079 059 047 036 029 023 017 015 012 008 wm onesm1 measure weights here all equal to 1 and we want to find the parameters x such that the model fits the given datas in the least square sense minimize fx sumi wmi2 ythtmix ymi 2 initial parameters guess x0 15 08 in the first examples we define the function fun and dfun in scilab language leastsq 1550 function e myfunx tm ym wm e wm ythtm x ym endfunction function g mydfunx tm ym wm v wmexpx2tm g v x1tmv endfunction now we could call leastsq 1 the simplest call fxopt gropt leastsqlistmyfuntmymwmx0 2 we provide the Jacobian fxopt gropt leastsqlistmyfuntmymwmmydfunx0 a small graphic before showing other calling features tt linspace011maxtm100 yy ythtt xopt clf plot2dtm ym style2 plot2dtt yy style 2 legendmeasure points fitted curve xtitlea simple fit with leastsq 3 how to get some information we use imp1 fxopt gropt leastsq1listmyfuntmymwmmydfunx0 4 using the conjugate gradient instead of quasi Newton fxopt gropt leastsq1listmyfuntmymwmmydfunx0gc 5 how to provide bound constraints not useful here xinf infinf xsup inf inf fxopt gropt leastsqlistmyfuntmymwmbxinfxsupx0 without Jacobian fxopt gropt leastsqlistmyfuntmymwmmydfunbxinfxsupx0 with Jacobian 6 playing with some stopping parameters of the algorithm allows only 40 function calls 8 iterations and set epsg001 epsf01 fxopt gropt leastsq1listmyfuntmymwmmydfunx0ar40800101 7 and 8 now we want to define fun and dfun in fortran then in C Note that the compile and link to scilab method used here is believed to be OS independant but there are some requirements in particular you need a C and a fortran compiler and they must be compatible with the ones used to build your scilab binary 7 fun and dfun in fortran 71 Let s Scilab write the fortran code in the TMPDIR directory fcode subroutine myfunmnxparamf parami tmi parammi ymi param2mi wmi implicit none integer nm double precision xn param fm integer i do i 1m leastsq 1551 fi param2mi x1expx2parami parammi enddo end subroutine fun subroutine mydfunmnxparamdf parami tmi parammi ymi param2mi wmi implicit none integer nm double precision xn param dfmn integer i do i 1m dfi1 param2miexpx2parami dfi2 x1paramidfi1 enddo end subroutine dfun cd TMPDIR mputlfcodeTMPDIRmyfunf 72 compiles it You need a fortran compiler names myfun mydfun flibname ilibforlinknamesmyfunof 73 link it to scilab see link help page linkflibnamenamesf 74 ready for the leastsq call be carreful dont forget to give the dimension m after the routine name fxopt gropt leastsqlistmyfunmtmymwmx0 without Jacobian fxopt gropt leastsqlistmyfunmtmymwmmydfunx0 with Jacobian 8 last example fun and dfun in C 81 Let s Scilab write the C code in the TMPDIR directory ccode include mathh void myfuncint mint n double x double param double f parami tmi parammi ymi param2mi wmi int i for i 0 i m i fi param2mi x0expx1parami parammi return void mydfuncint mint n double x double param double df parami tmi parammi ymi param2mi wmi int i for i 0 i m i dfi param2miexpx1parami dfim x0paramidfi return mputlccodeTMPDIRmyfuncc 82 compiles it You need a C compiler leastsq 1552 names myfunc mydfunc clibname ilibforlinknamesmyfuncoc 83 link it to scilab see link help page linkclibnamenamesc 84 ready for the leastsq call fxopt gropt leastsqlistmyfuncmtmymwmmydfuncx0 See Also lsqrsolve optim NDcost datafit external qpsolve 1553 Name list2vec Catenates list entries in a matrix bigVectorvarsizes list2vecli Parameters li a list with n entries The list entries must be 2D matrices with comptible types bigVector A column vector Formed by the elements of the corresponding list entry varsizes An n by 3 matrix Each row contains the dimensions of the corresponding list entry Description Catenates list entries in a column vector The list entries are supposed to be matrices with compatible types with respect to catenation This function is a subsidiary for lmisolver Examples list2veclist123 list2veclist1 2 345s s1 See Also vec2list Authors FD INRIA 1554 Name lmisolver linear matrix inequation solver XLISTFOPT lmisolverXLIST0evalfunc options Parameters XLIST0 a list of containing initial guess eg XLIST0listX1X2Xn evalfunc a Scilab function external function with specific syntax The syntax the function evalfunc must be as follows LMELMIOBJevalfunctX where X is a list of matrices LME LMI are lists and OBJ a real scalar XLISTF a list of matrices eg XLIST0listX1X2Xn options optional parameter If given options is a real row vector with 5 components Mboundabstolnumaxitersreltol Description lmisolver solves the following problem minimize fX1X2Xn a linear function of Xis under the linear constraints GiX1X2Xn0 for i1p and LMI linear matrix inequali ties constraints HjX1X2Xn 0 for j1q The functions f G H are coded in the Scilab function evalfunc and the set of matrices Xis in the list X ie XlistX1Xn The function evalfun must return in the list LME the matrices G1XGpX ie LMEiGiX1Xn i1p evalfun must return in the list LMI the matrices H1X0HqX ie LMIjHjX1Xn j1q evalfun must return in OBJ the value of fX ie OBJfX1Xn lmisolver returns in XLISTF a list of real matrices i e XLISTlistX1X2Xn where the Xis solve the LMI problem Defining YZ and cost by YZcostevalfuncXLIST Y is a list of zero matrices YlistY1Yp Y10 Y20 Yp0 Z is a list of square symmetric matrices ZlistZ1Zq which are semi positive definite Z10 Z20 Zq0 ie specZj 0 cost is minimized lmisolver can also solve LMI problems in which the Xis are not matrices but lists of matrices More details are given in the documentation of LMITOOL lmisolver 1555 Examples Find diagonal matrix X ie XdiagdiagX p1 such that A1XXA1Q1 0 A2XXA2Q2 0 q2 and traceX is maximized n 2 A1 randnn A2 randnn Xs diag1n Q1 A1XsXsA101eye Q2 A2XsXsA202eye deffLMELMIOBJevalfXlistX Xlist1 LME XdiagdiagX LMI listA1XXA1Q1A2XXA2Q2 OBJ sumdiagX XlmisolverlistzerosA1evalf XX1 YZcevalfX See Also lmitool 1556 Name lmitool tool for solving linear matrix inequations lmitool lmitoolfilename txtlmitoolprobnamevarlistdatalist Parameters filename a string referring to a sci function probname a string containing the name of the problem varlist a string containing the names of the unknown matrices separated by commas if there are more than one datalist a string containing the names of data matrices separated by commas if there are more than one txt a string providing information on what the user should do next Description lmitool or lmitoolfilename is used to define interactively a LMI problem In the non interactive mode txtlmitoolprobnamevarlistdatalist generates a file in the cur rent directory The name of this file is obtained by adding sci to the end of probname This file is the skeleton of a solver function and the corresponding evaluation function needed by lmisolver See Also lmisolver 1557 Name lsqrsolve minimize the sum of the squares of nonlinear functions levenbergmarquardt algorithm x v infolsqrsolvex0fctm stop diag x v infolsqrsolvex0fctm fjac stop diag Parameters x0 real vector of size n initial estimate of the solution vector fct external ie function or list or string m integer the number of functions m must be greater than or equal to n fjac external ie function or list or string stop optional vector ftolxtolgtolmaxfevepsfcnfactor the default value is 1d81d81d510000100 ftol A positive real numbertermination occurs when both the actual and predicted relative reduc tions in the sum of squares are at most ftol therefore ftol measures the relative error desired in the sum of squares xtol A positive real number termination occurs when the relative error between two consecutive iterates is at most xtol therefore xtol measures the relative error desired in the approx imate solution gtol A nonnegative input variable termination occurs when the cosine of the angle between fctx and any column of the jacobian is at most gtol in absolute value therefore gtol measures the orthogonality desired between the function vector and the columns of the ja cobian maxfev A positive integer termination occurs when the number of calls to fct is at least maxfev by the end of an iteration epsfcn A positive real number used in determining a suitable step length for the forwarddifference approximation this approximation assumes that the relative errors in the functions are of the order of epsfcn if epsfcn is less than the machine precision it is assumed that the relative errors in the functions are of the order of the machine precision factor A positive real number used in determining the initial step bound this bound is set to the product of factor and the euclidean norm of diagx if nonzero or else to factor itself in most cases factor should lie in the interval 01100 100 is a generally recommended value diag is an array of length n diag must contain positive entries that serve as multiplicative scale factors for the variables lsqrsolve 1558 x real vector final estimate of the solution vector v real vector value of fctx info termination indicator 0 improper input parameters 1 algorithm estimates that the relative error between x and the solution is at most tol 2 number of calls to fcn reached 3 tol is too small No further improvement in the approximate solution x is possible 4 iteration is not making good progress 5 number of calls to fcn has reached or exceeded maxfev 6 ftol is too small no further reduction in the sum of squares is possible 7 xtol is too small no further improvement in the approximate solutionx is possible 8 gtol is too small fvec is orthogonal to the columns of the jacobian to machine precision Description minimize the sum of the squares of m nonlinear functions in n variables by a modification of the levenbergmarquardt algorithm the user must provide a subroutine which calculates the functions the jacobian is then calculated by a forwarddifference approximation minimize sumfctxm2 where fct is function from Rn to Rm fct should be a Scilab function whose calling sequence is vfctxm given x and m a character string which refers to a C or Fortran routine which must be linked to Scilab Fortran calling sequence should be fctmnxviflag where m n iflag are integers x a double precision vector of size n and v a double precision vector of size m C calling sequence should be fctint m int n double xdouble vint iflag fjac is an external which returns vdfctdx x it should be a Scilab function whose calling sequence is Jfjacxm given x and m lsqrsolve 1559 a character string it refers to a C or Fortran routine which must be linked to Scilab Fortran calling sequence should be fjacmnxjaciflag where m n iflag are inte gers x a double precision vector of size n and jac a double precision vector of size mn C calling sequence should be fjacint m int n double xdouble vint iflag return 1 in iflag to stop the algoritm if the function or jacobian could not be evaluated Examples A simple example with lsqrsolve a17 28 4 3 b10111 function yf1xm yaxb endfunction xsolvlsqrsolve100100f13 xsolab function yfj1xm ya endfunction xsolvlsqrsolve100100f13fj1 xsolab Data fitting problem 1 build the data a34b12c14 deffyFFxyaxbcxx X013YFFX100rand5 solve function ef1abcm aabc1babc2cabc3 eYaXbcXX endfunction abcvlsqrsolve101010f1sizeX1 abc normv See Also external qpsolve optim fsolve Used Functions lmdif lmder from minpack Argonne National Laboratory 1560 Name numdiff numerical gradient estimation gnumdifffunx dx Parameters fun an external Scilab function or list See below for calling sequence see also external for details about external functions x vector the argument of the function fun dx vector the finite difference step Default value is dxsqrteps11d3absx g vector the estimated gradient Description given a function funx from Rn to Rp computes the matrix g such as gij dfidxj using finite difference methods Without parameters the function fun calling sequence is yfunx and numd iff can be called as gnumdifffunx Else the function fun call ing sequence must be yfunxparam1pararm2paramq If parame ters param1param2paramq exist then numdiff can be called as follow gnumdifflistfunparam1param2paramqx See the derivative with respect to numerical accuracy issues and comparison between the two algo rithms Examples example 1 without parameters myfun is a function from R2 to R x1x2 myfunx function fmyfunx fx1x1x1x2 endfunction x5 8 gnumdiffmyfunx The exact gradient ie derivate belong x1 first component and derivate belong x2 second component is exact2x1x2 x1 example 2 with parameters myfun is a function from R to R x1 myfunx myfun contains 3 parameters a b c numdiff 1561 function fmyfunxabc fxacb endfunction a3 b4 c2 x1 g2numdifflistmyfunabcx The exact gradient ie derivate belong x1 is exact2cxac1 See Also optim derivative external 1562 Name optim nonlinear optimization routine fxoptoptimcostfx0 f xopt gradopt workoptimcostf contrx0 algo df0 mem work stop params impiflag Parameters costf external ie Scilab function list or string costf is the cost function that is a Scilab script a Fortran 77 routine or a C function x0 real vector initial value of variable to be minimized f value of optimal cost fcostfxopt xopt best value of x found contr keyword representing the following sequence of arguments bbinfbsup with binf and bsup are real vectors with same dimension as x0 binf and bsup are lower and upper bounds on x algo qn quasiNewton this is the default solver gc conjugate gradient nd nondifferentiable Note that the conjugate gradient solver does not accept bounds on x df0 real scalar Guessed decreasing of f at first iteration df01 is the default value mem integer number of variables used to approximate the Hessian Default value is 10 This feature is available for the GradientConjugate algorithm gc without constraints and the nonsmooth algorithm nd without constraints stop keyword representing the sequence of optional parameters controlling the convergence of the algorithm arnap iter epsg epsf epsx ar reserved keyword for stopping rule selection defined as follows nap maximum number of calls to costf allowed default is 100 iter maximum number of iterations allowed default is 100 epsg threshold on gradient norm optim 1563 epsf threshold controlling decreasing of f epsx threshold controlling variation of x This vector possibly matrix of same size as x0 can be used to scale x params keyword representing the method to initialize the arguments ti td passed to the objective function provided as a C or Fortran routine This option has no meaning when the cost function is a Scilab script params can be set to only one of the following values in That mode allows to allocate memory in the internal Scilab workspace so that the objective function can get arrays with the required size but without directly allocating the memory in stands for initialization In that mode before the value and derivative of the objective func tion is to be computed there is a dialog between the optim Scilab primitive and the objective function In this dialog the objective function is called two times with particular values of the ind parameter The first time ind is set to 10 and the objective function is expected to set the nizs nrzs and ndzs integer parameters of the nird common common nird nizsnrzsndzs This allows Scilab to allocate memory inside its internal workspace The second time the ob jective function is called ind is set to 11 and the objective function is expected to set the ti tr and tz arrays After this initialization phase each time it is called the objective function is ensured that the ti tr and tz arrays which are passed to it have the values that have been pre viously initialized tivalti In this mode valti is expected to be a Scilab vector variable containing integers Whenever the objective function is called the ti array it receives contains the values of the Scilab variable td valtd In this mode valtd is expected to be a Scilab vector variable containing double values When ever the objective function is called the td array it receives contains the values of the Scilab variable tivaltitdvaltd This mode combines the two previous The ti td arrays may be used so that the objective function can be computed For example if the objective function is a polynomial the ti array may may be used to store the coefficients of that polynomial Users should choose carefully between the in mode and the ti and td mode depending on the fact that the arrays are Scilab variables or not If the data is available as Scilab variables then the ti valti td valtd mode should be chosen If the data is available directly from the objective function the in mode should be chosen Notice that there is no tr mode since in Scilab all real values are of double type If neither the in mode nor the ti td mode is chosen that is if params is not present as an option of the optim primitive the user may should not assume that the titr and td arrays can be used reading or writing the arrays may generate unpredictable results optim 1564 impiflag named argument used to set the trace mode The possible values for iflag are 012 and 2 Use this option with caution most of these reports are written on the Scilab standard output iflag0 nothing except errors is reported this is the default iflag1 initial and final reports iflag2 adds a report per iteration iflag2 add reports on linear search iflag0 calls the cost function with ind1 every imp iterations gradopt gradient of costf at xopt work working array for hot restart for quasiNewton method This array is automatically initialized by optim when optim is invoked It can be used as input parameter to speedup the calculations Description Nonlinear optimization routine for programs without constraints or with bound constraints min costfx wrt x costf is an external ie a Scilab function a list or a string giving the name of a C or Fortran routine see external This external must return the value f of the cost function at the point x and the gradient g of the cost function at the point x Scilab function case If costf is a Scilab function the calling sequence for costf must be fgindcostfxind Here costf is a function which returns f value real number of cost function at x and g gradient vector of cost function at x The variable ind is described below List case If costf is a list it should be of the form listrealcostf arg1argn with realcostf a Scilab function with calling sequence fgindcostfxindarg1 argn The x f g ind arguments have the same meaning that above argi arguments can be used to pass function parameters String case If costf is a character string it refers to the name of a C or Fortran routine which must be linked to Scilab Fortran case The interface of the Fortran subroutine computing the objective must be subroutine costfindnxfgtitrtd optim 1565 with the following declarations integer indn ti double precision xnfgntd real tr The argument ind is described below If ind 2 3 or 4 the inputs of the routine are x ind n ti trtd If ind 2 3 or 4 the outputs of the routine are f and g C case The interface of the C function computing the objective must be void costfint ind int n double x double f double g int ti float tr double td The argument ind is described below The inputs and outputs of the function are the same as in the fortran case The ind input argument is a message sent from the solver to the cost function so that the cost function knows what to compute If ind2 costf must provide f If ind3 costf must provide g If ind4 costf must provide f and g If ind1 costf can print messages When the imp option is set to a negative integer value say m for example the cost function is called back every m iterations with the ind1 parameter This can be used to print messages fill a log file or creating an interactive plot See below for sample uses of this feature On output ind0 means that f cannot be evaluated at x and ind0 interrupts the optimization Example Scilab function The following is an example with a Scilab function Notice for simplifications reasons the Scilab function cost of the following example computes the objective function f and its derivative no matter of the value of ind This allows to keep the example simple In practical situations though the com putation of f and g may raise performances issues so that a direct optimization may be to use the value of ind to compute f and g only when needed External function written in Scilab function fgind costxind xref123 f05normxxref2 gxxref endfunction Simplest call x0111 optim 1566 fxoptoptimcostx0 By conjugate gradient you can use qn gc or nd fxoptgoptoptimcostx0gc Seen as non differentiable fxoptgoptoptimcostx0nd Upper and lower bounds on x fxoptgoptoptimcostb1020514x0 Upper and lower bounds on x and setting up the algorithm to gc fxoptgoptoptimcostb1020514x0gc Bound on the number of call to the objective function fxoptgoptoptimcostb1020514x0gcar3 Set max number of call to the objective function 3 Set max number of iterations 100 Set stopping threshold on the value of f 1e6 on the value of the norm of the gradient of the objective function 1e6 on the improvement on the parameters xopt 1e61e61e6 fxoptgoptoptimcostb1020514x0gcar31001e61e61e31e31e3 Additionnal messages are printed in the console fxoptoptimcostx0imp3 Example C function The following is an example with a C function where a C source code is written into a file dynamically compiled and loaded into Scilab and then used by the optim solver The interface of the rosenc function is fixed even if the arguments are not really used in the cost function This is because the un derlying optimization solvers must assume that the objective function has a known constant interface In the following example the arrays ti and tr are not used only the array td is used as a parameter of the Rosenbrock function Notice that the content of the arrays ti and td are the same that the content of the Scilab variable as expected External function written in C C compiler required write down the C code Rosenbrock problem Cinclude mathh double sqdouble x return xx void rosencint ind int n double x double f double g int ti float tr double td double p int i ptd0 if ind2ind4 f10 for i1ini fpsqxisqxi1sq10xi if ind3ind4 g040px1sqx0x0 optim 1567 for i1in1i gi20pxisqxi140pxi1sqxixi2010xi gn120pxn1sqxn22010xn1 cd TMPDIR mputlCTMPDIRrosencc compile the C code lilibforlinkrosencrosenccc incremental linking linklrosencc solve the problem x0401050 p100 fxogooptimrosencx0tdp Example Fortran function The following is an example with a Fortran function External function written in Fortran Fortran compiler required write down the Fortran code Rosenbrock problem F subroutine rosenfind n x f g ti tr td integer indnti double precision xnfgntd real tr c double precision yp ptd1 if indeq2orindeq4 then f10d0 do i2n ffpxixi12210d0xi2 enddo endif if indeq3orindeq4 then g140d0px2x12x1 ifngt2 then do i2n1 gi20d0pxixi1240d0pxi1xi2xi 20d010d0xi enddo endif gn20d0pxnxn1220d010d0xn endif return end cd TMPDIR mputlFTMPDIRrosenff compile the Fortran code lilibforlinkrosenfrosenfff optim 1568 incremental linking linklrosenff solve the problem x0401050 p100 fxogooptimrosenfx0tdp Example Fortran function with initialization The following is an example with a Fortran function in which the in option is used to allocate memory inside the Scilab environment In this mode there is a dialog between Scilab and the objective function The goal of this dialog is to initialize the parameters of the objective function Each part of this dialog is based on a specific value of the ind parameter At the beginning Scilab calls the objective function with the ind parameter equals to 10 This tells the objective function to initialize the sizes of the arrays it needs by setting the nizs nrzs and ndzs integer parameters of the nird common Then the objective function returns At this point Scilab creates internal variables and allocate memory for the variable izs rzs and dzs Scilab calls the objective function back again this time with ind equals to 11 This tells the objective function to initialize the arrays izs rzs and dzs When the objective function has done so it returns Then Scilab enters in the real optimization mode and calls the optimization solver the user requested Whenever the objective function is called the izs rzs and dzs arrays have the values that have been previously initialized Define a fortran source code and compile it fortran compiler required fortransource subroutine rosenfindnxfgizsrzsdzs C c Example of cost function given by a subroutine c if n2 returns ind0 c fbonnans oct 86 implicit double precision ahoz real rzs1 double precision dzs dimension xngnizs commonnirdnizsnrzsndzs if nlt3 then ind0 return endif ifindeq10 then nizs2 nrzs1 ndzs2 return endif ifindeq11 then izs15 izs210 dzs21000d0 return endif ifindeq2go to 5 ifindeq3go to 20 ifindeq4go to 5 optim 1569 ind1 return 5 f10d0 do 10 i2n im1i1 10 ff dzs2xixim122 10d0xi2 ifindeq2return 20 g140d0dzs2x2x12x1 nm1n1 do 30 i2nm1 im1i1 ip1i1 gi20d0dzs2xixim12 30 gigi 40d0dzs2xip1xi2xi 20d010d0xi gn20d0dzs2xnxnm12 20d010d0xn return end cd TMPDIR mputlfortransourceTMPDIRrosenff compile the C code libpathilibforlinkrosenfrosenfff incremental linking linkidlinklibpathrosenff x012ones15 Solve the problem fxgoptimrosenfx0in Example Fortran function with initialization on Win dows with Intel Fortran Compiler Under the Windows operating system with Intel Fortran Compiler one must carefully design the for tran source code so that the dynamic link works properly On Scilabs side the optimization compo nent is dynamically linked and the symbol nird is exported out of the optimization dll On the cost functions side which is also dynamically linked the nird common must be imported in the cost function dll The following example is a rewriting of the previous example with special attention for the Windows operating system with Intel Fortran compiler as example In that case we introduce additionnal com piling instructions which allows the compiler to import the nird symbol fortransourcesubroutine rosenfindnxfgizsrzsdzs cDEC IF DEFINED FORDLL cDEC ATTRIBUTES DLLIMPORT nird cDEC ENDIF C c Example of cost function given by a subroutine c if n2 returns ind0 c fbonnans oct 86 implicit double precision ahoz optim 1570 etc Example Logging features The imp flag may take negative integer values say k In that case the cost function is called once every k iterations This allows to draw the function value or write a log file In the following example we solve the Rosenbrock test case For each iteration of the algorithm we print the value of x f and g function fgind costxind xref123 if ind 1 ind 4 then f05normxxref2 end if ind 1 ind 4 then gxxref end if ind 1 then mprintf mprintfx s strcatstringx mprintff e f gxxref mprintfg s strcatstringg end endfunction x0111 fxoptoptimcostx0imp1 The previous script produces the following output x 1 1 1 f 6500000e000 g 0 3 2 x 1 0 16666667 f 2888889e000 g 0 2 13333333 x 1 2 3 f 9860761e031 g 0 4441D16 1332D15 x 1 2 3 f 0000000e000 g 0 0 0 In the following example we solve the Rosenbrock test case For each iteration of the algorithm we plot the current value of x into a 2D graph containing the contours of Rosenbrocks function This allows to see the progress of the algorithm while the algorithm is performing We could as well write the value of x f and g into a log file if needed optim 1571 1 Define rosenbrock function f g ind rosenbrock x ind if ind 1 ind 4 then f 1000 x2x122 1x12 end if ind 1 ind 4 then g1 400 x2 x12 x1 2 1 x1 g2 200 x2 x12 end if ind 1 then plot x1 x2 g end endfunction x0 12 10 xopt 10 10 2 Draw the contour of Rosenbrocks function xmin 20 xmax 20 stepx 01 ymin 10 ymax 20 stepy 01 nx 100 ny 100 stepx xmax xminnx xdata xminstepxxmax stepy ymax yminny ydata yminstepyymax for ix 1lengthxdata for iy 1lengthydata x xdataix ydataiy f g ind rosenbrock x 4 zdata ix iy f end end contour xdata ydata zdata 1 10 100 500 1000 plotx01 x02 b plotxopt1 xopt2 r 3 Plot the optimization process during optimization fopt xopt optim rosenbrock x0 imp 1 Example Optimizing with numerical derivatives It is possible to optimize a problem without an explicit knowledge of the derivative of the cost function For this purpose we can use the numdiff or derivative function to compute a numerical derivative of the cost function In the following example we use the numdiff function to solve Rosenbrocks problem function f rosenbrock x f 1000 x2x122 1x12 endfunction optim 1572 function f g ind rosenbrockCost x ind if ind 1 ind 4 then f rosenbrock x end if ind 1 ind 4 then g numdiff rosenbrock x end endfunction x0 12 10 fopt xopt optim rosenbrockCost x0 In the following example we use the derivative function to solve Rosenbrocks problem Given that the step computation strategy is not the same in numdiff and derivative this might lead to improved results function f rosenbrock x f 1000 x2x122 1x12 endfunction function f g ind rosenbrockCost2 x ind if ind 1 ind 4 then f rosenbrock x end if ind 1 ind 4 then g derivative rosenbrock x order 4 end endfunction x0 12 10 fopt xopt optim rosenbrockCost2 x0 Example Counting function evaluations and number of iterations The imp option can take negative values If the imp is equal to m where m is a negative integer then the cost function is evaluated every m iterations with the ind input argument equal to 1 The following example uses this feature to compute the number of iterations The global variable mydata is used to store the number of function evaluations as well as the number of iterations xref123 x0111 global MYDATA MYDATA tlist TMYDATAniternfevals MYDATAniter 0 MYDATAnfevals 0 function fgind costxind global MYDATA dispind if ind 1 MYDATAniter MYDATAniter 1 end MYDATAnfevals MYDATAnfevals 1 optim 1573 f05normxxref2 gxxref endfunction fxoptoptimcostx0imp1 mprintf Number of function evaluationsd MYDATAnfevals mprintf Number of iterationsd MYDATAniter While the previous example perfectly works there is a risk that the same variable MYDATA is used by some internal function used by optim In this case the value may be wrong This is why a sufficiently weird variable name has been used Example Passing extra parameters In most practical situations the cost function depends on extra parameters which are required to eval uate the cost function There are several methods to achieve this goal In the following example the cost function uses 4 parameters a b c and d We define the cost function with additionnal input arguments which are declared after the index argument Then we pass a list as the first input argument of the optim solver The first element of the list is the cost function The additionnal variables are directly passed to the cost function function f g ind costfunction x ind a b c d f a x1 c 2 b x2 d 2 g1 2 a x1 c g2 2 b x2 d endfunction x0 1 1 a 10 b 20 c 30 d 40 costf list costfunction a b c d fopt xopt optim costf x0 imp 2 These coefficients are defined before the optimizer is called There are directly used in the cost func tion The example NOT to follow function f g ind costfunction x ind f a x1 c 2 b x2 d 2 g1 2 a x1 c g2 2 b x2 d endfunction x0 1 1 a 10 b 20 c 30 d 40 fopt xopt optim costfunction x0 imp 2 optim 1574 While the previous example perfectly works there is a risk that the same variables are used by some internal function used by optim In this case the value of the parameters are not what is expected and the optimization can fail or worse give a wrong result In the following example we define the cost function with the classical header Inside the function definition we declare that the parameters a b c and d are global variables Then we declare and set the global variables Another example NOT to follow function f g ind costfunction x ind global a b c d f a x1 c 2 b x2 d 2 g1 2 a x1 c g2 2 b x2 d endfunction x0 1 1 global a b c d a 10 b 20 c 30 d 40 fopt xopt optim costfunction x0 imp 2 While the previous example perfectly works there is a risk that the same variables are used by some internal function used by optim In this case the value of the parameters are not what is expected and the optimization can fail or worse give a wrong result Example Checking that derivatives are correct Many optimization problem can be avoided if the derivatives are computed correctly One common reason for failure in the steplength procedure is an error in the calculation of the cost function and its gradient Incorrect calculation of derivatives is by far the most common user error In the following example we give a false implementation of Rosenbrocks gradient In order to check the computation of the derivatives we use the derivative function We define the simplified function which delegates the computation of f to the rosenbrock function The simplified func tion is passed as an input argument of the derivative function function f g index rosenbrock x index f 1000 x2x122 1x12 Exact g1 400 x2 x12 x1 2 1 x1 Wrong g1 1200 x2 x12 x1 2 1 x1 g2 200 x2 x12 endfunction function f simplified x index 1 f g index rosenbrock x index endfunction x0 12 1 index 1 f g index rosenbrock x0 index optim 1575 gnd derivative simplified x0 mprintf Exact derivatives strcat stringg mprintf Numerical derivatives strcat stringgnd The previous script produces the following output Obviously the difference between the two gradient is enormous which shows that the wrong formula has been used in the gradient Exact derivative638 88 Numerical derivative2156 88 See Also external qpsolve datafit leastsq numdiff derivative NDcost References The following is a map from the various options to the underlying solvers with some comments about the algorithm when available qn without constraints n1qn1 a quasiNewton method with a Wolfetype line search qn with bounds constraints qnbd a quasiNewton method with projection RR0242 A variant of a projected variable metric method for bound constrained optimization problems Bonnans Frederic Rapport de recherche de lINRIA Rocquencourt Octobre 1983 gc without constraints n1qn3 a conjugate gradient method with BFGS gc with bounds constraints gcbd a BFGStype method with limited memory and projection nd without constraints n1fc1 a bundle method nd with bounds constraints not available Author The Modulopt library JFrederic Bonnans JeanCharles Gilbert Claude Lemarechal The interfaces to the Modulopt library JFrederic Bonnans This help Michael Baudin 1576 Name qld linear quadratic programming solver xlagrqldQpCbcicsme tol xlagrinfoqldQpCbcicsme tol Parameters Q real positive definite symmetric matrix dimension n x n p real column vector dimension n C real matrix dimension me md x n b RHS column vector dimension me md ci column vector of lowerbounds dimension n If there are no lower bound constraints put ci If some components of x are bounded from below set the other unconstrained values of ci to a very large negative number eg cij numberpropertieshuge cs column vector of upperbounds Same remarks as above me number of equality constraints ie C1mex b1me tol Floatting point number required prÃcision x optimal solution found lagr vector of Lagrange multipliers If lower and upperbounds cics are provided lagr has n me md components and lagr1n is the Lagrange vector associated with the bound constraints and lagr n1 n me md is the Lagrange vector associated with the linear constraints If an upperbound resp lowerbound constraint i is active lagri is 0 resp 0 If no bounds are provided lagr has only me md components info integer return the execution status instead of sending errors info1 Too many iterations needed info2 Accuracy insufficient to statisfy convergence criterion info5 Length of working array is too short info10 The constraints are inconsistent qld 1577 Description This function requires Q to be positive definite if it is not the case one may use the The contributed toolbox quapro Examples Find x in R6 such that C1x b1 3 equality constraints ie me3 C1 111031 103456 253010 b1123 C2x b2 2 inequality constraints C2010121 102110 b2125 with x between ci and cs ci1000100000100010001000cs10000100151001001000 and minimize 05xQx px with p123456 Qeye66 No initial point is given CC1C2 bb1b2 me3 xlagrqldQpCbcicsme Only linear constraints 1 to 4 are active lagr160 See Also qpsolve optim The contributed toolbox quapro may also be of interest in particular for singular Q Authors KSchittkowski University of Bayreuth Germany AL Tits and JL Zhou University of Maryland qld 1578 Used Functions ql0001f in modulesoptimizationsrcfortranql0001f 1579 Name qpsolve linear quadratic programming solver builtin x iact iter fqpsolveQp1C1bme Parameters Q real positive definite symmetric matrix dimension n x n p real column vector dimension n C real matrix dimension me md x n This matrix may be dense or sparse b RHS column vector dimension mme md me number of equality constraints ie xC1me b1me x optimal solution found iact vector indicator of active constraints The first non zero entries give the index of the active con straints iter 2x1 vector first component gives the number of main iterations the second one says how many constraints were deleted after they became active Description This function requires Q to be symmetric positive definite If this hypothesis is not satisfied one may use the contributed quapro toolbox Examples Find x in R6 such that xC1 b1 3 equality constraints ie me3 C1 11 2 1 0 5 13 3 04 0 3 5 1 1 6 0 qpsolve 1580 b1123 xC2 b2 2 inequality constraints C2 0 1 1 0 02 11 21 1 0 b2 125 and minimize 05xQx px with p123456 Qeye66 me3 xiactiterfqpsolveQpC1 C2b1b2me Only linear constraints 1 to 4 are active See Also optim qld qpsolve The contributed toolbox quapro may also be of interest in particular for singular Q Memory requirements Let r be rminmn Then the memory required by qpsolve during the computations is 2nrr52 2m 1 Authors S Steer INRIA Scilab interface Berwin A Turlach School of Mathematics and Statistics M019 The University of Western Australia Crawley AUSTRALIA solver code References Goldfarb D and Idnani A 1982 Dual and PrimalDual Methods for Solving Strictly Convex Quadratic Programs in JP Hennart ed Numerical Analysis Proceedings Cocoyoc Mexico 1981 Vol 909 of Lecture Notes in Mathematics SpringerVerlag Berlin pp 226239 Goldfarb D and Idnani A 1983 A numerically stable dual method for solving strictly convex quadratic programs Mathematical Programming 27 133 QuadProg Quadratic Programming Routines Berwin A Turlachhttpwwwmathsuwaeduau berwinsoftwarequadproghtml qpsolve 1581 Used Functions qpgen2f and qpgen1f also named QPsolvef developped by Berwin A Turlach according to the GoldfarbIdnani algorithm 1582 Name qpsolve linear quadratic programming solver x iact iter fqpsolveQpCbcicsme Parameters Q real positive definite symmetric matrix dimension n x n p real column vector dimension n C real matrix dimension me md x n This matrix may be dense or sparse b RHS column vector dimension mme md ci column vector of lowerbounds dimension n If there are no lower bound constraints put ci If some components of x are bounded from below set the other unconstrained values of ci to a very large negative number eg cij numberpropertieshuge cs column vector of upperbounds Same remarks as above me number of equality constraints ie C1mex b1me x optimal solution found iact vector indicator of active constraints The first non zero entries give the index of the active con straints iter 2x1 vector first component gives the number of main iterations the second one says how many constraints were deleted after they became active Description This function requires Q to be symmetric positive definite If that hypothesis is not satisfied one may use the quapro function which is provided in the Scilab quapro toolbox The qpsolve solver is implemented as a Scilab script which calls the compiled qpsolve primitive It is provided as a facility in order to be a direct replacement for the former quapro solver indeed the qpsolve 1583 qpsolve solver has been designed so that it provides the same interface that is the same inputoutput arguments But the x0 and imp input arguments are available in quapro but not in qpsolve Examples Find x in R6 such that C1x b1 3 equality constraints ie me3 C1 111031 103456 253010 b1123 C2x b2 2 inequality constraints C2010121 102110 b2125 with x between ci and cs ci1000100000100010001000 cs10000100151001001000 and minimize 05xQx px with p123456 Qeye66 No initial point is given CC1C2 bb1b2 me3 xiactiterfqpsolveQpCbcicsme Only linear constraints 1 to 4 are active See Also optim qpsolve qld The contributed toolbox quapro may also be of interest in particular for singular Q Memory requirements Let r be rminmn Then the memory required by qpsolve during the computations is 2nrr52 2m 1 Authors S Steer INRIA Scilab interface qpsolve 1584 Berwin A Turlach School of Mathematics and Statistics M019 The University of Western Australia Crawley AUSTRALIA solver code References Goldfarb D and Idnani A 1982 Dual and PrimalDual Methods for Solving Strictly Convex Quadratic Programs in JP Hennart ed Numerical Analysis Proceedings Cocoyoc Mexico 1981 Vol 909 of Lecture Notes in Mathematics SpringerVerlag Berlin pp 226239 Goldfarb D and Idnani A 1983 A numerically stable dual method for solving strictly convex quadratic programs Mathematical Programming 27 133 QuadProg Quadratic Programming Routines Berwin A Turlachhttpwwwmathsuwaeduau berwinsoftwarequadproghtml Used Functions qpgen1f also named QPsolvef developped by Berwin A Turlach according to the GoldfarbIdnani algorithm 1585 Name quapro linear quadratic programming solver obsolete Description This function is superseded by qpsolve Users who are still interested by quapro may consider the Scilab quapro toolbox which provide the same features as in older Scilab releases See at httpwwwscilaborgcontribindexcontribphppagedownloadphp See Also qpsolve 1586 Name readmps reads a file in MPS format mps readmps filenamebounds maxsizes Parameters filename a string the name of the mps file bounds 2vector lowboundupbound default lower and upper bounds maxsizes 3vector maxmmaxnmaxnza Maximum number of contraints and variables maximum number of nonzeros entries in the LP constraint matrix If omitted readmps reads the file once just to compute these numbers mps tlist with following fields irobj integer index of the objective row namec character string Name of the objective nameb character string Name of the right hand side namran character string Name of the ranges section nambnd character string Name of the bounds section name character string Name of the LP problem rownames character string column vector Name of the rows colnames character string row vector Name of the columns rowstat integer vector row types 1 row type is 2 row type is 3 row type is 4 objective row readmps 1587 5 other free row rowcode real matrix hdrowcdlnkrow with hdrowcd real vector Header to the linked list of rows with the same codes lnkrow integer vector Linked list of rows with the same codes colcode real matrix hdcolcdlnkcol with hdcolcd integer vector Header to the linked list of columns with the same codes lnkcol integer vector Linked list of columns with the same codes rownmbs integer vector Row numbers of nonzeros in columns of matrix A colpnts integer vector Pointers to the beginning of columns of matrix A acoeff real vector Array of nonzero elements for each column rhs real vector Right hand side of the linear program ranges real vector of constraint ranges bounds real matrix lboundsubounds with ubounds full column vector of upper bounds lbounds full column vector of lower bounds stavar full column vector of variable status 0 standard non negative variable 1 upper bounded variable 2 lower bounded variable 3 lower and upper bounded variable 4 minus infinity type variable ie infxu readmps 1588 5 plus infinity type variable ie lx inf 6 fixed type variable ie lxu k free variable Description Reads a file containing description of an LP problem given in MPS format and returns a tlist which describes the problem It is an interface with the program rdmps1f of hopdm J Gondzio For a description of the variables see the file rdmps1f MPS format is a standard ASCII medium for LP codes MPS format is described in more detail in Murtaghs book Murtagh B 1981 Advanced Linear Programming McGrewHill New York 1981 Examples Let the LP problem objective min XONE 4 YTWO 9 ZTHREE constraints LIM1 XONE YTWO 5 LIM2 XONE ZTHREE 10 MYEQN YTWO ZTHREE 7 Bounds 0 XONE 4 1 YTWO 1 Generate MPS file txtNAME TESTPROB ROWS N COST L LIM1 G LIM2 E MYEQN COLUMNS XONE COST 1 LIM1 1 XONE LIM2 1 YTWO COST 4 LIM1 1 YTWO MYEQN 1 ZTHREE COST 9 LIM2 1 ZTHREE MYEQN 1 RHS RHS1 LIM1 5 LIM2 10 RHS1 MYEQN 7 BOUNDS UP BND1 XONE 4 LO BND1 YTWO 1 UP BND1 YTWO 1 ENDATA mputltxtTMPDIRtestmps readmps 1589 Read the MPS file PreadmpsTMPDIRtestmps0 1030 dispP 1590 Nom recons reciprocal function for aplat r reconsflind Parameters fl a flat list ind a list of paths r a hierachical list build with the leaves of fl Description Reciprocal function for aplat Creates a hierachical list given a flat one and a list of paths utility function for vec2list and lmisolver Examples lfindaplatlist12list31xxxlist321 reconslfind See Also aplat Authors FD and SS INRIA 1591 Name semidef semidefinite programming xZulinfosemidefx0Z0Fblckszscoptions Parameters x0 m x 1 real column vector must be strictly primal feasible see below Z0 L x 1 real vector compressed form of a strictly feasible dual matrix see below F L x m1 real matrix blckszs p x 2 integer matrix sizes of the blocks defining the dimensions of the square diagonal blocks sizeFijblckszsj j1m1 c m x 1 real vector options row vector with five entries nuabstolreltol0maxiters ul row vector with two entries Description xZulinfosemidefx0Z0Fblckszscoptions solves semidefinite pro gram and its dual exploiting block structure in the matrices Fi It interfaces L Vandenberghe and S Boyd spc program The Fis matrices are stored columnwise in F in compressed format if Fij i0m j1L denote the jth symmetric diagonal block of Fi then semidef 1592 where packM for symmetric M is the vector M11M12M1nM22M23M2nMnn ob tained by scanning columnwise the lower triangular part of M blckszs gives the size of block j ie sizeFijblckszsj Z is a block diagonal matrix with L blocks Z0 ZL1 Zj has size blckszsj times blckszsj Every block is stored using packed storage of the lower triangular part The 2 vector ul contains the primal objective value cx and the dual objective value traceF0Z The entries of options are respectively nu a real parameter which ntrols the rate of convergence abstol absolute tolerance reltol relative tolerance has a special meaning when negative tv target value only referenced if reltol 0 iters on entry maximum number of iterations 0 on exit the number of iterations taken Notice that the absolute tolerance cannot be lower than 10e8 that is the absolute tolerance used in the algorithm is the maximum of the userdefined tolerance and the constant tolerance 10e8 info returns 1 if maxiters exceeded 2 if absolute accuracy is reached 3 if relative accuracy is reached 4 if target value is reached 5 if target value is not achievable negative values indicate errors Convergence criterion 1 maxiters is exceeded 2 duality gap is less than abstol 3 primal and dual objective are both positive and duality gap is less than reltol dual objective or primal and dual objective are both negative and duality gap is less than reltol minus the primal objective 4 reltol is negative and primal objective is less than tv or dual objective is greater than tv Examples F02100 1200 0031 0013 F11200 2100 0013 0031 semidef 1593 F22200 2200 0034 0044 blckszs22 F01F01212F02F03434 F11F11212F12F13434 F21F21212F22F23434 x000 Z02F0 Z01Z01212Z02Z03434 FFF01F02F11F12F21F22 ZZ0Z01Z02 ctraceF1Z0traceF2Z0 options101d101d10050 xZulinfosemidefx0packZZ0packFFblckszscoptions wvec2listunpackZblckszsblckszsblckszsZsysdiagw1w2 cxtraceF0Z specF0F1x1F2x2 traceF1Zc1 traceF2Zc2 References L Vandenberghe and S Boyd Semidefinite Programming Informations Systems Laboratory Stan ford University 1994 Ju E Nesterov and M J Todd SelfScaled Cones and InteriorPoint Methods in Nonlinear Program ming Working Paper CORE Catholic University of Louvain LouvainlaNeuve Belgium April 1994 SP Software for Semidefinite Programming httpwwweeuclaeduvandenbesphtml 1594 Name vec2list list2vec reciprocal function livec2listbigVectorvarsizesind Parameters bigVector An m by n matrix Each column is used to generate the corresponding list entry varsizes An n by 2 matrix Each row give the dimensions of the matrix to be built with the correponding column of bigVector ind a list with n entries Each entry is a vector of positive integers which gives the hierchical path where the corresponding matrix has to be put li a list or a recursive list with n leaves The list entries or leaves are 2D matrices built with the corresponding column of bigVector and size given by the corresponding row of varsizes Description If the ind argument is not given this function creates a list The list entries or leaves are 2D matrices built with the corresponding column of bigVector and size given by the corresponding row of varsizes If the ind argument is given this function creates a hierachical list with n leaves The leaves are 2D matrices built with the corresponding column of bigVector and size given by the corresponding row of varsizes The hierachical path for each leaf if given by the corresponding entry of ind This function is a subsidiary for lmisolver Examples vec2list14ones42 vec2list142 11 2 vec2list14ones42list1231321 See Also list2vec Authors FD INRIA SS INRIA Parte XXVI Sobrecarga 1596 Name overloading capacidades de overloading sobrecarga de exibições funções e operadores Descrição No Scilab exibições funções e operadores de variáveis podem ser definidos para novos objetos uti lizando funções codificadas no Scilab ou primitivas Exibição Display a exibição de objetos definidos por uma estrutura tlist pode ser sobrecarregada a exibição padrão é semelhante a de lists A função de sobrecarga não deve ter argumentos de saída e deve ter um único argumento de entrada Seu nome é formado como segue tlisttypep onde tlisttype significa a primeira entrada do componente do tipo tlist truncado aos 9 primeiros caracteres Operadores Operators cada operador que não está definido para dados tipos de operandos pode ser definido A função de sobrecarga deve ter um único argumento de saída e um ou dois de entrada de acordo com o número de operandos O nome da função é definido como segue para operadores binários tipodoprimeirooperandocódigodo operadortipodosegundooperando para operadores unários tipodooperandocódigodooperador Operadores de extração e inserção que são nnários são descritos abaixo tipodooperando tipodoprimeirooperando tipodosegundooperando são seqüências de caracteres associadas a cada tipo de dado como descrito na tabela seguinte tipo de dado código char tipo de dado código char constante s booleano b string c bibilioteca f ponteiro de função fptr manipulador h inteiro i lista l função m função compilada mc polinômio p esparso sp esparso booleano spb tlist tlisttype polinômio de tamanho implícito ip matriz esparsa do Mat lab msp mlist mlisttype ponteiro ptr códigodooperador é um único caractere associado a cada operador como descrito na tabela seguinte operador código char operador código char t a s m r l p x d q overloading 1597 k y z b u v w ab c ab f extraction e insertion i o n g h j 5 0 1 2 3 4 iext 6 A função de sobrecarga para sintaxe de extração bai1in tem a seguinte seqüência de chamamento btipodeaei1ina e a sintaxex1xmai1in tem a seguinte seqüência de chamamento x1xmtipodeaei1ina A função de sobrecarga associada à sintaxe de inserção ai1inb tem a segunite seqüência de chamamento atipodebitipodeai1inba O código char 6 pode ser usado para alguns algoritmos de inserção complexos como xb233 onde o campo b não está definido na estrutura x A inserção é automaticamente decomposta em tempxb temp233 xbtemp O código char 6 é usado para o primeiro passo desse algoritmo A função de sobrecarga de 6 é muito semelhante à função de es Funções Functions algumas funções primitivas básicas também podem ser sobrecarregadas para novos tipo de dados Quando tal função não é definida para tipos de dados particulares a função tipodeumargumentonomedafunção é chamada O usuário pode adi cionar a esta função chamada a definição associada aos tipos de dados de entrada Exemplos EXIBIÇÃO defftabpldisp l3 l2stringl4 tlisttababxyrand22 OPERADOR deffxcasabxastringb s1 FUNÇÃO deffxcsinaxsina sin2x Ver Também tlist disp symbols Parte XXVII Polinômios 1599 Name bezout equação de Bezout para polinômios ou inteiros thegcdUbezoutp1p2 Parâmetros p1 p2 dois polinômios reais ou dois escalares inteiros tipo igual a 8 Descrição thegcdUbezoutp1p2 computa o MDC thegcd de p1 e p2 e também uma matriz 2x2 unimodular U tal quet p1p2U thegcd0 O MMC de p1 e p2 é dado por p1U12 or p2U22 Exemplos caso polinomial xpoly0x p1x1x35p2x2x33 thegcdUbezoutp1p2 detU cleanp1p2U thelcmp1U12 lcmp1p2 caso inteiro i1int32235 i2int322332 thegcdUbezouti1i2 Vint322235 233222345 thegcdUgcdV VU lcmV Ver Também poly roots simp clean lcm Autor S Steer INRIA 1600 Name clean limpa matrizes arredonda para zero entradas pequenas BcleanA epsa epsr Parâmetros A uma matriz numérica de escalares de polinômios esparsa epsaepsr números reais valores padrões respectivos 1d10 e 1d10 Descrição Esta função elimina ie ajusta para zero todos os coeficientes com valores absolutos epsa e val ores relativos epsr relativo siginifica em relação à norma1 de coeficientes em um polinômio possivelmente uma matriz de polinômios ou matriz de razões de polinômios Os valores padrões são epsa1d10 e epsr1d10 Para uma matriz de constantes cleanAepsa ajusta para zero todas as entradas menores que epsa Exemplos xpoly0x wx12x3x2xx2123x3 winvw cleanwinvw 1601 Name cmndred forma de denominador comum ndcmndrednumden Parâmetros num den duas matrizes de polinômios de dimensões iguais Descrição ndcmndrednumden computa uma matriz de polinômios n e um polinômio denominador comum d tais que ndnumden A matriz de razões de polinômios definida por numden é nd Ver Também simp clean 1602 Name coeff coeficientes de matrizes de polinômios CcoeffMp v Parâmetros Mp matriz de polinômios v vetor linha ou coluna de inteiros dos graus selecionados C matriz grande dos coeficientes Descrição CcoeffMp retorna em uma matriz grande C os coeficientes da matriz de polinômios Mp C é particionada como CC0C1Ck onde os Ci estão dispostos em ordem crescente k maxidegreeMp CcoeffMpv retorna a matriz de coeficientes com graus em v v é um vetor linha ou coluna Ver Também poly degree invcoeff Autor S Steer INRIA 1603 Name coffg matriz inversa de polinômios NsdcoffgFs Parâmetros Fs matriz quadrada de polinômios Descrição coffg computa Fs1 onde Fs é uma matriz de polinômios pelo método dos cofatores Fs inverse Nsd d denominador comum Ns numerador uma matriz de polinômios Para matrizes grandes seja paciente os resultados geralmente são confiáveis Exemplos spoly0s a s s21 s s21 a1dcoffga a1dinva Ver Também determ detr invr penlaur glever Autor F D 1604 Name colcompr compressão de colunas de matrizes de polinômios YrkaccolcomprA Parâmetros A matriz de polinômios Y matriz de polinômios quadrada base unimodular direita rk posto normal de A Ac AcAY matriz de polinômios Descrição Compressão de colunas da matriz de polinômios A compressão para a esquerda Exemplos spoly0s psss122s2s3 Yrkaccolcomprpp ppY Ver Também rowcompr 1605 Name degree grau da matriz de polinômios DdegreeM Parâmetros M matriz de polinômios D matriz de inteiros Descrição Retorna a matriz de graus mais elevados de M Ver Também poly coeff clean 1606 Name denom denominador dendenomr Parâmetros r matriz de polinômios de razões de polinômios ou de constantes den matriz de polinômios Descrição dendenomr retorna o denominador de uma matriz de razões de polinômios Desde que razões de polinômios são representadas internamente como rlistrnumdendtnumden denomr é o mesmo que r3 rden ou rden Ver Também numer 1607 Name derivat derivada de matriz de razões de polinômios pdderivatp Parâmetros p matriz de polinômios ou de razões de polinômios Descrição Computa a derivada da matriz de polinômios ou de funções racionais em relação à variável livre Exemplos spoly0s derivat1s 1s2 1608 Name determ determinante de matrizes de polinômios resdetermW k Parâmetros W matriz quadrada de polinômios reais k inteiro limite superior para o grau do determinante de W Descrição Retorna o determinante de uma matriz de polinômios reais computação feita por Transformada Rápida de Fourier TRF se W possuir tamanho maior do que 22 resdetermW kk é um inteiro maior do que o grau verdadeiro do determinante de W O valor padrão de k é a menor potência de 2 que é maior que nmaxidegreeW Método apenas se o tamanho de W for maior que 22 avalia o determinante de W para as freqüências de Fourier e aplica a TRF inversa para os coeficientes do determinante Exemplos spoly0s wsrand1010 determw detcoeffw1s10 Ver Também det detr coffg Autor FD 1609 Name detr determinante polinomial ddetrh Parâmetros h matriz quadrada de polinômios ou de razões de polinômios Descrição ddetrh retorna o determinante d da matriz de funções polinomiais ou racionais h É baseado no algoritmo de Leverrier Ver Também det determ 1610 Name diophant equação de Bezout diofantina xerrdiophantp1p2b Parâmetros p1p2 vetor de polinômios p1p2 p1 p2 b polinômio x vetor de polinômios x1x2 Descrição diophant resolve a equação de Bezout p1x1p2x2b com p1p2 um vetor de polinômios Se a equação não for solúvel de outro modo err0 Exemplos spoly0sp1s32p21s x1sx22s xerrdiophantp1p2p1x1p2x2 p1x1p2x2p1x1p2x2 1611 Name factors fatoração numérica real lnumgfactorspol flag lnumldengfactorsrat flag ratfactorsratflag Parâmetros pol polinômio real rat razão de polinômios reais ratpol1pol2 lnum lista de polinômios de graus 1 ou 2 lden lista de polinômios de graus 1 ou 2 g número real flag string c ou d Descrição Retorna os fatores do polinômio pol na lista lnum e o ganho g Temse pol g vezes o produto das entradas da lista lnum se flag não for fornecido Se flagc for dado então temse poli omega gprodlnumji omega Se flagd for dado então temse polexpi omega gprodlnumiexpi omega Se o argumento de factors for uma razão ratpol1pol2 os fatores do numerador pol1 e do denominador pol2 são retornados nas listas lnum e lden respectivamente O ganho é retornado como g ie temse rat g vezes produto das entradas de lnum produto das entradas de lden Se flag for c respectivamente d as raízes pol serão refletidas em relação em relação ao eixo imaginário respectivamente ao círculo unitário ie os fatores em lnum são polinômios estáveis A mesma coisa se factors for invocado com argumentos racionais as entradas em lnum e lden são polinômios estáveis se flag for dado R2factorsR1c ou R2factorsR1d com R1 uma função racional ou lista syslin SISO então a saída R2 é uma transferência com com numerador e denominador estáveis e com a mesma magnitude de R1 ao longo do eixo imaginário c ou do círculo unitário d Exemplos npoly0225z dpoly01037z Rsyslindnd R1factorsRd rootsR1num factors 1612 rootsR1den wexp2ipi0011 normabshornerR1wabshornerRw Ver Também simp 1613 Name gcd cálculo de máximo divisor comum pgcdUgcdp Parâmetros p vetor linha de polinômios pp1pn ou vetor linha de inteiros tipo igual a 8 Descrição Computa o MDC dos componentes de p e uma matriz unimodular inversa de polinômios U com grau mínimo tais que pU0 0 pgcd Exemplos caso polinomial spoly0s psss122s2s3 pgcdugcdp pu caso inteiro Vint322235 233222345 thegcdUgcdV VU Ver Também bezout lcm hermit 1614 Name hermit forma hermitiana ArUhermitA Parâmetros A matriz de polinômios Ar matriz de polinômios triangular U matriz de polinômios unimodular Descrição Forma hermitiana U é uma matriz unimodular tal que AU está na forma triangular de Hermite A variável de saída é ArAU Aviso versão experimental Exemplos spoly0s ps ss12 2s2s3 ArUhermitpp cleanppU detU Ver Também hrmt htrianr 1615 Name horner avaliação polinomialracional hornerPx Parâmetros P matriz de polinômios ou de razões de polinômios x número real polinômio ou razão de polinômios Descrição Avalia a matriz de polinômios ou de razões de polinômios P Ps quando a variável s do polinômio é substituida por x hornerPxPx Exemplo transformação bilinear admita que P Ps uma matriz de razões de polinômios então a matriz de razões de polinômios P1s1s é obtida por hornerP1s1s Para avaliar uma matriz de razões de polinômios em dadas freqüências use preferivelmente a primitiva freq Exemplos avaliação de um polinômio para um vetor de números Ppoly13x hornerP1 2 5 hornerP1 2 5i avaliação de uma razão spoly0sMs1s hornerM1 hornerMi hornerM1s avaliação de um polinômio para uma matriz de números X 1 23 4 ppoly13xc mhornerp X 1X02X13X2 Ver Também freq repfreq evstr 1616 Name hrmt máximo divisor comum de polinômios pgUhrmtv Parâmetros v vetor linha de polinômios ie matriz de polinômios 1xk pg polinômio U matriz de polinômios unimodular Descrição pgUhrmtv retorna uma matriz unimodular U e pg MDC do vetor linha de polinômios v tais que vU pg0 Exemplos xpoly0x vxx1x2x1x2x13x22x1 pgUhrmtvUcleanU detU Ver Também gcd htrianr Autor S Steer INRIA 1617 Name htrianr triangularização de matrizes de polinômios ArUrkhtrianrA Parâmetros A matriz de polinômios Ar matriz de polinômios U matriz unimodular de polinômios rk inteiro posto normal def A Descrição Triangularização da matriz de polinômios A A is mn m n ArAU Aviso há eliminação de termos pequenos ver código da função Exemplos xpoly0x Mxx22x31x2x4 MuUrkhtrianrM detU MU12 Ver Também hrmt colcompr 1618 Name invr inversão de matrizes de razões de polinômios F invrH Parâmetros H matriz de polinômios ou de razões de polinômios F matriz de polinômios ou de razões de polinômios Descrição Se H é uma matriz de polinômios ou de razões de polinômios invr computa H1 utilizando o algoritmo de Leverrier ver código da função Exemplos spoly0s Hsss21s1s invrH NumdencoffgHNumden H1ss11s2s3sinvrH Ver Também glever coffg inv 1619 Name lcm mínimo múltiplo comum ppfactlcmp Parâmetros p vetor de polinômios fact vetor de polinômios ou inteiros tipo igual a 8 pp polinômio ou inteiro Descrição pplcmp computa o MMC pp do vetor de polinômios p ppfactlcmp computa ainda o vetor fact tal que pfactpponesp Exemplos caso polinomial spoly0s psss12s2s2 ppfactlcmp pfact pp caso inteiro Vint322235 233222345 lcmV Ver Também gcd bezout 1620 Name lcmdiag fatoração diagonal por MMC NDlcmdiagH NDlcmdiagHflag Parâmetros H matriz de razões de polinômios N matriz de polinômios D matriz de polinômios diagonal flag string row ou col padrão Descrição NDlcmdiagHrow computa uma fatoração DHN ie HD1N onde D é uma matriz diagonal com DkkMMC da késima linha de Hden NDlcmdiagH ou NDlcmdiagHcol retorna HND1 com matriz diag onal D e DkkMMC da késima coluna de Hden Exemplos spoly0s H1ss2ss121s2s22s2 NDlcmdiagH NDH Ver Também lcm gcd bezout 1621 Name ldiv divisão longa entre matrizes de polinômios xldivndk Parâmetros nd duas matrizes de polinômios reais k inteiro Descrição xldivndk fornece os k primeiros coeficientes da divisão longa de n por d ie the a expansão de Taylor da matriz de razões de polinômios nijzdijz aproximandose do infinito Os coeficientes de expansão de nijdij são armazenados em xi1nkj k1n Exemplos wssssrand113abcdabcdwss wtfss2tfwss x1ldivnumerwtfdenomwtf5 x2cbcabca2bca3bca4b wssbismarkp2ssx1511 wtfbiscleanss2tfwssbis x3ldivnumerwtfbisdenomwtfbis5 Ver Também arl2 markp2ss pdiv 1622 Name numer numerador numnumerR Parâmetros R matriz de polinômios de razões de polinômios ou de constantes num matriz de polinômios Descrição Função utilitária numnumerR retorna o numerador num de uma matriz de funções racionais R R também pode ser uma matriz de polinômios ou de constantes numerR é equivalente a R2 Rnum ou Rnum Ver Também denom 1623 Name pdiv divisão polinomial RQpdivP1P2 QpdivP1P2 Parâmetros P1 matriz de polinômios P2 polinômio ou matriz de polinômios RQ duas matrizes de polinômios Descrição Divisão euclidiana elemento a elemento da matriz de polinômios P1 pelo polinômio P2 ou pela matriz de polinômios P2 Rij é a matriz de restos Qij é a matriz de quocientes e P1ij QijP2 Qij ou P1ij QijP2ij Qij Exemplos xpoly0x p11x21xp21x rqpdivp1p2 p2qp1 p21x rqpdivp1p2 p2qrp1 Ver Também ldiv gcd 1624 Name pol2des conversão de matrizes de polinômios para formas descritoras NBCpol2desDs Parâmetros Ds matriz de polinômios N B C três matrizes de reais Descrição Dada a matriz de polinômios DsD0 D1 s D2 s2 Dk sk pol2des retorna três matrizes N B C com sendo N nilpotente tais que Ds C sNeye1 B Exemplos spoly0s G1s1s23s3NBCpol2desG G1cleanCinvsNeyeBG2numerG1 Ver Também ss2des tf2des Autor FD 1625 Name pol2str conversão de polinômio para string strpol2strp Parâmetros p polinômio real str string Descrição Converte um polinômio para um string função utilitária Ver Também string pol2tex 1626 Name polfact fatores mínimos fpolfactp Parâmetros p polinômio f vetor f0 f1 fn tal que pprodf f0 constante fi polinômio Descrição fpolfactp retorna os valores mínimos de p ie ff0 f1 fn tal que pprodf Ver Também lcm cmndred factors Autor S Steer INRIA 1627 Name residu resíduo VresiduPQ1Q2 Parâmetros P Q1 Q2 polinômios ou matrizes de polinômios de coeficientes reais ou complexos Descrição VresiduPQ1Q2 retorna a matriz V tal que Vij é a soma dos resíduos da fração racional PijQ1ijQ2ij calculada nos zeros de Q1ij Q1ij e Q2ij não devem possuir raízes em comum Exemplos spoly0s Hss121s2NnumerHDdenomH wresiduNhornerNsDhornerDs Ns Ns Ds Ds sqrtsumw This is H2 norm h2normtf2ssH ps1s1s2s10as5s1sss122 bs3s25s3 residupab5318634410 Exato zpoly0zaz307z205z03bz303z202z01 atildgtildadbtildgtildbd residubbtildzaatild29488038 Exato aa0ibb0i realresidubbtildzaatild29488038 Caso complexo Ver Também pfss bdiag roots poly gtild Autor FDelebecque INRIA 1628 Name roots raízes de polinômios xrootsp xrootspe Parâmetros p polinômio com coeficientes reais ou complexos ou vetor dos coeficientes do polinômio em ordem de graus decrescentes para compatibilidade com o Matlab Descrição xrootsp retorna no vetor de complexos x as raízes do polinômio p Para polinômios reais de grau 100 o algoritmo rápido RPOLY é utilizado Em outros casos as raízes são computadas como os autovalores da matriz companheira associada Use xrootspe para forçar este algoritmo em qualquer caso Exemplos ppoly0101i1ix rootsp Arand33rootspolyAx avaliações por polinômios característicos specA Ver Também poly spec companion Autor Serge Steer INRIA References O algoritmo RPOLY é descrito em Algorithm 493 Zeros of a Real Polynomial ACM TOMS Vol ume 1 edição 2 Junho 1975 pp 178189 Jenkins M A e Traub J F 1970 A ThreeStage Algorithm for Real Polynomials Using Quadratic Iteration SIAM J Numer Anal 71970 545566 Jenkins M A e Traub J F 1970 Principles for Testing Polynomial Zerofinding Programs ACM TOMS 1 1 Março1975 pp 2634 Funções Utilizadas O código fonte de rpolyf pode ser achado no diretório SCImodulespolynomialssrcfortran de uma distribuição fonte do Scilab A computação de autovalores é feita utilizandose os códigos do LA PACK DGEEV e ZGEEV 1629 Name rowcompr compressão de linhas de uma matriz de polinômios XrkAcrowcomprA Parâmetros A matriz de polinômios Y matriz de polinômios quadrada base unimodular esquerda rk posto normal de A Ac AcXA matriz de polinômios Descrição Compressão de linhas da matriz de polinômios A X é uma base polinomial unimodular esquerda que comprime as linhas de A rk é o posto normal de A Aviso há eliminação de termos pequenos utilize com cuidado Ver Também colcompr 1630 Name sfact fatoração espectral em tempo discreto FsfactP Parâmetros P matriz de polinômios reais Descrição Acha F um fator espectral de P P é uma matriz de polinômios tal que cada raiz de P possui uma imagem simétrica em relação ao círculo unitário O problema é singular se uma raiz estiver no círculo unitário sfactP retorna uma matriz de polinômios Fz que é antiestável e tal que P Fz F1z zn Para polinômios escalares um algorimto específico é implementado Os algoritmos são implementados do livro de Kucera Exemplos exemplo polinomial zpoly0z pz122z wsfactp wnumerhornerw1z exemplo matricial F1z12z12z221zzz32zz12z PF1gtildF1d P é simétrica FsfactP rootsdetP rootsdetgtildFd as raízes estáveis rootsdetF as raízes antiestáveis cleanPFgtildFd exemplo de uso de tempo contínuo spoly0s p3s1is1is05s05s1is1iprealp ps polinômio em s2 procura por f estável tal que pfsfs whornerp1s1s transformação bilinear wp1s1s wnnumerw tomando o numerador fnsfactwnfnumerhornerfn1ss1 fator e transformação de volta ffsqrthornerfgtildfc0ffsqrthornerp0 normalização rootsf f é estável cleanfgtildfcp fsfs é ps Ver Também gtild fspecg 1631 Name simp simplificação racional N1D1simpND H1simpH Parâmetros ND polinômios reais ou matrizes de polinômios reais H matriz de razões de polinômios ie matriz com entradas nd n e d polinômios reais Descrição n1d1simpnd calcula dois polinômios n1 e d1 tais que n1d1 nd Se N e D são matrizes de polinômios os cálculos são feitos elemento a elemento H1simpH também é válido cada entrada de H é simplificada em H1 Cuidado Nenhum limiar é dado ie simp não pode forçar uma simplificação Para sistemas lineares dinâmicos que incluem integradores a simplificação modifica o ganho estático H0 para sistemas contínuos H1 para sistemas discretos Para dados complexos simp retorna suas entradas Uma simplificação racional é chamada após aproximadamente cada operação sobre razões de polinômios É possível alternar o modo de simplificação entre on e off ligado e desligado uti lizando a função simpmode Exemplos spoly0s ndsimps1s2s1s2 simpmodeFhnsss simpmodeThnsss Ver Também roots trfmod poly clean simpmode 1632 Name simpmode modifica o modo de simplificação racional modsimpmode simpmodemod Parâmetros mod um booleano Descrição A simplificação racional é chamada após quase cada operação sobre razões de polinômios É possível alternar o modo de simplificação entre on e off ligado e desligado utilizando a função simpmode simpmodt ajusta o modo de simplificação racional para on simpmodf ajusta o modo de simplificação racional para off modsimpmod retorna em mod o modo de simplificação racional corrente Exemplos spoly0s modsimpmode simpmodefhnsss simpmodethnsss simpmodemod Ver Também simp 1633 Name sylm matriz de Sylvester Ssylmab Parâmetros ab duas matrizes de polinômios S matriz Descrição sylmab fornece a matriz de Sylvester associada aos polinômios a e b ie a matriz S tal que coeff ax by S coeffxcoeffy A dimensão de S é igual a degreeadegreeb Se a e b são polinômios primos entre si então ranksylmabdegreeadegreeb e as instruções u sylmab eyenanb1 x polyu1nbzcoeff y polyunb1nanbzcoeff computam os fatores de Bezout x e y de graus mínimos tais que axby 1 1634 Name systmat matriz sistema SmsystmatSl Parâmetros Sl sistema linear lista syslin ou sistema descritor Sm feixe de matrizes Descrição Matriz sistema do sistema linear Sl lista syslin em forma de espaço de estados função utilitária Sm sI A B C D Para um sistema descritor SllistdesABCDE systmat retorna Sm sE A B C D Ver Também ss2des sm2des sm2ss Parte XXVIII Processamento de Sinais 1636 Índice 5 How to 1637 How to design an elliptic filter 1638 Capítulo 5 How to How to 1638 Nome How to design an elliptic filter How to design an elliptic filter analog and digital Description The goal is to design a simple analog and digital elliptic filter Designing an analog elliptic filter There are several possibilities to design an elliptic lowpass filter We can use analpf or zpell We will use zpell to produce the poles and zeros of the filter Once we have got these poles and zeros we will have to translate this representation into a syslin one And then the filter can be represented in bode plot analog elliptic Bessel order 2 cutoff 1 Hz Epsilon 3 ripple of filter in pass band 0epsilon1 A 60 attenuation of filter in stop band A1 OmegaC 10 pass band cutoff frequency in Hertz OmegaR 50 stop band cutoff frequency in Hertz Generate the filter zerospolsgain zpell3601050 Generate the equivalent linear system of the filter num gain realpolyzeross den realpolypolss elatf syslincnumden Plot the resulting filter bodeelatf001100 titleAnalog Elliptic filter Bode plot is only suited for analog filters How to 1639 If you want to design a highpass bandpass or bandstop filter you can first design a lowpass and then transfrom this lowpass filter using the trans function Designing a digital elliptic filter Now lets focus on how to produce a digital lowpass elliptic filter We can produce two kinds of digital filters an IIR Infinite Impulse Response To compute such a filter we can use the following functions iir eqiir a FIR Finite Impulse Response To compute such a filter we can use the following functions How to 1640 eqfir ffilt wfir fsfirlin For our demonstration we will use the iir function Order 2 The order of the filter Fs 1000 The sampling frequency Fcutoff 40 The cutoff frequency We design a low pass elliptic filter hz iirOrderlpellipFcutoffFs2 001 01 We compute the frequency response of the filter frqrepfrepfreqhz0000105 dbrepf phirepf dbphirepf And plot the bode like representation of the digital filter subplot211 plot2dFsfrqdbrepf xtitleObtained Frequency Response Magnitude subplot212 plot2dFsfrqphirepf xtitleObtained Frequency Response Phase in degree Here is the representation of the digital elliptic filter How to 1641 To represent the filter in phase and magnitude we need first to convert the discrete impulse response into magnitude and phase using the dbphi function This convertion is done using a set of normalized frequencies Filtering a signal using the digital filter Designing a filter is a first step Once done this filter will be used to transform a signal To get rid of some noise for example In the following examples we will filter a gaussian noise randnormal Input rand11000 Produce a random gaussian noise t 11000 sl tf2sshz From transfert function to syslin representation y fltsInputsl Filter the signal How to 1642 subplot211 plottInput xtitleThe gaussian noisety subplot212 plotty xtitleThe filtered gaussian noisety Here is the representation of the signal before and after filtering As we can see in the result the high frequencies of the noise have been removed and it remains only the low frequencies The signal is still noisy but it contains mainly low frequencies Filtering a signal using the analog filter To filter a signal using an analog filter we have two strategies transform the analog filter into a discrete one using the dscr function apply the csim function to filter the signal How to 1643 First we try using the dscr flts functions randnormal Input rand11000 Produce a random gaussian noise n 11000 The sample index eldtf dscrelatf1100 Discretization of the linear filter y fltsInputeldtf Filter the signal subplot211 plotnInput xtitleThe gaussian noiseny subplot212 plotny xtitleThe filtered gaussian noiseny Here is the representation of the signal before and after filtering using the dscr flts approach How to 1644 Next we use the csim function randnormal Input rand11000 Produce a random gaussian noise t 11000 t t001 Convert sample index into time steps y csimInputtelatf Filter the signal subplot211 plottInput xtitleThe gaussian noisety subplot212 plotty xtitleThe filtered gaussian noisety Here is the representation of the signal before and after filtering using the csim approach How to 1645 The main difference between the dscr flts approach and the csim approach the dscr flts uses samples whereas the csim functions uses time steps See Also bode iir poly syslin zpell flts tf2ss dscr csim trans analpf 1646 Name Signal Signal manual description Filters analpf analog lowpass filter buttmag squared magnitude response of a Butterworth filter casc creates cascade realization of filter cheb1mag square magnitude response of a type 1 Chebyshev filter cheb2mag square magnitude response of a type 1 Chebyshev filter chepol recursive implementation of Chebychev polynomial convol convolution of 2 discrete series ell1 mag squared magnitude of an elliptic filter eqfir minimax multiband linear phase FIR filter eqiir design of iir filter faurre optimal lqg filter lindquis optimal lqg filter lindquist algorithm ffilt FIR lowpasshighpass bandpass or stopband filter filter compute the filter model findfreq parameter compatibility for elliptic filter design findm for elliptic filter design frmag magnitude of the frequency responses of FIR and IIR filters fsfirlin design of FIR linear phase frequency sampling technique fwiir optimum design of IIR filters in cascade realization Signal 1647 iir designs an iir digital filter using analog filter designs iirgroup group delay of iir filter iirlp Lp IIR filters optimization group calculate the group delay of a digital filter remezb minimax approximation of a frequency domain magnitude response kalm Kalman update and error variance lev resolve the YuleWalker equations levin solve recursively Toeplitz system normal equations srfaur squareroot algorithm for the algebraic Riccati equation srkf squareroot Kalman filter algorithm sskf steadystate Kalman filter system generates the next observation given the old state trans transformation of standardized lowpass filter into lowpass highpass bandpass stopband wfir linearphase windowed FIR lowpass bandpass highpass stopband wiener Wiener estimate forwardbackward Kalman filter formulation wigner timefrequency wigner spectrum of a signal window calculate symmetric window zpbutt Butterworth analog filter zpch1 poles of a type 1 Chebyshev analog filter zpch2 poles and zeros of a type 2 Chebyshev analog filter zpell poles and zeros of prototype lowpass elliptic filter Signal 1648 Spectral estimation corr correlation coefficients cspect spectral estimation using the modified periodogram method czt chirp ztransform algorithm intdec change the sampling rate of a 1D or 2D signal mese calculate the maximum entropy spectral estimate pspect auto and crossspectral estimate wigner WignerVille timefrequency spectral estimation Transforms dft discrete Fourier transform fft fast flourier transform hilb Hilbert transform centred around the origin hank hankel matrix of the covariance sequence of a vector process mfft fft for a multidimensional signal Identification lattnlattp recursive solution of normal equations phc State space realisation by the principal hankel component approximation method rpem identification by the recursive prediction error method Miscellaneous sinc calculate the function sin2pifltpit sincd calculates the function SinNxSinx Signal 1649 k Jacobis complete elliptic integral asn TP the elliptic integral sn Jacobi s elliptic function with parameter m bilt bilinear transform or biquadratic transform jmat permutes block rows or block columns of a matrix 1650 Name analpf create analog lowpass filter hspolszersgainanalpfnfdesignrpomega Parameters n positive integer filter order fdesign string filter design method butt or cheb1 or cheb2 or ellip rp 2vector of error values for cheb1 cheb2 and ellip filters where only rp1 is used for cheb1 case only rp2 is used for cheb2 case and rp1 and rp2 are both used for ellip case 0rp1rp21 for cheb1 filters 1rp1ripple1 in passband for cheb2 filters 0ripplerp2 in stopband for ellip filters 1rp1ripple1 in passband 0ripplerp2 in stopband omega cutoff frequency of lowpass filter in Hertz hs rational polynomial transfer function pols poles of transfer function zers zeros of transfer function gain gain of transfer function Description Creates analog lowpass filter with cutoff frequency at omega hsgainpolyzersspolypolss Examples Evaluate magnitude response of continuoustime system hsanalpf4cheb11 05 fr0115 hffreqhs2hs3ifr hmabshf plotfrhm Authors C B 1652 Name bilt bilinear or biquadratic transform SISO system given by a zeropoles representation nplnzrngn biltplzrgnnumden Parameters pl a vector the poles of the given system zr a vector the zeros of the given system num a polynomial with degree equal to the degree of den the numerator of the transform den a polynomial with degree 1 or 2 the denominator of the transform npl a vector the poles of the transformed system nzr a vector the zeros of the transformed system ngn a scalar the gain of the transformed system Description function for calculating the gain poles and zeros which result from a bilinear transform or from a biquadratic transform Used by the functions iir and trans Examples Hlpiir3lpellip01 008 03 plrootsHlpden zrrootsHlpnum gncoeffHlpnumdegreeHlpnumcoeffHlpdendegreeHlpden zpoly0z a03 numza den1az nplnzrngn biltplzrgnnumden Hlptngnpolynzrzrpolynplzr comparison with horner hornerHlpnumden Authors Carey Bunks bilt 1653 See Also iir trans horner 1654 Name buttmag response of Butterworth filter hbuttmagorderomegacsample Parameters order integer filter order omegac real cutoff frequency in Hertz sample vector of frequency where buttmag is evaluated h Butterworth filter values at sample points Description squared magnitude response of a Butterworth filter omegac cutoff frequency sample sample of frequencies Examples squared magnitude response of Butterworth filter hbuttmag1330011000 mag20loghlog10 plot2d11000mag2011 0180100020 Authors F D 1655 Name casc cascade realization of filter from coefficients celscascxz Parameters x 4xNmatrix where each column is a cascade element the first two column entries being the numerator coefficients and the second two column entries being the denominator coefficients z string representing the cascade variable cels resulting cascade representation Description Creates cascade realization of filter from a matrix of coefficients utility function Examples x123456789101112 celscascxz 1656 Name cepstrum cepstrum calculation fresp cepstrumwmag Parameters w positive real vector of frequencies radsec mag real vector of magnitudes same size as w fresp complex vector Description fresp cepstrumwmag returns a frequency response frespi whose magnitude at fre quency wi equals magi and such that the phase of freq corresponds to a stable and minimum phase system w needs not to be sorted but minimal entry should not be close to zero and all the entries of w should be different Examples w01015mag1abssinw frespcepstrumwmag plot2dwwmagabsfresp See Also frfit 1657 Name cheb1mag response of Chebyshev type 1 filter h2cheb1magnomegacepsilonsample Parameters n integer filter order omegac real cutoff frequency epsilon real ripple in pass band sample vector of frequencies where cheb1mag is evaluated h2 Chebyshev I filter values at sample points Description Square magnitude response of a type 1 Chebyshev filter omegacpassband edge epsilonsuch that 11epsilon2passband ripple samplevector of frequencies where the square magnitude is desired Examples Chebyshev ripple in the passband n13epsilon02omegac3sample000510 hcheb1magnomegacepsilonsample plot2dsampleh xtitlefrequenciesmagnitude See Also buttmag 1658 Name cheb2mag response of type 2 Chebyshev filter h2cheb2magnomegarAsample Parameters n integer filter order omegar real scalar cutoff frequency A attenuation in stop band sample vector of frequencies where cheb2mag is evaluated h2 vector of Chebyshev II filter values at sample points Description Square magnitude response of a type 2 Chebyshev filter omegar stopband edge sample vector of frequencies where the square magnitude h2 is desired Examples Chebyshev ripple in the stopband n10omegar6A102sample0000100510 h2cheb2magnomegarAsample plotsamplelogh2log10frequenciesmagnitude in dB Plotting of frequency edges minvalmaxilogh2log10 plot2domegaromegarminval02000 Computation of the attenuation in dB at the stopband edge attenuationlogAAlog10 plot2dsampleattenuationonessample5000 See Also cheb1mag 1659 Name chepol Chebychev polynomial Tnchepolnvar Parameters n integer polynomial order var string polynomial variable Tn polynomial in the variable var Description Recursive implementation of Chebychev polynomial Tn2poly0varchepoln1varchepoln2var with T01 and T1poly0var Examples chepol4x Authors F D 1660 Name convol convolution yconvolhx ye1convolhxe0 Parameters h a vector first input sequence short one x a vector second input sequence long one e0 a vectorold tail to overlap add not used in first call y a vector the convolution e1 new tail to overlap add not used in last call Description Calculates the convolution y hx of two discrete sequences by using the fft The convolution is defined as follow Overlap add method can be used USE OF OVERLAP ADD METHOD For xx1x2xNm1xN First call is y1e1convolhx1 Subsequent calls ykekconvolhxkekm1 Final call yNconvolhxNeNm1 Finally yy1y2yNm1yN The algorithm based on the convolution definition is implemented for polynomial product yconvolhx is equivalent to ycoeffpolyhzcpolyxzc but much more efficient if x is a long array Examples x13 h110000h201000h300100 x1convolh1xx2convolh2xx3convolh3x convolh1h2h3x p1polyxxcoeff p2polyh1h2h3xcoeff p1p2 See Also corr fft pspect convol 1661 Authors F D C Bunks Date 3 Oct 1988 1662 Name corr correlation covariance covMeancorrxynlags covMeancorrfftxmacroymacronsect wxucorrupdtx1y1w0 wxucorrupdtx2y2wxu wkcorrupdtxkykwxu Parameters x a real vector y a real vector default value x nlags integer number of correlation coefficients desired xmacro a scilab external see below ymacro a scilab external see below default value xmacro n an integer total size of the sequence see below sect size of sections of the sequence see below xi a real vector yi a real vectordefault value xi cov real vector the correlation coefficients Mean real number or vector the mean of x and if given y Description Computes n m 1 covm xk xmean ymk ymean n k 1 corr 1663 for m0nlag1 and two vectors xx1xn yy1yn Note that if x and y sequences are differents corrxy is different with corryx Short sequences covMeancorrxynlags returns the first nlags correlation coefficients and Mean meanx mean of xy if y is an argument The sequence x resp y is assumed real and x and y are of same dimension n Long sequences covMeancorrfftxmacroymacronsect Here xmacro is either a function of type xxxmacrosectistart which returns a vector xx of dimension nsect containing the part of the sequence with indices from istart to istartsect1 a fortran subroutine or C procedure which performs the same calculation See the source code of dgetx for an example n total size of the sequence sect size of sections of the sequence sect must be a power of 2 cov has dimension sect Calculation is performed by FFT Updating method wxucorrupdtx1y1w0 wxucorrupdtx2y2wxu wkcorrupdtxkykwxu With this calling sequence the calculation is updated at each call to corr w0 0ones12nlags nlags power of 2 x1x2 are parts of x such that xx1x2 and sizes of xi a power of 2 To get nlags coefficients a final fft must be performed cfftw1n covc1nlags n is the size of x y Caution this calling sequence assumes that xmean ymean 0 Examples xpi10pi101024pi randseedrandnormal y8sinx8sin2xrandx8sinx8sin199xrandx c for j12for k12cccorrykyj64endend cmatrixc2128cov for j164covcovcj1212jend randunif randnormalxrand1256yx deffzxxinciszxisisinc1 deffzyyinciszyisisinc1 cmxycorrxy32 xxmxy1onesxyymxy2onesy centring c1corrxy32c2corrx32 corr 1664 normc1c21 c3m3corrfftxxyy25632 normc1c31 c4m4corrfftxx25632 normm31normm41 normc3c11normc4c21 x1x1128x2x129256 y1y1128y2y129256 w00ones164 32 coeffs w1xucorrux1y1w0w2corrux2y2w1xu zzrealfftw21256c5zz132 normc5c11 w1xucorrux1w0w2corrux2w1xu zzrealfftw21256c6zz132 normc6c21 randunif test for Fortran or C external deffyxmacrosecistysinististsec1 xxmacro1001 cc1mm1corrx23 ccmmcorrfftxmacro10023 cc2mm2corrfftcorexx10023 maxiabscccc1maxiabsmmmm1maxiabscccc2maxiabsmmmm2 deffyymacrosecistycosististsec1 yymacro1001 cc1mm1corrxy23 ccmmcorrfftxmacroymacro10023 cc2mm2corrfftcorexxcorexy10023 maxiabscccc1maxiabsmmmm1maxiabscccc2maxiabsmmmm2 See Also fft 1665 Name cspect two sided crossspectral estimate between 2 discrete time signals using the correlation method sm cwpcspectnlagsnpointswtypex y wpar sm cwpcspectnlagsnpointswtypenx ny wpar Parameters x vector the data of the first signal y vector the data of the second signal If y is omitted it is supposed to be equal to x autocorrela tion If it is present it must have the same numer of element than x nx a scalar the number of points in the x signal In this case the segments of the x signal are loaded by a user defined function named getx see below ny a scalar the number of points in the y signal In this case the segments of the y signal are loaded by a user defined function named gety see below If present ny must be equal to nx nlags number of correlation lags positive integer npoints number of transform points positive integer wtype The window type re rectangular tr triangular hm Hamming hn Hanning kr Kaiserin this case the wpar argument must be given ch Chebyshev in this case the wpar argument must be given wpar optional parameters for Kaiser and Chebyshev windows kr wpar must be a strictly positive number ch wpar must be a 2 element vector mainlobewidthsidelobeheightwith 0mainlobewidth5 and sidelobeheight0 sm The power spectral estimate in the interval 01 of the normalized frequencies It is a row array of size npoints The array is real in case of autocorrelation and complex in case of cross correlation cspect 1666 cwp the unspecified Chebyshev window parameter in case of Chebyshev windowing or an empty matrix Description Computes the crossspectrum estimate of two signals x and y if both are given and the autospectral estimate of x otherwise Spectral estimate obtained using the correlation method The cross spectrum of two signal x and y is defined to be The correlation method calculates the spectral estimate as the Fourier transform of a modified estimate of the autocross correlation function This autocross correlation modified estimate consist of repeat edly calculating estimates of the autocorrelation function from overlapping subsegments if the data and then averaging these estimates to obtain the result The number of points of the window is 2nlags1 For batch processing the x and y data may be read segment by segment using the getx and gety user defined functions These functions have the following calling sequence xkgetxnsoffset and ykgetynsoffset where ns is the segment size and offset is the index of the first element of the segment in the full signal Warning For Scilab version up to 502 the returned value was the modulus of the current one Reference Oppenheim AV and RW Schafer DiscreteTime Signal Processing Upper Saddle River NJ Pren ticeHall 1999 Examples randnormalrandseed0 xrand11024331 make lowpass filter with eqfir nf33bedge0 1125 5des1 0wate1 1 heqfirnfbedgedeswate filter white data to obtain colored data h1h 0ones1maxisizex1 x1x 0ones1maxisizeh1 hfffth11 xffftx11yfhfxfyrealfftyf1 smcspect100200try smsizemaxisizesmfr1smsizesmsize plotfrlogsm See Also pspect mese corr Authors C Bunks INRIA 1668 Name czt chirp ztransform algorithm czxcztxmwphiatheta Parameters x input data sequence m czt is evaluated at m points in zplane w magnitude multiplier phi phase increment a initial magnitude theta initial phase czx chirp ztransform output Description chirp ztransform algorithm which calcultes the ztransform on a spiral in the zplane at the points aexpjthetawkexpjkphi for k01m1 Examples a7expipi6 ffrbdsxgetech preserve current context rect1212sqrt21212sqrt2 t2pi0179179xsetech00051 plot2dsintcost2012 rect plot2d0 reala0 imaga3000 xsegs100100010010 w093expipi15wexp09logw0zaw zrrealzziimagz plot2dzrzi5000 xsetech050051 plot2dsintcost2012 rect plot2d0 reala0 imaga1000 xsegs100100010010 w0w09393wexp09logw0zaw zrrealzziimagz plot2dzrzi5000 xsetechffrbds restore context Authors C Bunks 1670 Name detrend remove constant linear or piecewise linear trend from a vector y detrendx y detrendxflag y detrendxflagbp Parameters x vector or matrix of real or complex numbers the signal to treat flag a string equal to linear or l for linear or piecewise linear treatment or constant or c for constant treatment bp the breakpoints to provide if you want a piecewise linear treatment y output the signal x with the trend removed from it Description This function removes the constant or linear or piecewise linear trend from a vector x In general this can be useful before a fourier analysis If x is matrix this function removes the trend of each column of x When flag constant or c detrend removes the constant trend simply the mean of the signal and when flag linear or l the function removes the linear trend By adding a third argument bp it is possible to remove a continuous piecewise linear trend Note that the instants of the signal x goes from 0 to m1 m lengthx if x is a vector and m sizex1 in case x is a matrix So the breakpoints bpi must be reals in 0 m1 breakpoints outside are simply removed from bp vector The trend is got by a least square fit of x on the appropriate function space Examples example 1 t linspace016pi1000 x 20 t 03sin05t sint 2sin2t 05sin3t y detrendx clf plot2dtx ystyle2 5 legendbefore detrendafter detrend xgrid example 2 t linspace032pi2000 x abst16pi 03sin05t sint 2sin2t 05sin3t y detrendxlinear1000 clf plot2dtx ystyle2 5 legendbefore detrendafter detrend xgrid detrend 1671 Authors Bruno Pincon 1672 Name dft discrete Fourier transform xfdftxflag Parameters x input vector flag indicates dft flag1 or idft flag1 xf output vector Description Function which computes dft of vector x Examples n8omega exp2piin j0n1Fomegajj Fourier matrix x18xx Fx fftx1 dftx1 invFx fftx1 dftx1 See Also fft Authors C B 1673 Name ell1mag magnitude of elliptic filter vell1magepsm1z Parameters eps passband ripple11eps2 m1 stopband ripple11eps2m1 z sample vector of values in the complex plane v elliptic filter values at sample points Description Function used for squared magnitude of an elliptic filter Usually m1epsepsaa1 Returns vrealoneszoneszepsepsss for ssnzm1 Examples deffalphaBeTaalphabetanmm1 if 2intn2n then BeTaK1 else BeTa0end alphak1m1k1m epsilon01A10 ripple parameters m1epsilonepsilonAA1n5omegac6 mfindfreqepsilonAnomegar omegacsqrtm k1m1kmkm1k1mn Check alphaBetaalphabetanmm1 alphaasn1mnkm1 Check sample000120 Now we map the positive real axis into the contour zalphaasnsampleomegacmBetaonessample plotsampleell1magepsilonm1z See Also buttmag 1674 Name eqfir minimax approximation of FIR filter hneqfirnfbedgedeswate Parameters nf number of output filter points desired bedge Mx2 matrix giving a pair of edges for each band des Mvector giving desired magnitude for each band wate Mvector giving relative weight of error in each band hn output of linearphase FIR filter coefficients Description Minimax approximation of multiband linear phase FIR filter Examples hneqfir330 225 354 50 1 01 1 1 hmfrfrmaghn256 plotfrhm Authors C B 1675 Name eqiir Design of iir filters cellsfactzzeroszpoleseqiirftypeapproxomdeltapdeltas Parameters ftype filter type lphpsbbp approx design approximation buttcheb1cheb2ellip om 4vector of cutoff frequencies in radians omom1om2om3om4 0 om1 om2 om3 om4 pi When ftypelp or hp om3 and om4 are not used and may be set to 0 deltap ripple in the passband 0 deltap 1 deltas ripple in the stopband 0 deltas 1 cells realization of the filter as second order cells fact normalization constant zzeros zeros in the zdomain zpoles poles in the zdomain Description Design of iir filter based on syredi The filter obtained is hzfactproduct of the elements of cells That is hzfactprodcellsnumprodcellsden Examples cellsfactzzeroszpoleseqiirlpellip2pi104pi100020001 hfactpolyzzeroszpolyzpolesz See Also eqfir iir syredi 1676 Name faurre filter computation by simple Faurre algorithm PRTfaurrenHFGR0 Parameters n number of iterations H F G estimated triple from the covariance sequence of y R0 Eykyk P solution of the Riccati equation after n iterations R T gain matrix of the filter Description This function computes iteratively the minimal solution of the algebraic Riccati equation and gives the matrices R and T of the filter model The algorithm tries to compute the solution P as the growing limit of a sequence of matrices Pn such that 1 Pn1FPnFGFPnhR0HPnH GHPnF 1 P0GR0 G Note that this method may not convergeespecially when F has poles near the unit circle Use preferably the srfaur function See Also srfaur lindquist phc Authors G Le V 1677 Name ffilt coefficients of FIR lowpass xffiltftnflfh Parameters ft filter type where ft can take the values lp for lowpass filter hp for highpass filter bp for bandpass filter sb for stopband filter n integer number of filter samples desired fl real low frequency cutoff fh real high frequency cutoff x vector of filter coefficients Description Get n coefficients of a FIR lowpass highpass bandpass or stopband filter For low and highpass filters one cutoff frequency must be specified whose value is given in fl For bandpass and stop band filters two cutoff frequencies must be specified for which the lower value is in fl and the higher value is in fh Authors C B 1678 Name fft fast Fourier transform ifft fast Fourier transform xffta 1 or xffta xffta1 or xiffta xffta1dimincr xffta1dimincr Parameters x real or complex vector Real or complex matrix 2dim fft a real or complex vector matrix or multidimensionnal array dim integer incr integer Description Short syntax direct xffta1 or xffta gives a direct transform single variate If a is a vector a single variate direct FFT is computed that is xksum over m from 1 to n of amexp2ipim1k1n for k varying from 1 to n nsize of vector a the 1 argument refers to the sign of the exponent NOT to inverse multivariate If a is a matrix or or a multidimensionnal array a multivariate direct FFT is performed inverse afftx1 or aifftxperforms the inverse transform normalized by 1n single variate If a is a vector a single variate inverse FFT is computed multivariate If a is a matrix or or a multidimensionnal array a multivariate inverse FFT is performed Long syntax for multidimensional FFT xffta1dimincr allows to perform an multidimensional fft If a is a real or complex vector implicitly indexed by j1j2jp ie aj1j2jp where j1 lies in 1dim1 j2 in 1dim2 one gets a pvariate FFT by calling p times fft as follows fft 1679 incrk1 xa for k1p xfftx 1dimkincrk incrkincrkdimk end where dimk is the dimension of the current variable wrt which one is integrating and incrk is the increment which separates two successive jk elements in a In particularif a is an mxn matrix xffta1 is equivalent to the two instructions a1ffta1m1 and xffta11nm Examples Comparison with explicit formula a123nsizea norm1nexp2ipi0n10n1na ffta1 normexp2ipi0n10n1na ffta1 Frequency components of a signal build a noides signal sampled at 1000hz containing to pure frequencies at 50 and 70 Hz samplerate1000 t 01samplerate06 Nsizet number of samples ssin2pi50tsin2pi70tpi4grand1Nnor01 yffts the fft response is symmetric we retain only the first N2 points fsamplerate0N2N associated frequency vector nsizef clf plot2dfabsy1n See Also corr 1680 Name fft2 twodimension fast Fourier transform yfft2x yfft2xnm Parameters x a vectormatrixarray Real or Complex y a vectormatrixarray Real or Complex m integer number of rows n integer number of columns Description This functions performs the twodimension discrete Fourier transform yfft2xy and x have the same size yfft2xmn If m respectively n is less than the rows number respectively columns of x then the x rows number resp columns is truncated else if m resp n is more than the rows number resp columns of x then x rows are completed by zero resp columns if x is a matrix then y is a matrix if x is a hypermatrix then y is a hypermatrix with the size of the first dimension of y is equal to m the size of the second dimension of y is equal to n the size of the ith dimension of y for i2 case hypermatrix equal to the size of the ith dimension of x ie sizey1m sizey2n and sizeyisizexi for i2 Examples Comparison with explicit formula a1 2 3 4 5 6 7 8 9 10 11 12 msizea1 nsizea2 fourier transform along the rows for i1n a1iexp2ipi0m10m1mai end fourier transform along the columns for j1m a2tempexp2ipi0n10n1na1j a2ja2temp end norma2fft2a See Also 1682 Name fftshift rearranges the fft output moving the zero frequency to the center of the spectrum yfftshiftx job Parameters x real or complex vector or matrix y real or complex vector or matrix job integer dimension selection or string all Description if x results of an fft computation y fftshiftx or y fftshiftxall moves the zero frequency component to the center of the spectrum which is sometimes a more convenient form If x is a vector of size n y is the vector xn21n1n2 If x is an m by n matrix y is the matrix xm21n1m2n21n1n2 x11 x12 x22 x21 x gives y x21 x22 x12 x11 y fftshiftxn make the swap only along the nth dimension Examples make a signal t0011000 x3sint8sin3t05sin5t3randt compute the fft yfftx1 display clf subplot211plot2dabsy subplot212plot2dfftshiftabsy make a 2D image t00130 x3sintcos2t8sin3tsin5t 05sin5tsin5t3randtrandt compute the fft yfftx1 display clf xsetcolormaphotcolormap256 fftshift 1683 subplot211Matplotabsy subplot212Matplotfftshiftabsy See Also fft 1684 Name filtsinc samples of sinc function xfiltsincnfl Parameters n number of samples fl cutoff frequency of the associated lowpass filter in Hertz x samples of the sinc function Description Calculate n samples of the function sin2pifltpit for tn12n12 ie centred around the origin Examples plotfiltsinc10001 See Also sincd Authors C B 1685 Name filter filters a data sequence using a digital filter yzf filternumdenx zi Parameters num real vector the coefficients of the filter numerator in decreasing power order or a polynomial den real vector the coefficients of the filter denominator in decreasing power order or a polynomial x real row vector the input signal zi real row vector of length maxlengthalengthb1 the initial condition relative to a direct form II transposed state space representation The default value is a vector filled with zeros y real row vector the filtered signal zf real row vector the final state It can be used to filter a next batch of the input signal Description This function filters a data sequence using a digital filter using a direct form II transposed imple mentation References Oppenheim A V and RW Schafer DiscreteTime Signal Processing Englewood Cliffs NJ Pren ticeHall 1989 pp 311312 See Also flts rtitr ltitr Authors Serge Steer INRIA 1686 Name findfreq parameter compatibility for elliptic filter design mfindfreqepsilonAn Parameters epsilon passband ripple A stopband attenuation n filter order m frequency needed for construction of elliptic filter Description Search for m such that nK1m1KmKm1K1m with m1epsilonepsilonAA1 If m omegar2omegac2 the parameters epsilonAomegacomegar and n are then compatible for defining a prototype elliptic filter Here Kkm is the complete elliptic integral with parameter m See Also k Authors F D 1687 Name findm for elliptic filter design mfindmchi Description Search for m such that chi k1mkm For use with findfreq See Also k Authors F D 1688 Name frfit frequency response fit sysfrfitwfresporder numdenfrfitwfresporder sysfrfitwfresporderweight numdenfrfitwfresporderweight Parameters w positive real vector of frequencies Hz fresp complex vector of frequency responses same size as w order integer required order degree of den weight positive real vector default value onesw numden stable polynomials Description sysfrfitwfresporderweight returns a bistable transfer function Gssysnumden of of given order such that its frequency response Gwi matches frespi ie freqnumdeniw should be close to fresp weighti is the weight given to wi Examples w0010012spoly0s Gsyslinc2s201s2 s2s1s203s1 fresprepfreqGw Gidfrfitwfresp4 frespfitrepfreqGidw bodewfrespfrespfit See Also frep2tf factors cepstrum mrfit freq calfrq 1689 Name frmag magnitude of FIR and IIR filters xmfrfrmagsysnpts xmfrfrmagnumdennpts Parameters sys a single input single output discrete transfer function or a polynomial or the vector of polynomial coefficients the filter num a polynomial or the vector of polynomial coefficients the numerator of the filter den a polynomial or the vector of polynomial coefficients the denominator of the filter the default value is 1 npts integer the number of points in frequency response xm vector of magnitude of frequency response at the points fr fr points in the normalized frequency domain where magnitude is evaluated Description calculates the magnitude of the frequency responses of FIR and IIR filters The filter description can be one or two vectors of coefficients one or two polynomials or a single output discrete transfer function the frequency discretisation is given by frlinspace012npts Authors Carey Bunks Examples hziir3bpcheb115 2508 03 hzmfrfrmaghz256 plotfrhzm hziir3bpellip15 2508 03 hzmfrfrmaghz256 plotfrhzmr See Also iir eqfir repfreq calfrq phasemag 1690 Name fsfirlin design of FIR linear phase filters frequency sampling technique hstfsfirlinhdflag Parameters hd vector of desired frequency response samples flag is equal to 1 or 2 according to the choice of type 1 or type 2 design hst vector giving the approximated continuous response on a dense grid of frequencies Description function for the design of FIR linear phase filters using the frequency sampling technique Examples Example of how to use the fsfirlin macro for the design of an FIR filter by a frequency sampling technique Two filters are designed the first response hst1 with abrupt transitions from 0 to 1 between passbands and stop bands the second response hst2 with one sample in each transition band amplitude 05 for smoothing hdzeros115 ones110 zeros139desired samples hst1fsfirlinhd1filter with no sample in the transition hd155hd265samples in the transition bands hst2fsfirlinhd1corresponding filter pas1prodsizehst15 fg0pas5normalized frequencies grid plot2d1 1fg1257hst1 hst2 2nd example hd0ones115 ones110 0ones139desired samples hst1fsfirlinhd1filter with no sample in the transition hd155hd265samples in the transition bands hst2fsfirlinhd1corresponding filter pas1prodsizehst15 fg0pas5normalized frequencies grid nprodsizehst1 plotfg1nhst1 plot2dfg1nhst23000 See Also ffilt wfir G Le Vey 1692 Name group group delay for digital filter tgfrgroupnptsa1ia2ib1ib2i Parameters npts integer number of points desired in calculation of group delay a1i in coefficient polynomial rational polynomial or cascade polynomial form this variable is the transfer function of the filter In coefficient polynomial form this is a vector of coefficients see below a2i in coeff poly form this is a vector of coeffs b1i in coeff poly form this is a vector of coeffs b2i in coeff poly form this is a vector of coeffs tg values of group delay evaluated on the grid fr fr grid of frequency values where group delay is evaluated Description Calculate the group delay of a digital filter with transfer function hz The filter specification can be in coefficient form polynomial form rational polynomial form cascade polynomial form or in coefficient polynomial form In the coefficient polynomial form the transfer function is formulated by the following expression hzproda1ia2izz2prodb1ib2izz2 Examples zpoly0z hzz5 tgfrgroup100h plotfrtg Authors C B 1693 Name hank covariance to hankel matrix hkhankmncov Parameters m number of blocrows n number of bloccolumns cov sequence of covariances it must be given as R0 R1 R2Rk hk computed hankel matrix Description this function builds the hankel matrix of size mdnd from the covariance sequence of a vector process Examples Example of how to use the hank macro for building a Hankel matrix from multidimensional data covariance or Markov parameters eg This is used eg in the solution of normal equations by classical identification methods Instrumental Variables eg 1lets generate the multidimensional data under the form Cc0 c1 c2 cn where each bloc ck is a ddimensional matrix eg the kth correlation of a ddimensional stochastic process Xt ck EXt Xtk being the transposition in scilab we take here d2 and n64 crand2264 generate the hankel matrix H with 4 blocrows and 5 bloccolumns from the data in c Hhank45c See Also toeplitz Authors G Le Vey 1694 Name hilb FIR approximation to a Hilbert transform filter xhhilbn wtype par Parameters n odd integer number of points in filter wtype string window type retrhnhmkrch default re par window parameter for wtypekr or ch default par0 0 see the function window for more help xh Hilbert transform Description Returns the first n points of an FIR approximation to a Hilbert transform filter centred around the origin The FIR filter is designed by appropraitely windowing the ideal impulse response hn2 npisinnpi22 for n not equal 0 and h00 An approximation to an analytic signal generator can be built by designing an FIR Finite Impulse Re sponse filter approximation to the Hilbert transform operator The analytic signal can then be comput ed by adding the appropriately timeshifted real signal to the imaginary part generated by the Hilbert filter References httpieeexploreieeeorgiel478782300330385pdf tparnumber330385isnumber7823 A Reilly G Frazer and B Boashash Analytic signal generation Tips and traps IEEE Trans Signal Processing vol 42 pp32413245 Nov 1994 See Also window hilbert Examples plothilb51 Authors C B 1695 Name hilbert Discretetime analytic signal computation of a real signal using Hilbert transform xhilbertxr Parameters xr real vector the real signal samples x Complex vector the discretetime analytic signal Description Returns theanalytic signal from a real data sequence The analytic signal x xr ixi has a real part xr which is the original data and an imaginary part xi which contains the Hilbert transform The imaginary part is a version of the original real sequence with a 90 phase shift References httpieeexploreieeeorgiel5781697500782222pdf arnumber782222 Marple SL Computing the discretetime analytic signal via FFT IEEE Transactions on Signal Processing Vol 47 No9 September 1999 pp26002603 See Also window hil Examples compare the discretetime analytic signal imaginary part of the impulse real signal with the FIR approximation of the Hilbert transform filter m25 n2m1 yhilberteyen1 hhilbn hhm1h1m plotimagy h Authors C B 1696 Name iir iir digital filter hziirnftypefdesignfrqdelta Parameters n positive number witn inteher value the filter order ftype string specifying the filter type the possible values are lp for lowpasshp for high passbp for band pass and sb for stop band fdesign string specifying the analog filter design the possible values are butt cheb1 cheb2 and ellip frq 2vector of discrete cutoff frequencies ie 0frq5 For lp and hp filters only frq1 is used For bp and sb filters frq1 is the lower cutoff frequency and frq2 is the upper cutoff frequency delta 2vector of error values for cheb1 cheb2 and ellip filters where only delta1 is used for cheb1 case only delta2 is used for cheb2 case and delta1 and delta2 are both used for ellip case 0delta1delta21 for cheb1 filters 1delta1ripple1 in passband for cheb2 filters 0rippledelta2 in stopband for ellip filters 1delta1ripple1 in passband and 0rippledelta2 in stopband Description function which designs an iir digital filter using analog filter designs and bilinear transformation Examples hziir3bpellip15 2508 03 hzmfrfrmaghz256 plot2dfrhzm xtitleDiscrete IIR filter band pass 015ltfrlt025 qpoly0q to express the result in terms of the delay operator qz1 hzdhornerhz1q See Also eqfir eqiir analpf bilt Authors Carey Bunks 1697 Name iirgroup group delay Lp IIR filter optimization ltgradiirgroupprthetaomegawttd coutgradindiirlpxindpflaglambdaomegaadwatdwt Parameters r vector of the module of the poles and the zeros of the filters theta vector of the argument of the poles and the zeros of the filters omega frequencies where the filter specifications are given wt weighting function for and the group delay td desired group delay lt grad criterium and gradient values Description optimization of IIR filters for the Lp criterium for the the group delay Rabiner Gold pp270273 1698 Name iirlp Lp IIR filter optimization costgradindiirlpxindpflaglambdaomegaadwatdwt Parameters x 1X2 vector of the module and argument of the poles and the zeros of the filters flag string a for amplitude gd for group delay default case for amplitude and group delay omega frequencies where the filter specifications are given wawt weighting functions for the amplitude and the group delay lambda weighting with 1lambda of the costs a and gd for getting the global cost ad td desired amplitude and group delay cost grad criterium and gradient values Description optimization of IIR filters for the Lp criterium for the amplitude andor the group delay Rabiner Gold pp270273 1699 Name intdec Changes sampling rate of a signal yintdecxlom Parameters x input sampled signal lom For a 1D signal this is a scalar which gives the rate change For a 2D signal this is a 2Vector of sampling rate changes lomcol rate changerow rate change y Output sampled signal Description Changes the sampling rate of a 1D or 2D signal by the rates in lom Authors C B 1700 Name jmat row or column block permutation jjmatnm Parameters n number of block rows or block columns of the matrix m size of the square blocks Description This function permutes block rows or block columns of a matrix 1701 Name kalm Kalman update x1p1xpkalmyx0p0fghqr Parameters fgh current system matrices q r covariance matrices of dynamics and observation noise x0p0 state estimate and error variance at t0 based on data up to t1 y current observation Output from the function is x1p1 updated estimate and error covariance at t1 based on data up to t0 x updated estimate and error covariance at t0 based on data up to t0 Description function which gives the Kalman update and error variance Authors C B 1702 Name lattn recursive solution of normal equations lalblattnnpcov Parameters n maximum order of the filter p fixed dimension of the MA part If p 1 the algorithm reduces to the classical Levinson re cursions cov matrix containing the Rks dd matrices for a ddimensional processIt must be given the fol lowing way la listtype variable giving the successively calculated polynomials degree 1 to degree nwith co efficients Ak Description solves recursively on n p being fixed the following system normal equations ie identifies the AR part poles of a vector ARMAnp process where Rkk1nlag is the sequence of empirical covariances Authors G Le V 1703 Name lattp lattp lalblattpnpcov Description see lattn Authors GLevey 1704 Name lev YuleWalker equations Levinsons algorithm arsigma2rclevr Parameters r correlation coefficients ar autoRegressive model parameters sigma2 scale constant rc reflection coefficients Description resolve the YuleWalker equations using Levinsons algorithm Authors C B 1705 Name levin Toeplitz system solver by Levinson algorithm multidimensional lasiglevinncov Parameters n A scalar with integer value the maximum order of the filter cov A nlagd x d matrix It contains the Rk d x d matrices for a ddimensional process stored in the following way la A list the successively calculated Levinson polynomials degree 1 to n with coefficients Ak sig A list the successive meansquare errors Description function which solves recursively on n the following Toeplitz system normal equations where Rkk1nlag is the sequence of nlag empirical covariances Examples We use the levin macro for solving the normal equations on two examples a onedimensional and a twodimensional process We need the covariance sequence of the stochastic process This example may usefully be compared with the results from levin 1706 the phc macro see the corresponding help and example in it 1 A onedimensional process We generate the process defined by two sinusoids 1Hz and 2 Hz in additive Gaussian noise this is the observed process the simulated process is sampled at 10 Hz step 01 in t underafter t101100randnormal y1sin2pit1sin2pi2t1y1y1randy1plott1y1 covariance of y1 nlag128 c1corry1nlag c1c1c1 needs to be given columnwise see the section PARAMETERS of this help compute the filter for a maximum order of n10 la is a listtype variable each element of which containing the filters of order ranging from 1 to n try varying n in the ddimensional case this is a matrix polynomial square d X d sig gives the same way the meansquare error n15 la1sig1levinnc1 verify that the roots of la contain the frequency spectrum of the observed process y remember that y is sampled in our example at 10Hz T01s so that we need to retrieve the original frequencies 1Hz and 2 Hz through the log and correct scaling by the frequency sampling we verify this for each filter order for i1n s1rootsla1is1logs12pi1 now we get the estimated poles sorted positive ones only s1gsortimags1s1s11i2end the last two frequencies are the ones really present in the observed process the others are artifacts coming from the used model size This is related to the rather difficult problem of order estimation 2 A 2dimensional process 4 frequencies 1 2 3 and 4 Hz sampled at 01 Hz y1 y1sin2Pitsin2Pi2tGaussian noise y with y2 y2sin2Pi3tsin2Pi4tGaussian noise d2dt01 nlag64 t202pidt100 y2sint2sin2t2randt2sin3t2sin4t2randt2 c2 levin 1707 for j12 for k12 c2c2corry2ky2jnlagendend c2matrixc22128cov for j164covcovc2j1d1jdendcovar columnwise c2cov in the multidimensional case we have to compute the roots of the determinant of the matrix polynomial easy in the 2dimensional case but tricky if d3 We just do that here for the maximum desired filter order n mp is the matrix polynomial of degree n la2sig2levinnc2 mpla2ndeterminantmp11mp22mp12mp21 s2rootsdeterminants2logs22pi01same trick as above for 1D process s2gsortimags2s2s21dn2just the positive ones There the order estimation problem is seen to be much more difficult many artifacts The 4 frequencies are in the estimated spectrum but beneath many non relevant others See Also phc Authors G Le Vey 1708 Name lindquist Lindquists algorithm PRTlindquistnHFGR0 Parameters n number of iterations H F G estimated triple from the covariance sequence of y R0 Eykyk P solution of the Riccati equation after n iterations R T gain matrices of the filter Description computes iteratively the minimal solution of the algebraic Riccati equation and gives the matrices R and T of the filter model by the Lindquists algorithm See Also srfaur faurre phc Authors G Le V 1709 Name mese maximum entropy spectral estimation smfrmesex npts Parameters x Input sampled data sequence npts Optional parameter giving number of points of fr and sm default is 256 sm Samples of spectral estimate on the frequency grid fr fr npts equally spaced frequency samples in 05 Description Calculate the maximum entropy spectral estimate of x Authors C B 1710 Name mfft multidimensional fft xkmfftxflagdim Parameters x xijk input signal in the form of a row vector whose values are arranged so that the i index runs the quickest followed by the j index etc flag 1 FFT or 1 inverse FFT dim dimension vector which gives the number of values of x for each of its indices xk output of multidimensional fft in same format as for x Description FFT for a multidimensional signal For example for a three dimensional vector which has three points along its first dimension two points along its second dimension and three points along its third dimension the row vector is arranged as follows xx111x211x311 x121x221x321 x112x212x312 x122x222x322 x113x213x313 x123x223x323 and the dim vector is dim323 Authors C B 1711 Name mrfit frequency response fit sysmrfitwmagorder numdenmrfitwmagorder sysmrfitwmagorderweight numdenmrfitwmagorderweight Parameters w positive real vector of frequencies Hz mag real vector of frequency responses magnitude same size as w order integer required order degree of den weight positive real vector default value onesw numden stable polynomials Description sysmrfitwmagorderweight returns a bistable transfer function Gssysnum den of of given order such that its frequency response magnitude absGwi matches magi ie absfreqnumdeniw should be close to mag weighti is the weigth given to wi Examples w0010012spoly0s Gsyslinc2s201s2s2s1s203s1 syslincNumDen fresprepfreqGw magabsfresp Gidmrfitwmag4 frespfitrepfreqGidw plot2dwwmagabsfrespfit See Also cepstrum frfit freq calfrq 1712 Name asn elliptic integral yasnxm Parameters x upper limit of integral x0 can be a vector m parameter of integral 0m1 y value of the integral Description Calculates the elliptic integral If x is a vector y is a vector of same dimension as x Examples m08zasn1sqrtmmKrealzKtildeimagz x2max1sqrtm x100051x21x2max120x2maxx3x2max00510 xx1x2x3 yasnxm rect0Ktilde11K2Ktilde plot2drealyimagy1011 rect deffyfty1sqrt1t21mt2 intg009fasn09m Works for real case only Authors F D 1713 Name k Jacobis complete elliptic integral Kkm Parameters m parameter of the elliptic integral 0m1 m can be a vector K value of the elliptic integral from 0 to 1 on the real axis Description Calculates Jacobis complete elliptic integral of the first kind References Abramowitz and Stegun page 598 Examples m04 asn1m km See Also asn Authors FD 1714 Name sn Jacobi s elliptic function ysnxm Parameters x a point inside the fundamental rectangle defined by the elliptic integral x is a vector of complex numbers m parameter of the elliptic integral 0m1 y result Description Jacobi s sn elliptic function with parameter m the inverse of the elliptic integral for the parameter m The amplitude am is computed in fortran and the addition formulas for elliptic functions are applied Examples m036 Kkm P4K Real period realval0P50P plotrealvalrealsnrealvalm clf KKk1m Ip2KK imaval10Ip50KK0001 imaval2KK005Ip25IpKK z1sniimaval1mz2sniimaval2m plot2dimaval1imaval2imagz1imagz2 xgrid3 See Also asn k Authors F D 1715 Name phc Markovian representation HFGphchkdr Parameters hk hankel matrix d dimension of the observation r desired dimension of the state vector for the approximated model H F G relevant matrices of the Markovian model Description Function which computes the matrices H F G of a Markovian representation by the principal hankel component approximation method from the hankel matrix built from the covariance sequence of a stochastic process Examples This example may usefully be compared with the results from the levin macro see the corresponding help and example We consider the process defined by two sinusoids 1Hz and 2 Hz in additive Gaussian noise this is the observation the simulated process is sampled at 10 Hz t01100randnormal ysin2pitsin2pi2tyyrandyplotty covariance of y nlag128 ccorrynlag hankel matrix from the covariance sequence we can choose to take more information from covariance by taking greater n and m try it to compare the results n20m20 hhanknmc compute the Markov representation mhmfmg We just take here a state dimension equal to 4 this is the rather difficult problem of estimating the order Try varying ns the observation dimension is here equal to one phc 1716 ns4 mhmfmgphch1ns verify that the spectrum of mf contains the frequency spectrum of the observed process y remember that y is sampled in our example at 10Hz T01s so that we need to retrieve the original frequencies through the log and correct scaling by the frequency sampling sspecmfslogs ss2pi1 now we get the estimated spectrum imags See Also levin 1717 Name pspect two sided crossspectral estimate between 2 discrete time signals using the Welchs average periodogram method sm cwppspectsecstepseclengwtypex y wpar sm cwppspectsecstepseclengwtypenx ny wpar Parameters x vector the timedomain samples of the first signal y vector the timedomain samples of the second signal If y is omitted it is supposed to be equal to x autocorrelation If it is present it must have the same numer of element than x nx a scalar the number of samples in the x signal In this case the segments of the x signal are loaded by a user defined function named getx see below ny a scalar the number of samples in the y signal In this case the segments of the y signal are loaded by a user defined function named gety see below If present ny must be equal to nx secstep offset of each data window The overlap D is given by secleng secstep if secstepsecleng2 50 overlap is made The overlap secleng Number of points of the window wtype The window type re rectangular tr triangular hm Hamming hn Hanning kr Kaiserin this case the wpar argument must be given ch Chebyshev in this case the wpar argument must be given wpar optional parameters for Kaiser and Chebyshev windows kr wpar must be a strictly positive number ch wpar must be a 2 element vector mainlobewidthsidelobeheightwith 0mainlobewidth5 and sidelobeheight0 sm Two sided power spectral estimate in the interval 01 of the normalized frequencies It is a row array with seclen elements The array is real in case of autocorrelation and complex in case of crosscorrelation pspect 1718 The associated normalized frequencies array is linspace01seclen cwp unspecified Chebyshev window parameter in case of Chebyshev windowing or an empty matrix Description Computes the crossspectrum estimate of two signals x and y if both are given and the autospectral estimate of x otherwise Spectral estimate obtained using the modified periodogram method The cross spectrum of two signal x and y is defined to be The modified periodogram method of spectral estimation repeatedly calculates the periodogram of windowed subsections of the data containes in x and y These periodograms are then averaged to gether and normalized by an appropriate constant to obtain the final spectral estimate It is the aver aging process which reduces the variance in the estimate For batch processing the x and y data may be read segment by segment using the getx and gety user defined functions These functions have the following calling sequence xkgetxnsoffset and ykgetynsoffset where ns is the segment size and offset is the index of the first element of the segment in the full signal Reference Oppenheim AV and RW Schafer DiscreteTime Signal Processing Upper Saddle River NJ Pren ticeHall 1999 Examples randnormalrandseed0 xrand11024331 make lowpass filter with eqfir nf33bedge0 1125 5des1 0wate1 1 heqfirnfbedgedeswate filter white data to obtain colored data h1h 0ones1maxisizex1 x1x 0ones1maxisizeh1 hfffth11 xffftx11yrealffthfxf1 plot magnitude of filter h2h 0ones1968hf2ffth21hf2realhf2conjhf2 hsizemaxisizehf2fr1hsizehsizeplotfrloghf2 pspect example smpspect100200trysmsizemaxisizesmfr1smsizesmsize plotfrlogsm randunif See Also cspect pspect mese window C Bunks INRIA 1720 Name remez Remez exchange algorithm for the weighted chebyshev approximation of a continuous func tion with a sum of cosines anremezguessmagfgridweight Parameters guess real array of size n2 the initial guess fgrid real array of size ng the grid of normalized frequency points in 05 mag real array of size ng the desired magnitude on grid fg weight real array of size ng weighting function on error on grid fg an real array of size n cosine coefficients Description Minimax approximation of a frequency domain magnitude response The approximation takes the form h sumaicosweight i1n An FIR linearphase filter can be obtained from the the output of remez by using the following commands hn1nc1annc122 hnncan1 hnnc12nc1an2nc2 This function is mainly intended to be called by the remezb function Bibliography EW Cheney Introduction to Approximation Theory McGrawHill 1966 httpenwikipediaorgwikiRemezalgorithm References This function is based on the fortran code remezf written by James H Mcclellan department of electrical engineering and computer science Massachusetts In stitute of Technology Cambridge Massachussets 02139 Thomas W Parks department of electrical engineering Rice university Houston Texas 77001 remez 1721 Thomas W Parks department of electrical engineering Rice university Houston Texas 77001 Examples nc21 ngridnc250 fgrid50ngrid1ngrid1 mag1ngrid2ones1ngrid2 magngrid21ngrid0ones1ngrid2 weightonesfgrid guessround1ngridncngrid guessnc1ngrid guessnc2ngrid anremezguessmagfgridweight See Also remezb eqfir 1722 Name remezb Minimax approximation of magnitude response anremezbncfgdswt Parameters nc Number of cosine functions fg Grid of frequency points in 05 ds Desired magnitude on grid fg wt Weighting function on error on grid fg an Cosine filter coefficients Description Minimax approximation of a frequency domain magnitude response The approximation takes the form h sumancoswn for n01nc An FIR linearphase filter can be obtained from the the output of the function by using the following commands hn1nc1annc122 hnncan1 hnnc12nc1an2nc2 Examples Choose the number of cosine functions and create a dense grid in 024 and 265 nc21ngridnc16 fg240ngrid21ngrid21 fgngrid21ngridfg1ngrid226ones1ngrid2 Specify a low pass filter magnitude for the desired response ds1ngrid2ones1ngrid2 dsngrid21ngridzeros1ngrid2 Specify a uniform weighting function wtonesfg Run remezb anremezbncfgdswt Make a linear phase FIR filter hn1nc1annc122 hnncan1 remezb 1723 hnnc12nc1an2nc2 Plot the filters magnitude response plot50255256frmaghn256 Choose the number of cosine functions and create a dense grid in 05 nc21 ngridnc16 fg50ngrid1ngrid Specify a triangular shaped magnitude for the desired response ds1ngrid20ngrid21ngrid21 dsngrid21ngriddsngrid211 Specify a uniform weighting function wtonesfg Run remezb anremezbncfgdswt Make a linear phase FIR filter hn1nc1annc122 hnncan1 hnnc12nc1an2nc2 Plot the filters magnitude response plot50255256frmaghn256 See Also eqfir Authors C B 1724 Name rpem Recursive PredictionError Minimization estimation w1vrpemw0u0y0lambdakc Arguments w0 listthetaplphipsi where theta abc is a real vector of order 3n abc aa1an bb1bn cc1cn p 3n x 3n real matrix phipsil real vector of dimension 3n Applicable values for the first call thetaphipsil0ones13n peye3n3n u0 real vector of inputs arbitrary size u0 is not used by rpem y0 vector of outputs same dimension as u0 y01 is not used by rpem If the time domain is t0t0k1 the u0 vector contains the inputs ut0ut01ut0k1 and y0 the outputs yt0yt01yt0k1 Optional arguments lambda optional argument forgetting constant choosed close to 1 as convergence occur lambdalambda0alfabeta evolves according to lambdatalfalambdat1beta with lambda0lambda0 k contraction factor to be chosen close to 1 as convergence occurs kk0munu evolves according to rpem 1725 ktmukt1nu with k0k0 c Large argumentc1000 is the default value Outputs w1 Update for w0 v sum of squared prediction errors on u0 y0optional In particular w11 is the new estimate of theta If a new sample u1 y1 is available the update is obtained by w2vrpemw1u1y1lambdakc Arbitrary large series can thus be treated Description Recursive estimation of arguments in an ARMAX model Uses LjungSoderstrom recursive prediction error method Model considered is the following yta1yt1anytn b1ut1bnutnetc1et1cnetn The effect of this command is to update the estimation of unknown argument thetaabc with aa1an bb1bn cc1cn 1726 Name sincd digital sinc function or Direchlet kernel ssincdnflag Parameters n integer flag if flag 1 the function is centred around the origin if flag 2 the function is delayed by pi2n s vector of values of the function on a dense grid of frequencies Description function which calculates the function SinNxNSinx Examples plotsincd101 Authors G Le V 1727 Name srfaur squareroot algorithm pstlrtttsrfaurhfgr0npstl Parameters h f g convenient matrices of the statespace model r0 Eykyk n number of iterations p estimate of the solution after n iterations s t l intermediate matrices for successive iterations rt tt gain matrices of the filter model after n iterations p s t l may be given as input if more than one recursion is desired evaluation of intermediate values of p Description squareroot algorithm for the algebraic Riccati equation Examples GENERATE SIGNAL xpi10pi101024pi randseed0randnormal y11sinxsin2xsin19xrand21024 COMPUTE CORRELATIONS cfor j12for k12cccorrykyj64endend cmatrixc2128 FINDING HFG with 6 states hkhank2020c HFGphchk26 SOLVING RICCATI EQN r0c1212 PstlRtTtsrfaurHFGr0200 Make covariance matrix exactly symmetric RtRtRt2 srfaur 1728 See Also phc faurre lindquist 1729 Name srkf square root Kalman filter x1p1srkfyx0p0fhqr Parameters f h current system matrices q r covariance matrices of dynamics and observation noise x0 p0 state estimate and error variance at t0 based on data up to t1 y current observation Output from the function is x1 p1 updated estimate and error covariance at t1 based on data up to t0 Description square root Kalman filter algorithm Authors C B 1730 Name sskf steadystate Kalman filter xepesskfyfhqrx0 Parameters y data in form y0y1yn yk a column vector f system matrix dimNxN h observations matrix dimMxN q dynamics noise matrix dimNxN r observations noise matrix dimMxM x0 initial state estimate xe estimated state pe steadystate error covariance Description steadystate Kalman filter Authors C B 1731 Name syredi Design of iir filters syredi code interface factb2b1b0c1c0zzeroszpolessyrediitypiaproomdeltapdeltas Parameters itype integer the filter type 1 stands for lowpass 2 for highpass 3 for bandpass 4 for stopband iappro integer the design approximation type 1 stands for butterworth 2 for elliptic 3 for Chebytchev1 4 for Chebytchev2 om 4vector of cutoff frequencies in radians omom1om2om3om4 0 om1 om2 om3 om4 pi When ftypelp or hp om3 and om4 are not used and may be set to 0 deltap a real scalar the ripple in the passband 0 deltap 1 deltas a real scalar the ripple in the stopband 0 deltas 1 gain scalar the filter gain b2 real row vector degree 2 coefficients of numerators b1 real row vector degree 1 coefficients of numerators b0 real row vector degree 0 coefficients of numerators c1 real row vector degree 1 coefficients of denominators c0 real row vector degree 0 coefficients of denominators zzeros complex row vector filter zeros in the zdomain zpoles complex row vector filter poles in the zdomain Description Computes iir filter approximation The result is given as a set of second order transfer functions Hib0ib1izb2iz2c0ic1izz2 and also as a poles zeros gain representation The filter obtained is hfactH1Hn syredi 1732 Remark This builtin function is mainly intended to be used by the eqiir function References The syredi code is derived from doredi package written by Guenter F Dehner Institut fuer Nachrich tentechnik Universitaet ErlangenNuernberg Germany DehnerGF 1979 DOREDI Program for Design and Optimization of REcursive DIgital filtersPro grams for Digital Signal Processing edDigital Signal Processing committee of IEEE Acoustics Speech and Signal Processing Society For DOREDIf source code see httpmichaelgellistripodcomdsppgm25html Examples factb2b1b0c1c0zzeroszpolessyredi142pi104pi10000020001 hfactb0b1zb2z2c0c1zz2 See Also eqiir 1733 Name system observation update x1ysystemx0fghqr Parameters x0 input state vector f system matrix g input matrix h Output matrix q input noise covariance matrix r output noise covariance matrix x1 output state vector y output observation Description define system function which generates the next observation given the old state System recursively calculated x1fx0gu yhx0v where u is distributed N0q and v is distribute N0r Authors C B 1734 Name trans lowpass to other filter transform hzttranshztrtypefrq hzttranspdzdgdtrtypefrq Parameters hz a single input single output discrete transfer function the low pass filter pd Vector of given filter poles zd Vector of given filter zeros gd scalar the given filter gain trtype string the type of transformation see description for possible values frq 2vector of discrete cutoff frequencies ie0frq5 see description for details hzt transformed filter transfert function Description function for transforming standardized lowpass filter given its poleszerosgain representation into one of the following filters trtypelp low pass filter the cutoff frequency is given by the first entry of frq the second one is ignored trtypehp high pass filter the cutoff frequency is given by the first entry of frq the second one is ignored trtypebp band pass filter the frequency range is given by frq1 and frq2 trtypesb stop band filter the frequency range is given by frq1 and frq2 Used functions bilt Examples clf Hlpiir3lpellip01 008 03 trans 1735 HbptransHlpbp001 01 HsbtransHlpsb001 01 clfgainplotHlpHbpHsb1d3048 llegendoriginal low passband passstop band llegendlocationinlowerleft Authors Carey Bunks See Also iir bilt 1736 Name wfir linearphase FIR filters wftwfmfrwfirftypefordercfreqwtypefpar Parameters ftype string lphpbpsb filter type forder Filter order pos integerodd for ftypehp or sb cfreq 2vector of cutoff frequencies 0cfreq1cfreq25 only cfreq1 is used when ftypelp or hp wtype Window type retrhmhnkrch fpar 2vector of window parameters Kaiser window fpar10 fpar20 Chebyshev window fpar10 fpar20 or fpar10 0fpar25 wft time domain filter coefficients wfm frequency domain filter response on the grid fr fr Frequency grid Description Function which makes linearphase FIR lowpass bandpass highpass and stopband filters using the windowing technique Works interactively if called with no arguments Authors C Bunks 1737 Name wiener Wiener estimate xspsxfpfwieneryx0p0fghqr Parameters f g h system matrices in the interval t0tf f f0f1ff and fk is a nxn matrix g g0g1gf and gk is a nxn matrix h h0h1hf and hk is a mxn matrix q r covariance matrices of dynamics and observation noise q q0q1qf and qk is a nxn matrix r r0r1rf and gk is a mxm matrix x0 p0 initial state estimate and error variance y observations in the interval t0tf yy0y1yf and yk is a column mvector xs Smoothed state estimate xs xs0xs1xsf and xsk is a column nvector ps Error covariance of smoothed estimate psp0p1pf and pk is a nxn matrix xf Filtered state estimate xf xf0xf1xff and xfk is a column nvector pf Error covariance of filtered estimate pfp0p1pf and pk is a nxn matrix Description function which gives the Wiener estimate using the forwardbackward Kalman filter formulation Authors C B 1738 Name wigner timefrequency wigner spectrum tabwignerxhdeltatzp Parameters tab wigner spectrum lines correspond to the time variable x analyzed signal h data window deltat analysis time increment in samples zp length of FFTs pizp gives the frequency increment Description function which computes the timefrequency wigner spectrum of a signal 1739 Name window compute symmetric window of various type winlwindowren winlwindowtrn winlwindowhnn winlwindowhmn winlwindowkrnalpha winlcwpwindowchnpar Parameters n window length par parameter 2vector pardpdf where dp 0dp5 rules the main lobe width and df rules the side lobe height df0 Only one of these two value should be specified the other one should set equal to 1 alpha kaiser window parameter alpha 0 win window cwp unspecified Chebyshev window parameter Description function which calculates various symmetric window for Disgital signal processing The Kaiser window is a nearly optimal window function alpha is an arbitrary positive real number that determines the shape of the window and the integer n is the length of the window By construction this function peaks at unity for k n2 ie at the center of the window and decays exponentially towards the window edges The larger the value of alpha the narrower the window becomes alpha 0 corresponds to a rectangular window Conversely for larger alpha the width of the main lobe increases in the Fourier transform while the side lobes decrease in amplitude Thus this parameter controls the tradeoff between mainlobe width and sidelobe area alpha window shape 0 Rectangular shape 5 Similar to the Hamming window 6 Similar to the Hanning window 86 Similar to the Blackman window The Chebyshev window minimizes the mainlobe width given a particular sidelobe height It is char acterized by an equiripple behavior that is its sidelobes all have the same height The Hanning and Hamming windows are quite similar they only differ in the choice of one parameter alpha walpha1 alphacos2pixn1 alpha is equal to 12 in Hanning window and to 054 in Hamming window window 1740 Examples Hamming window clf N64 wwindowhmN subplot121plot2d1Nwstylecolorblue setgcagrid1 1colorgray subplot122 n256Wfrfrmagwn plot2dfr20log10Wstylecolorblue setgcagrid1 1colorgray Kaiser window clf N64 wwindowkrN6 subplot121plot2d1Nwstylecolorblue setgcagrid1 1colorgray subplot122 n256Wfrfrmagwn plot2dfr20log10Wstylecolorblue setgcagrid1 1colorgray Chebyshev window clf N64 wdfwindowchN00051 subplot121plot2d1Nwstylecolorblue setgcagrid1 1colorgray subplot122 n256Wfrfrmagwn plot2dfr20log10Wstylecolorblue setgcagrid1 1colorgray See Also wfir frmag ffilt Authors Carey Bunks Bibliography IEEE Programs for Digital Signal Processing IEEE Press New York John Wiley and Sons 1979 Program 52 1741 Name yulewalk leastsquare filter design Hz yulewalkNfrqmag Parameters N integer order of desired filter frq real row vector nondecreasing order frequencies mag non negative real row vector same size as frq desired magnitudes Hz filter BzAz Description Hz yulewalkNfrqmag finds the Nth order iir filter n1 n2 Bz b1z b2z bn Hz n1 n2 Az z a2z an which matches the magnitude frequency response given by vectors frq and mag Vectors frq and mag specify the frequency and magnitude of the desired frequency response The frequencies in frq must be between 00 and 10 with 10 corresponding to half the sample rate They must be in increasing order and start with 00 and end with 10 Examples f0040406061H001100Hzyulewalk8fH fs1000fhz ffs2 clf0xsetwindow0plot2dfhzH xtitleDesired Frequency Response Magnitude frqrepfrepfreqHz0000105 clf1xsetwindow1plot2dfsfrqabsrepf xtitleObtained Frequency Response Magnitude 1742 Name zpbutt Butterworth analog filter polsgainzpbuttnomegac Parameters n integer filter order omegac real cutoff frequency in Hertz pols resulting poles of filter gain resulting gain of filter Description computes the poles of a Butterworth analog filter of order n and cutoff frequency omegac transfer function Hs is calculated by Hsgainrealpolypolss Authors F Delebecque INRIA 1743 Name zpch1 Chebyshev analog filter polesgainzpch1nepsilonomegac Parameters n integer filter order epsilon real ripple in the pass band 0epsilon1 omegac real cutoff frequency in Hertz poles resulting filter poles gain resulting filter gain Description Poles of a Type 1 Chebyshev analog filter The transfer function is given by Hsgainpolypoless Authors FD 1744 Name zpch2 Chebyshev analog filter zerospolesgainzpch2nAomegar Parameters n integer filter order A real attenuation in stop band A1 omegar real cutoff frequency in Hertz zeros resulting filter zeros poles resulting filter poles gain Resulting filter gain Description Poles and zeros of a type 2 Chebyshev analog filter gain is the gain of the filter Hsgainpolyzerosspolypoless Authors FD 1745 Name zpell lowpass elliptic filter zerospolesgainzpellepsilonAomegacomegar Parameters epsilon real ripple of filter in pass band 0epsilon1 A real attenuation of filter in stop band A1 omegac real pass band cutoff frequency in Hertz omegar real stop band cutoff frequency in Hertz zeros resulting zeros of filter poles resulting poles of filter gain resulting gain of filter Description Poles and zeros of prototype lowpass elliptic filter gain is the gain of the filter See Also ell1mag eqiir Authors FD Parte XXIX Matrizes Esparsas 1747 Name full conversão de matriz esparsa para cheia completa Xfullsp Parâmetros sp matriz esparsa ou cheia de reais ou complexos X matriz cheia completa Descrição Xfullsp converte a matriz esparsa sp em sua representação cheia completa Se sp já é cheia então X é igual a sp Exemplos spsparse125431123 Afullsp Ver Também sparse sprand speye 1748 Name ludel função utilitária usada com lufact ludelhand Parâmetros hand manipulador para fatores lu esparsos saída de lufact Descrição Esta função é usada de modo conjunto com lufact Ela limpa o espaço de memória interna usado para guardar o resultado de lufact A seqüência de comandos prlufactAxlusolvepbludelp resolve o sis tema linear esparso Ax b e limpa p Ver Também sparse lufact luget 1749 Name lufact fatoração LU esparsa handrklufactAprec Parâmetros A matriz quadrada esparsa hand manipulador para fatores LU esparsos rk inteiro posto de A prec vetor de tamanho 2 precepsreps fornecendo os limiares absoluto e relativo Descrição handrklufactA realiza a fatoração LU da matriz esparsa A hand sem exibição é usado por lusolve para resolver sistemas lineares e luget para retirar os fatores hand deve ser limpo pelo comando ludelhand A matriz A não precisa ser de posto cheio mas deve ser quadrada desde que A é assumida como sendo esparsa podese adicionar 0 se necessário para quadrála eps a magnitude absoluta que um elemento deve ter para ser considerado um candidato a pivô exceto como último recurso Este número deve ser posto de modo a ser significantemente menor que o menor elemento da diagonal que se espera estar localizado na matriz O valor padrão é eps reps Este número determina qual será o limiar relativo do pivô Deve estar entre 0 e 1 Se for 1 então o método de pivoteamento tornase pivotação completa que é muito lento e tende a completar a matriz Se o número acertado é próximo de 0 o método de pivoteamento tornase estritamente de Markowitz sem limiar O limiar de pivô é usado para eliminar candidatos a pivô que poderiam causar crescimento excessivo de elementos se fossem usados Crescimento de elementos é a causa dos erros de arredondamento Crescimento de elementos ocorre mesmo em matrizes bem condi cionadas Definir o reps como um número grande reduzirá o crescimento de elementos e os erros de arredondamento mas colocálo muito grande aumentará muito o tempo de execução e resul tará num grande número de preenchimentos Se isto ocorrer a precisão pode ficar prejudicada por causa do grande número de operações requeridas na matriz devido ao grande número de preenchi mentos 0001 parece um bom valor e é o valor default O default é escolhido fornecendose um valor maior que 1 ou menor que ou igual a 0 Este valor deve ser aumentado e a matriz resolvida se o crescimento for excessivo Mudar o limiar do pivô não melhora o desempenho em matrizes onde o crescimento é baixo como é geralmente o caso de matrizes malcondicionadas reps foi escolhido para uso com matrizes quase diagonalmente dominantes como uma matriz de admissão de nó e nó modificado Para estas matrizes geralmente o melhor é usar pivotação diagonal Para matrizes sem uma diagonal forte geralmente é melhor usar um limiar maior como 001 ou 01 Exemplos arand55brand51Asparsea hrklufactA lufact 1750 xlusolvehbaxb ludelh Ver Também sparse lusolve luget 1751 Name luget extração dos fatores LU esparsos PLUQlugethand Parâmetros hand manipulador saída de lufact P matriz de permutação esparsa L matriz esparsa triangular infeiror se hand é obtida de uma matriz nãosingular U matriz quadrada triangular superior esparsa nãosnigular preenchida com 1 ao longo da diagonal principal Q matriz de permutação esparsa Descrição PLUQlugethand com hand obtida pelo comando handrklufactA com A uma matriz esparsa retorna quatro matrizes esparsas tais que PLUQA A matriz A não precisa ser de posto cheio mas deve ser quadrada desde que A é assumida esparsa podese adicionar 0 se necessário para quadrar A Se A é singular a matriz L é de colunas comprimidas com rk colunas independentes nãonulas a matriz nãosingular esparsa QinvU comprime em colunas A Exemplos arand52rand25Asparsea handrklufactAPLUQlugethand fullL PLUQA cleanPLUQA ludelhand Ver Também sparse lusolve luget clean 1752 Name lusolve solucionador de sistemas lineares esparsos lusolvehandb lusolveAb Parâmetros b matriz de reais completa A matriz quadrada de reais esparsa e invertível hand manipulador para fatores de lu esparsos previamente computados saída de lufact Descrição xlusolvehandb resolve o sistema linear esparso Ax b handrklufactA é a saída de lufact xlusolveAb resolve o sistema linear esparso Ax b Exemplos nonzeros1234rowscols11223344 spsparserowscolsnonzeros hrklufactspxlusolveh1111ludelh rkspx nonzeros1234rowscols11223344 spsparserowscolsnonzeros xlusolvespones41 spx Ver Também sparse lufact slash backslash 1753 Name mtlbsparse converte matriz esparsa YmtlbsparseX Parâmetros X matriz esparsa Y matriz esparsa em formato Matlab Descrição YmtlbsparseX é usado para converter X uma matriz esparsa Scilab para formato Matlab Y é uma variável de tipo 7 ie typeY é igual a 7 Esta função deve ser usada em mexfiles um mexfile Matlab contendo matrizes esparsas pode ser usado apenas se as matrizes esparsas do Scilab forem convertidas para este formato As funções full e spget funcionam com este formato Outras operações e funções usando este formato podem ficar sobrecarregadas com funções do Scilab usando o prefixo msp Por exemplo a função msppx ver diretório SCIDIRmacrospercent é usada para exibir tais objetos tipo 7 Exemplos Xsparserand22 YmtlbsparseX Y fullY ijvmnspgetY Ver Também full spget 1754 Name nnz número de entradas nãonulas de uma matriz nnnzX Parâmetros X matriz de reais ou complexos esparsa ou cheia n inteiro número de elementos nãonulos de X Descrição nnz conta o número de entradas nãonulas de uma matriz esparsa ou cheia Exemplos spsparse1245310123 nnzsp a1 0 0 0 2 nnza Ver Também spget 1755 Name sparse definição de matriz esparsa spsparseX spsparseijv mn Parâmetros X matriz completa ou esparsa de reais ou complexos ij matriz de inteiros de duas colunas índices das entradas não nulas v vetor mn vetor de inteiros com duas entradas dimensão de linha dimensão de coluna sp matriz esparsa Descrição sparse é usado para construir uma matriz esparsa Apenas entradas nãonulas são armazenadas sp sparseX converte uma matriz completa para sua forma esparsa retirando qualquer ele mento nulo Se X já é esparsa sp é X spsparseijv mn constrói uma matriz esparsa mn1pormn2 sparse matrix com spijk1ijk2vk ij e v devem ter a mesma dimensão de coluna Se o parâmetro opcional mn não for dado as dimensões da matriz sp são os valores máximos de ij1 e ij2 respectivamente Operações concatenação adição etc com matrizes esparsas são feitas usando a mesma sintaxe para matrizes completas Funções elementares também estão disponíveis absmaxisumdiag para matrizes es parsas Operações mistas completasesparsas são permitidas Os resultados são completos ou esparsos de pendendo das operações Exemplos spsparse1245310123 sizesp xrand22absxfullabssparsex Ver Também full spget sprand speye lufact 1756 Name spchol fatoração esparsa de Cholesky RP spcholX Parâmetros X matriz simétrica esparsa e positiva definida de reais P matriz de permutação R fator de Cholesky Descrição RP spcholX produz uma matriz triângular inferior R tal que PRRP X Exemplos X 3 0 0 2 0 0 2 0 2 0 0 0 5 4 0 0 0 0 0 0 0 0 0 4 5 0 0 0 0 0 0 0 0 2 0 0 3 0 0 2 0 2 0 0 0 0 0 0 5 0 0 0 0 0 4 0 0 0 0 0 4 0 3 0 3 0 2 0 0 2 0 0 3 0 2 0 0 0 0 0 0 0 3 0 4 0 3 0 2 0 0 2 0 0 2 0 3 0 0 0 0 0 0 0 3 0 3 0 4 0 0 0 0 0 4 0 0 0 0 0 5 XsparseXRP spcholX maxPRRPX Ver Também sparse lusolve luget chol 1757 Name spcompack converte uma representação de adjacência comprimida em representação de adjacência padrão Parâmetros xadj vetor de inteiros de comprimento n1 xlindx vetor de inteiros de comprimento n1 ponteiros lindx vetor de inteiros adjncy vetor de inteiros Descrição A função utilitária spcompak é usada para converter uma representação de adjacência comprimida em uma representação de adjacência padrão Exemplos A é a matriz esparsa A1000000 0100000 0010000 0011000 0011100 0011010 0011011 AsparseA Para esta matriz a representação padrão de adjacência é dada por xadj123812131516 adjncy1 2 34567 4567 5 67 7 ver sp2adj Incrementos no vetor xadj dão o número de entradas não nulas em cada coluna ie há 211 entrada na coluna 1 há 321 entrada na coluna 2 há 835 entradas na coluna 3 1284 4 etc O índice de linha dessas entradas é dado pelo vetor adjncy por exemplo adjncy 37adjncyxadj3xadj4134567 diz que as 5xadj4xadj3 entradas na coluna 3 têm índices de linha 34567 Na representação compacta as seqüências repetidas em adjncy são eliminadas Aqui em adjncy as seqüências 4567 e 7 são eliminadas A estrutura padrão xadjadjncy toma a forma comprimida lindxxlindx lindx1 2 34567 5 67 spcompack 1758 xlindx1238911 colunas 4 e 7 de A são eliminadas A pode ser reconstruída de xadjxlindxlindx xadjadjncyanz sp2adjA adjncyspcompackxadjxlindxlindx Ver Também sp2adj adj2sp spget 1759 Name spget recupera entradas de matriz esparsa ijvmnspgetsp Parâmetros sp matriz esparsa de reais ou complexos ij matriz de inteiros de duas colunas índices das entradas nãonulas mn vetor de inteiros com duas entradas dimensão de linha dimensão de coluna v vetor coluna Descrição spget é usado para converter a representação interna de matrizes esparsas na representação padrão ij v Entradas nãonulas de sp estão localizadas em linhas e colunas com índices em ij Exemplos spsparse1245310123 ijvmnspgetsp Ver Também sparse sprand speye lufact 1760 Name gmres Generalized Minimum RESidual method xflagerriterres gmresAbrstrtolmaxiMx0 Parameters A nbyn matrix or function returning Ax b right hand side vector x0 initial guess vector default zerosn1 M preconditioner matrix or function returning Mx In the first case default eyenn rstr number of iterations between restarts default 10 maxi maximum number of iterations default n tol error tolerance default 1e6 x solution vector err final residual norm iter number of iterations performed flag 0 gmres converged to the desired tolerance within maxi iterations 1 no convergence given maxi res residual vector Description GMRES solves the linear system Axb using the Generalized Minimal residual method with restarts Details of this algorithm are described in Templates for the Solution of Linear Systems Building Blocks for Iterative Methods Barrett Berry Chan Demmel Donato Dongarra Eijkhout Pozo Romine and Van der Vorst SIAM Publications 1993 ftp netlib2csutkedu cd linalg get templatesps gmres 1761 Iterative Methods for Sparse Linear Systems Second Edition Saad SIAM Publications 2003 ftp ftpcsumnedu cd deptuserssaadPS get allpszip Examples GMRES call xgmresAb See Also pcg qmr Authors Sage Group IRISA 2005 1762 Name pcg precondioned conjugate gradient x flag err iter res pcgA b tol maxIter M M2 x0 verbose x flag err iter res pcgA b keyvalue Parameters A a matrix or a function or a list computing Ax for each given x The following is a description of the computation of Ax depending on the type of A matrixIf A is a matrix it can be dense or sparse functionIf A is a function it must have the following header function y A x listIf A is a list the first element of the list is expected to be a function and the other ele ments in the list are the arguments of the function from index 2 to the end When the function is called the current value of x is passed to the function as the first argument The other argu ments passed are the one given in the list b right hand side vector size nx1 tol error relative tolerance default 1e8 The termination criteria is based on the 2norm of the residual rbAx divided by the 2norm of the right hand side b maxIter maximum number of iterations default n M preconditioner full or sparse matrix or function returning Mx default none M2 preconditioner full or sparse matrix or function returning M2x for each x default none x0 initial guess vector default zerosn1 verbose set to 1 to enable verbose logging default 0 x solution vector flag 0 if pcg converged to the desired tolerance within maxi iterations 1 else err final relative norm of the residual the 2norm of the righthand side b is used iter number of iterations performed pcg 1763 res vector of the residual relative norms Description Solves the linear system Axb using the conjugate gradient method with or without preconditioning The preconditionning should be defined by a symmetric positive definite matrix M or two matrices M1 and M2 such that MM1M2 in the case the function solves invMAx invMb for x M M1 and M2 can be Scilab functions with calling sequence yMilxx which computes the corresponding left division yMix The A matrix must be a symmetric positive definite matrix full or sparse or a function with calling sequence yAxx which computes yAx Example with well conditionned and ill conditionned problems In the following example two linear systems are solved The first maxtrix has a condition number equals to 002 which makes the algorithm converge in exactly 10 iterations Since this is the size of the matrix it is an expected behaviour for a gradient conjugate method The second one has a low condition number equals to 1d6 which makes the algorithm converge in a larger 22 iterations This is why the parameter maxIter is set to 30 See below for other examples of the keyvalue syntax Well conditionned problem A 94 0 0 0 0 28 0 0 32 0 0 59 13 5 0 0 0 10 0 0 0 13 72 34 2 0 0 0 0 65 0 5 34 114 0 0 0 0 0 55 0 0 2 0 70 0 28 32 12 0 28 0 0 0 0 87 20 0 33 0 0 0 0 0 28 20 71 39 0 0 0 10 0 0 32 0 39 46 8 0 32 0 0 0 12 33 0 8 82 11 0 0 65 55 0 0 0 0 11 100 bones101 x fail err iter respcgAb1d1215 mprintf faild iterd errrele failitererr Ill contionned one A 894 0 0 0 0 28 0 0 1000 70000 0 5 13 5 0 0 0 0 0 0 0 13 72 34 0 0 0 0 0 6500 0 5 34 1 0 0 0 0 0 55 0 0 0 0 70 0 28 32 12 0 28 0 0 0 0 87 20 0 33 0 0 0 0 0 28 20 71 39 0 0 0 0 0 0 32 0 39 46 8 0 1000 0 0 0 12 33 0 8 82 11 70000 0 6500 55 0 0 0 0 11 100 x fail err iter respcgAbmaxIter30tol1d12 mprintf faild iterd errrele failitererr pcg 1764 Examples with A given as a sparse matrix or function or list The following example shows that the method can handle sparse matrices as well It also shows the case where a function computing the righthand side is given to the pcg primitive The final case shown by this example is when a list is passed to the primitive Well conditionned problem A 94 0 0 0 0 28 0 0 32 0 0 59 13 5 0 0 0 10 0 0 0 13 72 34 2 0 0 0 0 65 0 5 34 114 0 0 0 0 0 55 0 0 2 0 70 0 28 32 12 0 28 0 0 0 0 87 20 0 33 0 0 0 0 0 28 20 71 39 0 0 0 10 0 0 32 0 39 46 8 0 32 0 0 0 12 33 0 8 82 11 0 0 65 55 0 0 0 0 11 100 bones101 Convert A into a sparse matrix AsparsesparseA x fail err iter respcgAsparsebmaxIter30tol1d12 mprintf faild iterd errrele failitererr Define a function which computes the righthand side function yAtimesxx A 94 0 0 0 0 28 0 0 32 0 0 59 13 5 0 0 0 10 0 0 0 13 72 34 2 0 0 0 0 65 0 5 34 114 0 0 0 0 0 55 0 0 2 0 70 0 28 32 12 0 28 0 0 0 0 87 20 0 33 0 0 0 0 0 28 20 71 39 0 0 0 10 0 0 32 0 39 46 8 0 32 0 0 0 12 33 0 8 82 11 0 0 65 55 0 0 0 0 11 100 yAx endfunction Pass the script Atimesx to the primitive x fail err iter respcgAtimesxbmaxIter30tol1d12 mprintf faild iterd errrele failitererr Define a function which computes the righthand side function yAtimesxbisxA yAx endfunction Pass a list to the primitive Alist listAtimesxbisAsparse x fail err iter respcgAlistbmaxIter30tol1d12 mprintf faild iterd errrele failitererr pcg 1765 Examples with keyvalue syntax The following example shows how to pass arguments with the keyvalue syntax This allows to set nonpositionnal arguments that is to set arguments which are not depending on their order in the list of arguments The available keys are the names of the optional arguments that is tol maxIter M M2 x0 verbose Notice that in the following example the verbose option is given before the maxIter option Without the keyvalue syntax the positionnal arguments would require that maxIter come first and verbose after Example of an argument passed with keyvalue syntax A1001110 b10111 xcomputed flag err iter respcgAbverbose1 With keyvalue syntax the order does not matter xcomputed flag err iter respcgAbverbose1maxIter0 See Also backslash qmr gmres Authors Sage Group IRISA 2004 Serge Steer INRIA 2006 Michael Baudin INRIA 20082009 References Templates for the Solution of Linear Systems Building Blocks for Iterative Methods Barrett Berry Chan Demmel Donato Dongarra Eijkhout Pozo Romine and Van der Vorst SIAM Publications 1993 ftp netlib2csutkedulinalgtemplatesps Iterative Methods for Sparse Linear Systems Second Edition Saad SIAM Publications 2003 ftp ftpcsumnedudeptuserssaadPSallpszip 1766 Name qmr quasi minimal resiqual method with preconditioning xflagerriterres qmrAbx0M1M1pM2M2pmaxitol Parameters A matrix of size nbyn or function returning Ax b right hand side vector x0 initial guess vector default zerosn1 M1 left preconditioner matrix or function returning M1x In the first case default eyenn M1p must only be provided when M1 is a function In this case M1p is the function which returns M1x M2 right preconditioner matrix or function returning M2x In the first case default eyenn M2p must only be provided when M2 is a function In this case M2p is the function which returns M2x maxi maximum number of iterations default n tol error tolerance default 1000eps x solution vector flag 0 gmres converged to the desired tolerance within maxi iterations 1 no convergence given maxi res residual vector err final residual norm iter number of iterations performed Description Solves the linear system Axb using the Quasi Minimal Residual Method with preconditioning qmr 1767 See Also gmres Authors SAGE Group IRISA 2005 Parte XXX Funções Especiais 1769 Name besseli funções modificadas de Bessel do primeiro tipo I sub alfa besselj funções de Bessel do primeiro tipo J sub alpha besselk funções modificadas de Bessel do segundo tipo K sub alpha bessely funções de Bessel do segundo tipo Y sub alpha besselh funções de Bessel do terceiro tipo também conhecidas como funções de Hankel y besselialphax ice y besseljalphax ice y besselkalphax ice y besselyalphax ice y besselhalphax y besselhalphaKx ice Parâmetros x vetor de reais ou complexos alpha vetor de reais ice flag sinalizador inteiro com valor padrão 0 K inteiro com valores possíveis 1 ou 2 a função do tipo de Hankel Descrição Aviso a semântica destas funções varia entre o Scilab30 e Scilab31 A semântica antiga está disponível para compatibilidade usando as funções oldbesseli oldbesselj oldbesselk oldbessely besselialphax computa as funções de Bessel modificadas do primeiro tipo I sub alfa para ordem real alpha e argumento x besselialphax1 computa besselialphaxexpabsrealx besseljalphax computa as funções de Bessel do primeiro tipo J sub alfa para ordem real alpha e argumento x besseljalphax1 computa besseljalphaxexp absimagx besselkalphax computa as funções de Bessel modificadas do segundo tipo K sub alfa para ordem real alpha e argumento x besselkalphax1 computa besselkalphaxexpx besselyalphax computa as funções de Bessel do segundo tipo Y sub alfa para ordem real alpha e argumento x besselyalphax1 computa besselyalphaxexp absimagx besselhalpha K x computa as funções de Bessel do terceiro tipo função de Hankel H1 ou H2 dependendo do K para ordem real alpha e argumentot x Se omitido K é suposto co mo sendo 1 besselhalpha1x1 computa besselhalpha1xexpix e besselhalpha2x1 computa besselhalpha2xexpix Observações Se alpha e x são arrays de mesmo tamanho o resultado y também terá este tamanho Se uma entrada é um escalar ela é expandida para o tamanho da outra entrada Se uma entrada é um vetor linha e a outra é um vetor coluna o resultado y é um table 2dimensional tabela de valores de funções besseli 1770 As funções de Bessel Yalfa e Jalfa são duas soluções independentes da equação diferencial de Bessel 2 2 2 x y x y x alfa y 0 alfa 0 As funções modificadas de Bessel Kalfa e Ialfa são duas soluções independentes para a equação diferencial de Bessel 2 2 2 x y x y x alfa y 0 alfa 0 As funções de Hankel de primeiro e segundo tipos H1alfa e H2alfa são combinações lineares das funções de Bessel de primeiro e segundo tipos H1alfaz Jalfaz i Yalfaz H2alfaz Jalfaz i Yalfaz Exemplos Funções I de Bessel x linspace001105000 xbasc subplot211 plot2dxbesseli04x style26 legendIstring042 xtitleAlgumas funções modificadas de Bessel do primeiro tipo subplot212 plot2dxbesseli04x1 style26 legendIstring041 xtitleAlgumas funções modificadas de Bessel do primeiro tipo escaladas Funções J de Bessel x linspace0405000 xbasc plot2dxbesselj04x style26 legJ0J1J2J3J4 legendIstring041 xtitleAlgumas funções de Bessel do primeiro tipo Usando o fato de que J12x sqrt2x pi sinx Para comparar o algoritmo de besselj05x com uma fórmula mais direta x linspace01405000 y1 besselj05 x y2 sqrt2 pixsinx er absy1y2y2 ind finder 0 y2 0 xbasc subplot211 plot2dxy1style2 xtitlebesselj05x subplot212 plot2dxind erind style2 logflagnl xtitleErro relativo entre as duas fórmulas para besselj05x besseli 1771 Funções K de Bessel x linspace001105000 xbasc subplot211 plot2dxbesselk04x style04 rect00610 legendKstring041 xtitleAlgumas funções modificadas de Bessel do segundo tipo subplot212 plot2dxbesselk04x1 style04 rect00610 legendKstring041 xtitleAlgumas funções modificadas de Bessel do segundo tipo escaladas Funções Y de Bessel x linspace01405000 funções Y de Bessel não possuem limite para x 0 xbasc plot2dxbessely04x style04 rect0154006 legendYstring044 xtitleAlgumas funções de Bessel do segundo tipo Funções H de Bessel x400252 y15002515 XY ndgridxy H besselh01XiY clffgcf xsetfpf fcolormapjetcolormap16 contour2dxyabsH020232strf034rect415315 legendsstring020232116ur xtitleCurvas de nível de H10z Autores Amos D E SNLA Daniel S L SNLA Weston M K SNLA Função Usada Os códigosfontes podem ser achados em SCImodulesspecialfunctionssrcfortranslatec e SCI modulesspecialfunctionssrcfortran Slatec dbesif zbesif dbesjf zbesjf dbeskf zbeskf dbesyf zbesyf zbeshf Drivers para estender a área de definição Serge Steer INRIA dbesigf zbesigf dbesjgf zbesjgf dbeskgf zbeskgf dbesygf zbesygf zbeshgf 1772 Name beta função beta z betaxy Parâmetros x y dois reais positivos ou duas matrizes ou vetores de reais positivos de mesmo tamanho z um real ou uma matriz de reais com mesmo tamanho que x com zij betaxijyij Descrição Computa a função beta completa 1 x1 y1 gammax gammay betaxy t 1t dt 0 gammaxy Para x e y pequenos o algoritmo usa a expressão em função da função gama de outro modo ele aplica a função exponencial no resutado da função betaln function fornecido no DCDFLIB Biblioteca de Rotinas FORTRAN para Funções Inversas e Outros Parâmetros de Distribuição Cumulativa ver cdfbet para maiores informações sobre DCDFLIB Exemplos exemplo 1 beta52 beta25 simetria deve ser exatamente 0 beta0505 o valor exato é pi exemplo 2 um estudo de erros baseado na relação B1x 1x a computação de 1x deve levar apenas a um erro relativo de epsm então pode ser usada como referência para avaliar o erro em B1x x logspace8820000 e betaonesxx 1x er abse x ind finder 0 eps onesxindnumberpropertieseps xbasc plot2dxinderind eps 2epsstyle1 2 3logflaglllegerepsm2 epsm xtitleerro relativo aproximado na computação de beta1x xselect exemplo 3 plotando a função beta t linspace021060 X tonest Y onestt Z betaXY xbasc plot3dt t Z flag2 4 4 legxyz alpha75 theta30 beta 1773 xtitleA função beta em 0210x0210 xselect Ver Também gamma cdfbet 1774 Name calerf computa funções de erro Parâmetros x matriz ou vetor de reais flag indicador inteiro y matriz ou vetor de reais de mesmo tamanho que x Descrição calerfx0 computa a função de erro erfx calerfx1 computa a função de erro complementar erfcx calerfx2 computa a função de erro complementar escalada erfcxx Exemplos deffyftyexpt2 calerf10 2sqrtpiintg01f Ver Também erf erfc erfcx Autor W J Cody código de Netlib specfun 1775 Name dlgamma derivada da função gammaln função psi y dlgammax Parâmetros x vetor de reais y vetor de reais com o mesmo tamanho Descrição dlgammax avalia em todos os elementos de x a derivada logarítmica da função gama gamma que corresponde também à derivada da função lngama gammaln ddx gammax gammax ddx ln gammax x deve ser real Também é conhecida como a função psi Exemplos dlgamma05 Ver Também gamma gammaln Autor W J Cody code from Netlib specfun 1776 Name erf função de erro y erfx Parâmetros x vetor ou matriz de reais y vetor ou matriz de reais de mesmo tamanho que x Descrição erf computa a função de erro x 2 2 t y e dt sqrtpi 0 Exemplos deffyftyexpt2 erf052sqrtpiintg005f Ver Também erfc erfcx calerf cdfnor Autor W J Cody código de Netlib specfun 1777 Name erfc função de erro complementar y erfcx Parâmetros x real vector or matrix y real vector or matrix of same size than x Descrição erfc computa a função de erro complementar oo 2 2 t y e dt sqrtpi x y 1 erfx Exemplos erf0502erfc0502 Ver Também erf erfcx calerf Autor W J Cody código de Netlib specfun 1778 Name erfcx função de erro complementar escalada y erfcxx Parameters x vetor ou matriz de reais y vetor ou matriz de reais de mesmo tamanho que x Descrição erfcx computa a função de erro complementar escalada 2 y expx erfcx 1 y quando x oo x sqrtpi Ver Também erf erfc calerf Autor W J Cody código de Netlib specfun 1779 Name erfinv função inversa à função de erro y erfinvx Parâmetros x vetor ou matriz de reais y vetor ou matriz de reais de mesmo tamanho que x Descrição erfinv computa a função inversa à função de erro erf x erfinvy satisfaz y erfx 1 y 1 inf x inf Exemplos xlinspace099099100 yerfinvx plot2dxy normxerfyinf Ver Também erfc cdfnor Referências Milton Abramowitz e Irene A Stegun eds Handbook of Mathematical Functions with Formulas Graphs and Mathematical Tables New York Dover 1972 1780 Name gamma função gama y gammax Parâmetros x vetor ou matriz de reais ou complexos y vetor ou matriz de reais ou complexos de mesmo tamanho que x Descrição gammax avalia a função gama em todos os elementos de x A função gama é defininda por oo x1 t gammax t e dt 0 e generaliza a função fatorial para os números reais gamman1 n Exemplos exemplos simples gamma05 gamma6prod15 o gráfico da função gama em ab a 3 b 5 x linspaceab40000 y gammax xbasc cxgetcolor xsetcolor2 plot2dx y style0 axesflag5 recta 10 b 10 xsetcolorc xtitleA função gama em stringastringb xselect Ver Também gammaln dlgamma Autores W J Cody e L Stoltz código de Netlib specfun 1781 Name gammaln o logaritmo natural da função gama y gammalnx Parameters x vetor de reais y vetor de reais com o mesmo tamanho Description gammalnx avalia o logaritmo natural da função gama em todos os elementos de x evitando underflow e overflow x deve ser de reais Exemplos gammaln05 Ver Também gamma dlgamma Autores W J Cody e L Stoltz código de Netlib specfun 1782 Name legendre funções associadas de Legendre y legendrenmx normflag Parâmetros n inteiro nãonegativo ou vetor de inteiros nãonegativos igualmente espaçados com incremento igual a 1 m inteiro nãonegativo ou vetor de inteiros nãonegativos igualmente espaçados com incremento igual a 1 x vetor linha de reais os elementos de x devem estar no intervalo 11 normflag opcional escalar string Descrição Quando n e m são escalares legendrenmx avalia a função de Legendre associada Pnmx em todos os elementos de x A definição usada é m m m2 d Pnmx 1 1x2 Pnx m dx onde Pn é o polinômio de Legendre de grau n Então legendren0x avalia o polinômio de Legendre Pnx em todos os elementos de x Quando normflag é igual a norm o resultado é uma versão normalizada sem o fator 1m precisamente m 2n1nm m2 d Pnmxnorm 1x2 Pnx 2 nm m dx que é útil para computar funções harmônicas esféricas ver exemplo 3 Por eficiência um dos primeiros dois argumentos pode ser um vetor por exemplo legendren1n20x avalia todos os polinômios de Legendre de graus n1 n11 n2 nos elementos de x e legendrenm1m2x avalia todas as funções de Legendre associadas Pnm para mm1 m11 m2 em x Formato de Saída Em qualquer caso o formato é y legendre 1783 maxlengthnlengthm x lengthx e yij Pnimxj se n é um vetor yij Pnmixj se m é um vetor y1j Pnmxj se ambos n e m são escalares de tal modo que x é preferivelmente um vetor linha mas qualquer matriz mx x nx é excetuada e considerada como uma matriz 1 x mx nx matrix reformada segundo a ordem das colunas Exemplos exemplo 1 plot dos primeiros 6 polinômios de Legendre em 11 l nearfloatpred1 x linspacell200 y legendre05 0 x xbasc plot2dxy legp0p1p2p3p4p5p6 xtitleOs 6 primeiros polinômios de Legendre exemplo 2 plot das funções associadas de Legendre de grau 5 l nearfloatpred1 x linspacell200 y legendre5 05 x norm xbasc plot2dxy legp50p51p52p53p54p55 xtitleAs funções associadas de Legendre normalizadas de grau 5 exemplo 3 definindo e plotando uma função harmônica esférica 31 definindo a função Ylm function y Ylmthetaphi teta pode ser um escalar ou um vetor linha phi pode ser um escalar ou um vetor coluna if m 0 then y 1msqrt2piexpimphilegendrel m costheta norm else y 1sqrt2piexpimphilegendrel m costheta norm end endfunction 32 definindo outra função útil function xyz sph2cartthetaphir vetor linha teta 1 x nt vetor coluna phi np x 1 r escalar ou matriz np x nt rij o comprimento em phii thetaj x rcosphisintheta y rsinphisintheta z ronesphicostheta endfunction 33 plot de Y31thetaphi l 3 m 1 legendre 1784 theta linspace01pi0160 phi linspace02pi120 f Ylmthetaphi x1y1z1 sph2cartthetaphiabsf xf1yf1zf1 nf3dx1y1z1 x2y2z2 sph2cartthetaphiabsrealf xf2yf2zf2 nf3dx2y2z2 x3y3z3 sph2cartthetaphiabsimagf xf3yf3zf3 nf3dx3y3z3 xbasc subplot131 plot3dxf1yf1zf1flag2 4 4 xtitleY31thetaphi subplot132 plot3dxf2yf2zf2flag2 4 4 xtitleRealY31thetaphi subplot133 plot3dxf3yf3zf3flag2 4 4 xtitleImagY31thetaphi Autores Smith John M código dxlegff de Slatec B Pincon interface Scilab 1785 Name oldbesseli funções de Bessel modificadas do primeiro tipo I sub alfa oldbesselj funções de Bessel do primeiro tipo J sub alfa oldbesselk funções de Bessel modificadas do segundo tipo K sub alfa oldbessely funções de Bessel do segundo tipo Y sub alfa y oldbesselialphax y oldbesselialphaxice y oldbesseljalphax y oldbesselkalphax y oldbesselkalphaxice y oldbesselyalphax Parâmetros x vetor de reais com entradas nãonegativas alpha vetor de reais com entradas nãonegativas igualmente espaçadas com incremento igual a 1alphaalpha0n1n2 ice flag inteiro com valor padrão 1 Descrição Funções obsoletas use besseli besselj besselk bessely no lugar Note contudo que a semântica destes dois grupos de funções é diferente oldbesselialphax computa funções modificadas de Bessel do primeiro tipo I sub alfa para ordem real nãonegativa alpha e argumento real nãonegativo x besselialphax2 computa besselialphaxexpx oldbesseljalphax computa funções de Bessel do primeiro tipo J sub alfa para ordem real nãonegativa alpha e argumento real nãonegativo x oldbesselkalphax computa as funções modificadas de Bessel do segundo tipo K sub alfa para ordem real nãonegativa alpha e argumento real nãonegativo x besselkalphax2 computa besselkalphaxexpx oldbesselyalphax computa funções de Bessel do segundo tipo Y sub alfa para ordem real nãonegativa alpha e argumento real nãonegativo x alpha e x podem ser vetores A saída é mporn com m sizex n sizealpha whose ij cuja entrada oldbesselalphajxi Observações As funções Yalfa e Jalfa de Bessel são duas soluções independentes da equação diferencial de Bessel 2 2 2 x y x y x alfa y 0 alfa 0 As funções modificadas Kalfa e Ialfa de Bessel são duas soluções independentes da equação difer encial modificada de Bessel oldbesseli 1786 2 2 2 x y x y x alfa y 0 alfa 0 Exemplos exemplo 1 exibindo algumas funções I de Bessel x linspace001105000 y oldbesseli04x ys oldbesseli04x2 xbasc subplot211 plot2dxy style26 legI0I1I2I3I4 rect00610 xtitleAlgumas funções modificadas de Bessel do primeiro tipo subplot212 plot2dxys style26 legI0sI1sI2sI3sI4s rect0061 xtitleAlgumas funções modificadas de Bessel do primeiro tipo escaladas exemplo 2 exibindo algumas funções J de Bessel x linspace0405000 y besselj04x xbasc plot2dxy style26 legJ0J1J2J3J4 xtitleAlgumas funções de Bessel do primeiro tipo example 3 usando o fato de que J12x sqrt2x pi sinx para comparar o algoritmo de besselj05x com uma fórmula mais direta x linspace01405000 y1 besselj05 x y2 sqrt2 pixsinx er absy1y2y2 ind finder 0 y2 0 xbasc subplot211 plot2dxy1style2 xtitlebesselj05x subplot212 plot2dxind erind style2 logflagnl xtitleerro relativo entre as duas fórmulas para besselj05x exemplo 4 exibindo algumas funções K de Bessel x linspace001105000 y besselk04x ys besselk04x1 xbasc subplot211 plot2dxy style04 legK0K1K2K3K4 rect00610 xtitleAlgumas funções modificadas de Bessel do segundo tipo subplot212 plot2dxys style04 legK0sK1sK2sK3sK4s rect00610 xtitleAlgumas funções modificadas de Bessel do segundo tipo escaladas exemplo 5 plot de várias funções Y de Bessel x linspace01405000 funções Y de Bessel não possuem limite para x 0 y bessely04x xbasc oldbesseli 1787 plot2dxy style04 legY0Y1Y2Y3Y4 rect0154006 xtitleAlgumas funções de Bessel do segundo tipo Autores W J Cody L Stoltz código de Netlib specfun Parte XXXI Cadeias de Caracteres Strings 1789 Name ascii conversão ASCII de strings aasciitxt txtasciia Parâmetros txt um string ou matriz de strings a um vetor de códigos ASCII inteiros Descrição Esta função converte um string Scilab para um vetor de códigos ASCII ou um vetor de códigos ASCII em strings Scilab Se txt é uma matriz de strings asciitxt é equivalente a asciistrcattxt Exemplos asciiolámundo asciiscilab ascii115 99 105 108 97 98 Ver Também code2str str2code 1790 Name blanks cria strings de caracteres em branco txtblanksn Parâmetros txt um único string n número de caracteres em branco Descrição blanksn é um string de n caracteres em branco Exemplos dispxxx blanks20 yyy 1791 Name code2str retorna o string associado ao código Scilab inteiro strcode2strc Parâmetros str string c vetor de códigos de caracteres inteiros Descrição Retorna o string associado ao código Scilab inteiro str é tal que ci é o código Scilab inteiro de partstri Exemplos code2str28 12 18 21 10 11 str2codeScilab Ver também str2code ascii 1792 Name convstr conversão maiúsculasminúsculas minúsculasmaiúsculas yconvstrstr flag Parâmetros str y uma matriz de strings flag um caractere de opção com dois possíveis valores u para maiúsculas l para minúsculas Descrição converts a matriz de strings strmatrix para caracteres minúsculos l valor padrão ou para maiúsculos u Exemplos Aestaéa minhamatriz convstrAu 1793 Name emptystr string de comprimento zero semptystr semptystra semptystrmn Parâmetros a qualquer tipo de matriz s matriz de strings mn inteiros Descrição Retorna uma matriz de strings de comprimento zero Sem argumentos de entrada retorna um string de comprimento zero Com uma matriz como argumento de entrada retorna uma matriz de strings de comprimento zero de mesmo tamanho Com dois argumentos inteiros retorna uma matriz mxn de strings de comprimento zero Exemplos xemptystrfor k110 xxstringkend Ver Também part length string 1794 Name grep acha correspondências de um string em um vetor de strings rowgrephaystackneedle rowwhichgrephaystackneedle rowgrephaystackneedle flag rowwhichgrephaystackneedle flag Parâmetros haystack vetor linha de strings needle string ou vetor linha de strings Os strings a serem procurados em haystack row vetor de índices linha onde uma correspondência foi encontrada ou matriz vazia se nenhuma ocorrência tiver sido encontrada which vetor de índices índice do string needle encontrado ou uma matriz vazia se nenhuma correspondência tiver sido encontrada flag caractere r para expressão regular Descrição Para cada entradada de haystack grep procura se pelo menos um string em needle corresponde a um substring Os índices das entradas de haystack onde pelo menos uma entrada foi encontrada são retor nados no argumento row O argumento opcional which fornece o índice do primeiro string de needle encontrado Quando se usa o terceiro parâmetro r needle deve ser substituído por uma expressão regular Então grep vai corresponder a haystack de acordo com as regras regulares expressas Exemplos txtacha correspondência em um string ou em um vetor de strings procura posição de um string em outro string Compara Strings greptxtstrings greptxtstrings Strings rwgreptxtstrings Strings str hatcathhatchathcatccchatatdog grepstrhcatr grepstrhcatr grepstrcatdogr Ver Também strindex 1795 Name isalphanum verifica se os caracteres de um string são alfanuméricos res isalphanumstr Parâmetros str string res matriz de valores booleanos Descrição res isalphanumstr retorna um array de mesmo tamanho que str contendo valores lógicos t true onde os elementos de str são alfanuméricos e f false onde eles não são Exemplos s A1B2C3 isalphanums Ver Também isletter isdigit 1796 Name isascii verifica se um caractere é do tipo 7bit USASCII res isasciistr Parâmetros str string res uma matriz de booleanos Descrição res isasciistr retorna verdadeiro T se c é um código 7bit USASCII entre 0 e 0177 octal inclusive Caso contrário retorna falso F Exemplos isasciicode2str300 isasciicode2str11 letters 115 99 105 108 97 98 isasciiletters asciiletters isasciiscilab Ver Também isalphanum 1797 Name isdigit checa se os caracteres de um string são números entre 0 e 9 res isdigitstr Parâmetros str string res matriz de valores booleanos Descrição res isdigitstr retorna um array com mesmo tamanho que str com valores T verdadeiro onde os elementos de str são dígitos de 0 a 9 e F falso onde eles não são Exemplos s A1B2C3 isdigits Ver Também isalphanum isletter 1798 Name isletter verifica se os caracteres de um string são letras do alfabeto res isletterstr Parâmetros str string res matriz de booleanos Descrição res isletterstr retorna um array de mesmo tamanho que str com t verdadeiro onde os elementos de str são letras do alfabeto e f false onde eles não são Exemplos s A1B2C3 isletters Ver Também isalphanum isdigit 1799 Name isnum testa se um string representa um número res isnumstr Parâmetros str um string ou matriz de strings res matriz de booleanos Descrição res isnumstrretorna T se str representa um número Exemplos isnum1 123 1e23 1d23 pi Ver Também isletter isdigit isalphanum Autores PM 1800 Name justify justifica um array de caracteres TjjustifyTopt Parâmetros T matriz de strings Tj matriz de strings O resultado justificado opt opção com possíveis valores r ou right para justificação direita l ou left para justificação esquerda c ou center justificação centrada Descrição justify justifica a coluna de uma matriz de strings de acordo com a opção dada Exemplos t1234xadfdfgdfghfgj 1354556dgf sdfgdsdfsf justifytl justifytc justifytr Ver Também length part 1801 Name length comprimento de um objeto nlengthM Parâmetros M matriz usual ou de polinômios ou de strings ou lista n inteiro ou matriz de inteiros Descrição Para uma matriz usual ou de polinômios n é o inteiro igual ao número de linhas vezes o número de colunas de M Também válido para M uma matriz de booleanos Para matrizes de strings e em particular para um string length retorna em n os comprimentos das entradas da matriz de strings M O comprimento de uma lista é o número de elementos da lista também dado por size length123 é 3 length1234 is 4 AVISO length para matrizes esparsas retorna o máximo das dimensões não o produto das dimensões exemplo lengthsparseeye122 retorna max122 não 24 Utilize size para matrizes esparsas Exemplos length123 456 lengtholá mundoSCI Ver Também size 1802 Name part extração de strings stringsout partstringsin v Parâmetros stringsin stringsout matriz de strings v vetor linha de inteiros Descrição Seja sk o caractere k do string s ou o espaço em branco se k lengths part retorna stringsout uma matriz de strings tal que stringsoutij é o string sv1svn sstringsinij Exemplos retorna caracteres da posição 8 a 11 partComo usar part 811 retorna caracteres da posição 2 a 4 para cada elemento caractere inexistente substituído por c partaabcabcd24 retorna o caractere da posição 1 para cada elemento e adiciona caracteres da posição 4 a 7 de cada elemento c partabcdefghijklmnopqrstu147 retorna o caractere 4 para cada elemento adiciona caracteres da posição 1 a 7 e adiciona o caractere da posição 4 para cada elemento c partabcdefghijklmnopqrstu4174 retorna o caractere da posição 1 adiciona de novo o caractere da posição 1 e o caractere da posição 2 cpartaabcabcd112 a a a partaabcabcd1 aa aa aa partaabcabcd11 aa aab aab partaabcabcd112 Ver Também string length 1803 Name regexp acha um string que corresponde ao string de expressão regular startregexpinputpatternflag startendmatchregexpinputpatternflag startendregexpinputpatternflag startendmatchregexpinputpatternflag Parâmetros input string pattern string sob regras de expressão regular start o índice de início de cada substring de str que corresponde ao padrão do string de expressão regular end o índice de fim de cada substring de str que corresponde ao padrão do string de expressão regular match o texto de cada substring de que corresponde a pattern flag o para correspondência com padrão uma vez Descrição As regras de expressão regular são similares às da linguagem Perl Para uma introdução rápido veja httpperldocperlorgperlrequickhtml Para um tutorial mais profundo veja httpperldocperlorg perlretuthtml e para página de referência veja httpperldocperlorgperlrehtml Uma diferença para Perl é que correspondência entre posições mas não entre caracteres por exemplo com ou o é uma correspondência válida em Perl mas não em Scilab Exemplos regexpxabyabbbzabo regexpaa041 regexpABCCabci regexpABCabcdi a b cregexpXABYABBBZabi Ver Também strindex 1804 Name sci2exp converte uma expressão para um string tsci2expa nam lmax Parâmetros a expressão Scilab Pode ser constante polinomial matriz de strings lista matriz de booleanos nam string t vetor de strings contém a expressão ou a instrução de simulação lmax inteiro contém o comprimento de linha máximo O valor padrão é 90 lmax0 indica ausência de controle de comprimento de linha um único string é retornado Descrição sci2exp converte expressão para um string de instrução se nam for fornecido ou para um string de expressão Exemplos a1 23 4 sci2expaaa sci2expaaa0 sci2expssrand222 sci2exppoly1 0 3 4sfi 1805 Name str2code retorna códigos scilab inteiros associados aos caracteres do string cstr2codestr Parâmetros str um string c um vetor de códigos de caracteres inteiros Descrição Retorna c tal que ci é o código scilab inteiro de partstri Exemplos str2codeScilab code2str28 12 18 21 10 11 Ver Também code2str ascii 1806 Name strcat concatena strings txtstrcatvectorofstrings stringadded txtstrcatvectorofstrings stringaddedflag Parâmetros vectorofstrings vetor de strings stringadded string adicionado o valor padrão é emptystr txt string flag string r para retornar uma matriz coluna c para retornar uma matriz linha Descrição txtstrcatvectorofstrings concatena strings txtvectorofstrings1vectorofstringsn txtstrcatvectorofstringsstringadded retorna txtvectorofstrings1stringaddedstringadded vectorofstringsn O símbolo de mais faz o mesmo ab é o mesmo que strcatab Se o tamanho de vectorofstrings for um retorna txtvectorofstrings1 strcatAB retorna A não AB como strcatAB Exemplos strcatstring110 strcatab strcatab strcatA strcatAB strcatAB strcatAB Ver Também string strings 1807 Name strchr acha a primeira ocorrência de um caractere em um string res strchrhaystackchar Parâmetros haystack string ou matriz de strings char caractere res string ou matriz de strings Descrição res strchrhaystackchar retorna a primeira ocorrência do caractere no string str num deve ter as mesmas dimensões que haystack ou apenas um caractere Exemplos strchrEste é um string de amostras strchrEste é um string de amostrano scilabs strchrEste é um string de amostrano scilabsa Ver Também strrchr strstr 1808 Name strcmp compara strings res strcmpstringonestringtwoi Parâmetros stringone string ou matriz de strings stringtwo string ou matriz de strings i parâmetro para realização de stricmp caso independente o valor padrão é s res matrix Descrição res strcmpstringonestringtwo retorna um valor inteiro indicando a relação entre os strings Um valor maior que zero indica que o primeiro caractere não correspondente possui valor maior em stringone que em stringtwo Um valor abaixo de zero indica o contrário Exemplos TXT1 scilabSciLabStrcmpSTRcmp TXT2 ScIlAbsciLabsTrCmPStrCMP strcmpTXT1TXT2 strcmpTXT1scilab strcmpTXT1SciLab strcmpTXT1TXT2i Ver Também strcat strcmpi 1809 Name strcmpi compara strings caso independente res strcmpistringonestringtwo Parâmetros stringone string ou matriz de strings stringtwo string ou matriz de strings res matriz Descrição res strcmpistringonestringtwo retorna um valor inteiro indicando a relação entre os strings Um valor inteiro maior que zero indica que o primeiro caractere que não corresponde possui valor maior em stringone que em stringtwo Um valor negativo indica o contrário Exemplos TXT1 scilabSciLabStrcmpSTRcmp TXT2 ScIlAbsciLabsTrCmPStrCMP strcmpiTXT1TXT2 strcmpiTXT1scilab Ver Também strcat strcmp 1810 Name strcspn retorna extensão até um caractere em um string res strcspnstringonestringtwo Parâmetros stringone string ou matriz de strings stringtwo string ou matriz de strings res matriz Descrição res strcspnstringonestringtwo lê stringone para a primeira ocorrência de qualquer caractere que esteja em stringtwo retornando o número de caracteres de stringone lidos antes da primeira ocorrência stringone deve ter as mesmas dimensões que stringtwo ou stringone deve ser um string Exemplos strcspnfcba731234567890 strcspnfcba73f7cba731234567890 strcspnfcba73f7cba7331234567890 Ver Também strspn 1811 Name strindex procura posição de um string em outro indstrindexhaystackneedleflag indwhichstrindexhaystackneedleflag Parâmetros haystack string O string onde se procurará por ocorrências de needle needle string ou vetor de strings Os strings a serem procurados em haystack ind vetor de índices which vetor de índices flag string r para expressão regular Descrição strindex procura índices onde needle i é encontrado em haystack Para cada k existe um i tal que parthaystackindk0lengthneedlei1 é o mesmo string que needlei Se o argumento which for requerido ele contém esses i Quando se usa o terceiro parâmetro r needle deve ser um string de expressão regular Então strindex irá corresponder a haystack de acordo com as regras regulares expressas strindex sem expressão regular é baseado no algoritmo de KnuthMorrisPratt Este algoritmo é mais poderoso que aquele usado no Scilab 4x Em alguns casos especiais o resultado pode ser diferente Exemplo Scilab 5x kwstrindexaabaab w 1 1 2 k 1 2 2 scilab 4x kwstrindexaabaab w 1 1 k 1 2 As regras de expressão regular são similares às da linguagem Perl Para uma introdução rápida ver httpperldocperlorgperlrequickhtml Para um tutorial mais profundo ver httpperldocperlorg perlretuthtml e para a página de referência ver httpperldocperlorgperlrehtml Exemplos strindex 1812 kstrindexSCIdemosscicos kstrindexSCIdemosscicosSCI kstrindexSCIdemosscicos kstrindexaaaaaaa kstrindexSCIdemosscicosSCIsci kwstrindex13abc233 kstrindex2 21 r Ver Também string strings regexp strsubst 1813 Name string conversão para string cadeia de caracteres stringx outintextstringx Parâmetros x matriz de reais ou função Descrição Converte uma matriz em uma matriz de strings Se x é uma função outintextstringx retorna três vetores de strings out é o vetor de variáveis de saída in é o vetor de variáveis de entrada e text é o vetor coluna do código fonte da função Se x é uma variável lib bibiloteca text é um vetor coluna de strings O primeiro elemento contém o endereço do arquivo biblioteca e o outro o nome da função que ela define Strings são definidos como string entre aspas simples ou string entre aspas duplas matrizes de strings são definidas como matrizes de constantes Concatenação de strings é feita pela operação Exemplos stringrand22 deffymymacroxyx1 outintextstringmymacro x123356 Result is stringx dispstringt dispstringi1 dispstringint16123 dispstring1ss3 Ver Também part length quote evstr execstr strsubst strcat strindex sci2exp 1814 Name strings objeto Scilab strings cadeias de caracteres Descrição Strings são definidos como string entre aspas simples ou string entre aspas duplas matrizes de strings são definidascomo matrizes constantes como de uso A concatenação de dois strings é feita por string1string2 Exemplos estaé uma matriz2x2 matrixmatrix Ver Também part length strcat 1815 Name stripblanks retira espaços em branco e tabulações no início ou no fim de strings txtstripblankstxttabs Parâmetros txt um string ou uma matriz de strings tabs se TRUE retira também tabulações o valor padrão é FALSE Descrição stripblanks retira espaços em branco e tabulações no início ou no fim de strings Exemplos a 123 a stripblanksa a 123 xyz strcatstripblanksa 1816 Name strncpy copia caracteres de strings res strncpystr1num Parâmetros str1 string ou matriz de strings num matriz Números máximos de caracteres a serem copiados da fonte res string ou matriz de strings Descrição res strncpystr1num copia os primeiros num caracteres da fonte para o destino num deve ter as mesmas dimensões que str1 ou deve ser um número Exemplos strncpyscilab3 strncpyscilabSciLabstrncpystrstr3 strncpyscilabSciLabstrncpystrstr1234 Ver Também strcat strcmp 1817 Name strrchr acha a última ocorrência de um caractere em um string res strrchrstr1char Parâmetros str1 string ou matriz de strings char caractere res string ou matriz de strings Descrição res strrchrstr1char retorna a última ocorrência de caractere no string str num deve ter as mesmas dimensões que str1 ou apenas um caracteres char Exemplos strrchrEste e um string de amostras strrchrEste e um string de amostrano scilabs strrchrEste e um string de amostrano scilabsa Ver Também strchr strstr 1818 Name strrev retorna um string invertido res strrevstr1 Parâmetros str1 um string ou uma matriz de strings res um string ou uma matriz de strings Descrição res strrevstr1 retorna o string em ordem inversa Exemplos rev strrevThis is a simple string strrevrev strrevThis is a simple stringscilab 1819 Name strsplit divide um string em um vetor de strings v strsplitstrind Parâmetros str string ind um vetor de índices estritamente crescentes no intervalo 1 lengthstr1 v o vetor coluna resultante de strings dimensão sizeind1 Descrição v strsplitstrind divide o string str em um vetor de strings nos pontos dados pelos índices em ind após cada caractere apontado pelo índice em ind Exemplos Sstrsplit divide um string em um vetor de strings strsplitS15 25 30 indstrindexS Ver Também strcat tokens Autor S Steer INRIA 1820 Name strspn retorna a extensão do conjunto de caracteres no string res strspnstr1str2 Parâmetros str1 string ou matriz de strings str2 string ou matriz de strings res matriz Descrição res strspnstr1str2 retorna o comprimento da porção inicial de str1 que consiste apenas de caracteres que fazem parte de str2 str2 deve ter as mesmas dimensões que str2 ou str1 pode ser um string Exemplos i strspn129o1234567890 printf O comprimento do numero inicial e d i i strspn129o130o1234567890130o Ver Também strcspn 1821 Name strstr localiza substrings res strstrhaystackneedle Parâmetros haystack string ou matriz de strings needle string ou matriz de strings res string ou matriz de strings Descrição res strstrhaystackneedle retorna uma matriz de strings começando onde da primeira ocorrência de needle em haystack até o fim de haystack ou se needle não é parte de haystack Exemplos strstrEste é um string simplessimples strstrEste é um string simplessamples strstrEste é um string simplesno scilabé strstrEste é um string simplesno scilabumscilab Ver Também strrchr strchr 1822 Name strsubst substitui um string por outro dentro de um string stringoutstrsubststringinsearchStrreplaceStr stringoutstrsubststringinsearchStrreplaceStrflag Parâmetros stringin matriz de strings Os strings nos quais serão procuradas ocorrências de searchStr searchStr string a se procurar em string replaceStr string O string de reposição strout matriz de strings O resultado da substituição em searchStr por replaceStr em string flag string r para expressão regular Descrição strsubst substitui todas as ocorrências de searchStr em string por replaceStr Quando se utiliza o quarto argumento r searchStr deve ser um string de uma expressão regular Então strsubst o fará corresponder com string e substituirá de acordo com a regra expressas regulares Exemplos strsubstSCIdemosscicosSCI strsubstSCIdemosscicos strsubst2 21 0r Ver Também string strings 1823 Name strtod converte um string para um double d strtodstr dendstr strtodstr Parâmetros str string ou matriz de strings d escalar real ou matriz de reais endstr string ou matriz de strings próximo caractere em str após o valor numérico Descrição dendstr strtodstr analisa o string str interpretando o seu conteúdo como um número de ponto flutuante e retorna o seu valor como um real Exemplos strtod123556Este 233 um real de amostra dendstr strtod123556Este 233 um real de amostra strtod123556Este 233 um real de amostra888666 aqui dendstr strtod123556Este 233 um real de amostra888666 aqui 1824 Name strtok divide um string em fichas tokens res strtokstrdelimiters Parâmetros str string delimiters string res string Descrição res strtokstrdelimiters divide str em fichas que são seqüências de caracteres contíguos separados por qualquer um dos caracteres que fazem parte do string delimiters delimiters delimitadores Exemplos TOKENS token strtokUm string de fichas e algumas fichas mais TOKENS TOKENStoken while token token strtok TOKENS TOKENStoken end dispTOKENS Ver Também strrchr strchr 1825 Name tokenpos retorna as posições das fichas token em um string kdftokenposstr delimiter Parâmetros str string O string onde se deve procurar fichas delimiter opcional um caractere ou vetor de caracteres Os delimitadores de fichas kdf matriz de duas colunas a primeira coluna fornece os índices dos primeiros caracteres das fichas a segunda fornece os índices dos últimos caracteres das fichas Descrição kdftokenposstr delimiter busca as fichas inclusas no string str O valor padrão de delimiter é Tab onde Tab é ascii9 Retorna os índices dos primeiros e últimos caracteres de cada ficha encontrada Exemplos strIsto é um string kdftokenposstr firstpartstrkdf11kdf12 Ver Também strindex tokens 1826 Name tokens retorna as fichas tokens de um string Ttokensstr delimiter Parâmetros str string o local de procura dos tokens delimiter opcional um caractere ou um vetor de caracteres Os delimitadores de fichas T vetor coluna de fichas encontradas Descrição Ttokensstr delimiter procura pelos tokens inclusos no string str O padrão de delimiter é Tab onde Tab é ascii9 Exemplos tokensIsto é um string tokensSCIdemosscicos tokensyab2 Ver Também strindex tokenpos 1827 Name tree2code gera a definição ASCII de uma função Scilab txttree2codetreeprettyprint Parâmetros tree uma árvore macro vinda de macr2tree prettyprint valor opcional booleano T o código gerado é identado e embelezado F o código gerado não é embelezado padrão txt um vetor coluna de strings o texto fornecendo as instruções Scilab Descrição Dada uma função Scilab carregada tree retornada por macr2tree tree2code permite gerar nova mente o código Exemplos treemacr2treecosh txttree2codetreeT writeio2txta Ver Também macr2tree Autor VC Parte XXXII Cálculos Formais 1829 Name addf adição simbólica addfab Parâmetros ab strings Descrição addfab retorna a cadeia de caracteres ab Simplificações triviais tais como addf0a ou addf12 são realizadas Exemplos addf01 addf1a addf12 ab Ver Também mulf subf ldivf rdivf eval evstr 1830 Name ldivf divisão simbólica esquerda invertida ldivfdc Descrição Retorna o string cd Simplificações triviais como 1c c são realizadas Exemplos ldivf11 ldivfa0 ldivfax ldivf24 Ver Também rdivf addf mulf evstr 1831 Name mulf multiplicação simbólica mulfdc Descrição Retorna o string cd Simplificações triviais tais como 1c c são realizadas Exemplos mulf1a mulf0a ab Cuidado Ver Também rdivf addf subf 1832 Name rdivf divisão simbólica direitaesquerda rldivfdc Parâmetros dcr strings Descrição Retorna o string cd Simplificações triviais tais como c1 c são realizadas Exemplos ldivfcd ldivf12 ldivfa0 Ver Também ldivf 1833 Name subf subtração simbólica csubfab Parâmetros abc strings Descrição Retorna o string cab Simplificações triviais como subf0a ou subf12 são realizadas Exemplos subf0a subf21 subfa0 Ver Também mulf ldivf rdivf eval evstr Parte XXXIII Data e Hora 1835 Name date retorna string contendo a data corrente dtdate Parâmetros dt a string Descrição dtdate retorna um string contendo a data no formato ddmmmyyyy Exemplos date Ver Também getdate toc tic timer etime 1836 Name etime tempo decorrido e etimet2t1 Parâmetros t2 um vetor com 6 ou 10 valores t1 um vetor com 6 ou 10 valores e número de segundos entre t2 e t1 Descrição t1 e t2 com 10 valores t2 e t1 devem ter o mesmo formato retornado por getdate Neste caso seus terceiro quarto e quinto valores serão ignorados t1 e t2 com 6 valores t2 e t1 devem ter o mesmo formato T Ano Mês Dia Hora Minuto Segundo com Segundo o número de segundos com milisegundos ex 12345 t2 e t1 devem ter o mesmo tamanho t2 e t1 podem ser matrizes com cada linha contendo o formato descrito acima todas as linhas tendo o mesmo formato Exemplos t12004 06 10 17 00 12345 t22004 06 10 17 01 13965 E1etimet2t1 t12004 06 24 162 5 10 17 00 12 345 t22004 06 24 162 5 10 17 01 13 965 E2etimet2t1 Ver Também tic toc getdate datenum datevec Autor VC 1837 Name getdate retorna informação sobre data e hora dtgetdate xgetdates dtgetdatex Parâmetros dt um vetor de inteiros com 10 entradas ver abaixo x um inteiro contendo uma data codificada em segundos a partir de 01011970 Descrição dtgetdate retorna a dada corrente no formato dado abaixo dt1 o ano como um número com o século entre 0000 e 9999 dt2 o mês do ano como um número entre 01 e 12 dt3 o número da semana ISO 8601 como um número entre 01 e 53 dt4 o dia Juliano do ano como um número entre 001 e 366 dt5 especifica o dia da semana como um número decimal entre 1 e 7 com 1 representando domingo dt6 o dia do mês como um número entre 01 e 31 dt7 a hora do dia como um número entre 00 e 23 dt8 o minuto da hora como um número entre 00 e 59 dt9 o segundo do minuto como um número entre 00 e 59 dt10 o milissegundo do segundo como um número entre 000 e 999 xgetdates retorna um escalar com o número de segundos desde 01011970 0000 UTC Convenção de Tempo Unix dtgetdatex põe a data dada por x número de segundos desde 01011970 0000 UTC no formato acima Neste caso dt10 é sempre igual a 0 getdate 1838 Exemplos wgetdate mprintfAnodMêsdDiadw1w2w6 xgetdates getdatex Ver Também date timer Autor VC 1839 Name tic inicia um cronômetro tic Descrição A seqüência de comando tic operation toc imprime o número de segundos requeri dos para a operação Exemplos tic realtimeinit1 realtime0 realtime10 toc Ver Também toc timer etime Autores VC AC 1840 Name toc lê o cronômetro toc t toc Parâmetros t número de segundos desde a última chamada a tic precisão em ordem de milissegundos Descrição A seqüência de comandos tic operation toc imprime o número de segundos re queridos para a operação Exemplos tic realtimeinit1 realtime0 realtime10 toc Ver Também tic timer etime Autores VC AC 1841 Name calendar Calendar ccalendar c calendarym Description c calendar returns a list containing a calendar for the current month The calendar runs Sunday to Saturday c calendarym where y and m are integers returns a calendar for the specified month of the spec ified year Examples calendar calendar19738 See Also datevec datenum Authors Allan CORNET 1842 Name clock Return current time as date vector c clock Description c clock returns a 6element date vector containing the current date and time in decimal form c year month day hour minute seconds the first five elements are integers The seconds element is accurate to several digits beyond the decimal point Examples clock See Also datenum datevec timer etime tic toc Authors PM 1843 Name datenum Convert to serial date number N datenum N datenumDT N datenumY M D N datenumY M D H MI S Description The datenum function converts date vectors defined by datevec into serial date numbers Date num bers are serial days elapsed from some reference date By default the serial day 1 corresponds to 1 Jan0000 N datenum returns the serial date numbers corresponding to current date N datenumDT converts one or more date vectors to serial date number N DT can be an mby6 or mby3 matrix containing m full or partial date vector respectively N datenumY M D returns the serial date numbers for corresponding elements of the Y M and D year month day arrays Y M and D must be arrays of the same size or any can be a scalar N datenumY M D H MI S returns the serial date numbers for corresponding elements of the Y M D H MI and S year month day hour minute and second array valuesY M D H MI and S must be arrays of the same size or any can be a scalar Examples N datenum datenum N datenumDT A 0 1 1 0 0 0 2005 2 8 21 37 30 datenumA N datenumY M D Years 0 1973 2006 Months 1 8 2 Days 1 4 8 datenumYearsMonthsDays Years 0 0 0 0 0 0 Months 1 1 1 1 1 1 Days 1 2 3 4 5 6 datenumYearsMonthsDays N datenumY M D H MI S Years grand510uin02006 Months grand510uin112 Days grand510uin128 Hours grand510uin023 Minutes grand510uin059 Seconds grand510uin059 datenumYearsMonthsDaysHoursMinutesSeconds datenum 1844 See Also datevec calendar Authors AC 1845 Name datevec Date components VdatevecDT YMDHMISdatevecDT Description V datevecDT converts a serial date number defined by datenum to a date vector V having ele ments year month day hour minute second The first five vector elements are integers DT can be an array Y M D H MI S datevecDT returns the components of the date vector as individual variables DT can be an array Examples First example datevec720840 Second example datevecdatenum Third example With integers values A grand1012uin11000000 datevecA Fourth example With real values A grand1012unf11000000 datevecA See Also datenum calendar Authors AC 1846 Name eomday Return last day of month E eomdayY M Description E eomdayY M returns the last day of the year and month given by corresponding elements of arrays Y and M Examples eomday20063 See Also datenum datevec weekday Authors PM 1847 Name now Return current date and time t now Description t now returns date and time as a serial date number See datenum Examples realtimeinit1 realtime0 t1 now datevect1 realtime10 t1 now datevect1 See Also clock datenum datevec Authors PM 1848 Name realtimeinit set time unit realtime set dates origin or waits until date realtimeinittimeunit realtimet Parameters timeunit a real number The number of seconds associated to the realtime argument t a real number A date Description These two functions can be used to handle real time into Scilab realtimeinittimeunit defines the time unit associated to the realtime argument t first call to realtimet0 sets current date to t0 subsequent calls to realtimet wait till date t is reached Examples realtimeinit12sets time unit to half a second realtime0sets current date to 0 for k110realtimekmprintfcurrent time is stringk2sec end next instruction outputs a dot each 2 seconds realtimeinit2 realtime0for k110realtimekmprintf end realtimeinit1realtime0 dtgetdates realtime10 getdatesdt See Also getdate 1849 Name sleep suspend Scilab sleepmilliseconds Description sleep Sleep process for specified number of miliseconds specified by the argument The actual suspension time may be longer because of other activities in the system or because of the time spent in processing the call Examples ticsleep6000toc See Also xpause pause Authors Allan CORNET 1850 Name timer cpu time timer Description Returns the CPU time since the preceding call to timer timer has a time precision of 100 nanoseconds NOTE CPU time is the number of processor cycles used for a computation This is not at all equivalent to realworld time CPU time can be used to compare CPU usage between different programs or functions irrespective of background processes that might slow down the computer Examples timerArand100100timer See Also getdate toc tic etime 1851 Name weekday Return day of week NS weekdayD NS weekdayD form Description NS weekdayD returns the day of the week in numericN and stringS form for a given serial date number or date string D Input argument D can represent more than one date in an array of serial date number NS weekdayD form returns the week in numericN and stringS form where the content of S depends on the form argument If form is long then S countains the full name of the weekday eg Thuesday If form is short then S contains an abbreviated name eg Tue from this table Examples today datenum NS weekdaytoday NS weekdaytodayshort NS weekdaytodaylong See Also datenum datevec weekday Authors PM Parte XXXIV Estatística 1853 Name cdfbet cumulative distribution function Beta distribution PQcdfbetPQXYAB XYcdfbetXYABPQ AcdfbetABPQXY BcdfbetBPQXYA Parameters PQXYAB five real vectors of the same size PQ Q1P The integral from 0 to X of the beta distribution Input range 0 1 Q 1P XY Y1X Upper limit of integration of beta density Input range 01 Search range 01 AB The two parameters of the beta density input range 0 infinity Search range 1D3001D300 Description Calculates any one parameter of the beta distribution given values for the others The beta density is proportional to tA1 1tB1 Cumulative distribution function P is calculated directly by code associated with the following ref erence DiDinato A R and Morris A H Algorithm 708 Significant Digit Computation of the Incomplete Beta Function Ratios ACM Trans Math Softw 18 1993 360373 Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1854 Name cdfbin cumulative distribution function Binomial distribution PQcdfbinPQSXnPrOmpr ScdfbinSXnPrOmprPQ XncdfbinXnPrOmprPQS PrOmprcdfbinPrOmprPQSXn Parameters PQSXnPrOmpr six real vectors of the same size PQ Q1P The cumulation from 0 to S of the binomial distribution Probablility of S or fewer successes in XN trials each with probability of success PR Input range 01 S The number of successes observed Input range 0 XN Search range 0 XN Xn The number of binomial trials Input range 0 infinity Search range 1E300 1E300 PrOmpr Ompr1Pr The probability of success in each binomial trial Input range 01 Search range 01 Description Calculates any one parameter of the binomial distribution given values for the others Formula 26524 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the binomial distribution to the cumulative incomplete beta distribution Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1855 Name cdfchi cumulative distribution function chisquare distribution PQcdfchiPQXDf XcdfchiXDfPQ DfcdfchiDfPQX Parameters PQXnDf four real vectors of the same size PQ Q1P The integral from 0 to X of the chisquare distribution Input range 0 1 X Upper limit of integration of the noncentral chisquare distribution Input range 0 infinity Search range 01E300 Df Degrees of freedom of the chisquare distribution Input range 0 infinity Search range 1E300 1E300 Description Calculates any one parameter of the chisquare distribution given values for the others Formula 26419 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the chisquare distribution to the incomplete distribution Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1856 Name cdfchn cumulative distribution function noncentral chisquare distribution PQcdfchnPQXDfPnonc XcdfchnXDfPnoncPQ DfcdfchnDfPnoncPQX PnonccdfchnPnoncPQXDf Parameters PQXDfPnonc five real vectors of the same size PQ Q1P The integral from 0 to X of the noncentral chisquare distribution Input range 0 11E16 X Upper limit of integration of the noncentral chisquare distribution Input range 0 infinity Search range 01E300 Df Degrees of freedom of the noncentral chisquare distribution Input range 0 infinity Search range 1E300 1E300 Pnonc Noncentrality parameter of the noncentral chisquare distribution Input range 0 infinity Search range 01E4 Description Calculates any one parameter of the noncentral chisquare distribution given values for the others Formula 26425 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to compute the cumulative distribution function Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter The computation time required for this routine is proportional to the noncentrality parameter PNONC Very large values of this parameter can consume immense computer resources This is why the search range is bounded by 10000 From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1857 Name cdff cumulative distribution function F distribution PQcdffPQFDfnDfd FcdffFDfnDfdPQ DfncdffDfnDfdPQF DfdcdffDfdPQFDfn Parameters PQFDfnDfd five real vectors of the same size PQ Q1P The integral from 0 to F of the fdensity Input range 01 F Upper limit of integration of the fdensity Input range 0 infinity Search range 01E300 Dfn Degrees of freedom of the numerator sum of squares Input range 0 infinity Search range 1E300 1E300 Dfd Degrees of freedom of the denominator sum of squares Input range 0 infinity Search range 1E300 1E300 Description Calculates any one parameter of the F distribution given values for the others Formula 2662 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the computation of the cumulative distribution function for the F variate to that of an incomplete beta Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter The value of the cumulative F distribution is not necessarily monotone in either degrees of freedom There thus may be two values that provide a given CDF value This routine assumes monotonicity and will find an arbitrary one of the two values From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1858 Name cdffnc cumulative distribution function noncentral fdistribution PQcdffncPQFDfnDfdPnonc FcdffncFDfnDfdPnoncPQ DfncdffncDfnDfdPnoncPQF DfdcdffncDfdPnoncPQFDfn PnonccdffncPnoncPQFDfnDfd Parameters PQFDfnDfdPnonc six real vectors of the same size PQ Q1P The integral from 0 to F of the noncentral fdensity Input range 011E16 F Upper limit of integration of the noncentral fdensity Input range 0 infinity Search range 01E300 Dfn Degrees of freedom of the numerator sum of squares Input range 0 infinity Search range 1E300 1E300 Dfd Degrees of freedom of the denominator sum of squares Must be in range 0 infinity Input range 0 infinity Search range 1E300 1E300 Pnonc The noncentrality parameter Input range 0infinity Search range 01E4 Description Calculates any one parameter of the Noncentral F distribution given values for the others Formula 26620 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to compute the cumulative distribution function Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter The computation time required for this routine is proportional to the noncentrality parameter PNONC Very large values of this parameter can consume immense computer resources This is why the search range is bounded by 10000 The value of the cumulative noncentral F distribution is not necessarily monotone in either degrees of freedom There thus may be two values that provide a given CDF value This routine assumes monotonicity and will find an arbitrary one of the two values From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1859 Name cdfgam cumulative distribution function gamma distribution PQcdfgamPQXShapeScale XcdfgamXShapeScalePQ ShapecdfgamShapeScalePQX ScalecdfgamScalePQXShape Parameters PQXShapeScale five real vectors of the same size PQ Q1P The integral from 0 to X of the gamma density Input range 01 X The upper limit of integration of the gamma density Input range 0 infinity Search range 01E300 Shape The shape parameter of the gamma density Input range 0 infinity Search range 1E3001E300 Scale The scale parameter of the gamma density Input range 0 infinity Search range 1E3001E300 Description Calculates any one parameter of the gamma distribution given values for the others Cumulative distribution function P is calculated directly by the code associated with DiDinato A R and Morris A H Computation of the incomplete gamma function ratios and their inverse ACM Trans Math Softw 12 1986 377393 Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter The gamma density is proportional to TSHAPE 1 EXP SCALE T From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1860 Name cdfnbn cumulative distribution function negative binomial distribution PQcdfnbnPQSXnPrOmpr ScdfnbnSXnPrOmprPQ XncdfnbnXnPrOmprPQS PrOmprcdfnbnPrOmprPQSXn Parameters PQSXnPrOmpr six real vectors of the same size PQ Q1P The cumulation from 0 to S of the negative binomial distribution Input range 01 S The upper limit of cumulation of the binomial distribution There are F or fewer failures before the XNth success Input range 0 infinity Search range 0 1E300 Xn The number of successes Input range 0 infinity Search range 0 1E300 Pr The probability of success in each binomial trial Input range 01 Search range 01 Ompr 1PR Input range 01 Search range 01 PR OMPR 10 Description Calculates any one parameter of the negative binomial distribution given values for the others The cumulative negative binomial distribution returns the probability that there will be F or fewer failures before the XNth success in binomial trials each of which has probability of success PR The individual term of the negative binomial is the probability of S failures before XN successes and is Choose S XNS1 PRXN 1PRS Formula 26526 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce calculation of the cumulative distribution function to that of an incomplete beta Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1861 Name cdfnor cumulative distribution function normal distribution PQcdfnorPQXMeanStd XcdfnorXMeanStdPQ MeancdfnorMeanStdPQX StdcdfnorStdPQXMean Parameters PQXMeanStd six real vectors of the same size PQ Q1P The integral from infinity to X of the normal density Input range 01 X Upper limit of integration of the normaldensity Input range infinity infinity Mean The mean of the normal density Input range infinity infinity Sd Standard Deviation of the normal density Input range 0 infinity Description Calculates any one parameter of the normal distribution given values for the others A slightly modified version of ANORM from Cody WD 1993 ALGORITHM 715 SPECFUN A Portabel FORTRAN Package of Special Function Routines and Test Drivers acm Transactions on Mathematical Software 19 2232 is used to calulate the cumulative standard normal distribution The rational functions from pages 9095 of Kennedy and Gentle Statistical Computing Marcel Dekker NY 1980 are used as starting values to Newtons Iterations which compute the inverse stan dard normal Therefore no searches are necessary for any parameter For X 15 the asymptotic expansion for the normal is used as the starting value in finding the inverse standard normal This is formula 26212 of Abramowitz and Stegun The normal density is proportional to exp 05 X MEANSD2 From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1862 Name cdfpoi cumulative distribution function poisson distribution PQcdfpoiPQSXlam ScdfpoiSXlamPQ XlamcdfpoiXlamPQS Parameters PQSXlam four real vectors of the same size PQ Q1P The cumulation from 0 to S of the poisson density Input range 01 S Upper limit of cumulation of the Poisson Input range 0 infinity Search range 01E300 Xlam Mean of the Poisson distribution Input range 0 infinity Search range 01E300 Description Calculates any one parameter of the Poisson distribution given values for the others Formula 26421 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the computation of the cumulative distribution function to that of computing a chisquare hence an incomplete gamma function Cumulative distribution function P is calculated directly Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1863 Name cdft cumulative distribution function Students T distribution PQcdftPQTDf TcdftTDfPQ DfcdftDfPQT Parameters PQTDf six real vectors of the same size PQ Q1P The integral from infinity to t of the tdensity Input range 01 T Upper limit of integration of the tdensity Input range infinity infinity Search range 1E150 1E150 DF Degrees of freedom of the tdistribution Input range 0 infinity Search range 1e300 1E10 Description Calculates any one parameter of the T distribution given values for the others Formula 26527 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the computation of the cumulative distribution function to that of an incomplete beta Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter 1864 Name center center scenterx scenterxr or scenterx1 scenterxc or scenterx2 Parameters x real or complex vector or matrix Description This function computes s the centred version of the numerical matrix x For a vector or a matrix x scenterx returns in the ij coefficient of the matrix s the value xijxbar where xbar is the mean of the values of the coefficients of x scenterxr or equivalently scenterx1 is the rowwise center reduction of the values of x It returns in the entry sij the value xijxbarvjj with xbarvj the mean of the values of the j column scenterxc or equivalently scenterx2 is the columnwise center reduction of the values of x It returns in the entry sij the value xijxbarhi with xbarhi the mean of the values of the i row Examples x02113249 00002211 06653811 07560439 03303271 06283918 scenterx scenterxr scenterxc See Also wcenter Authors Carlos Klimann 1865 Name wcenter center and weight swcenterx swcenterxr or swcenterx1 swcenterxc or swcenterx2 Parameters x real or complex vector or matrix Description This function computes s the weigthed and centred version of the numerical matrix x For a vector or a matrix x swcenterx returns in the ij coefficient of the matrix s the value xijxbarsigma where xbar is the mean of the values of the coefficients of x and sigma his standard deviation swcenterxr or equivalently swcenterx1 is the rowwise centre reduction of the values of x It returns in the entry sij the value xijxbarvjsigmavj with xbarvj the mean of the values of the j column and sigmavj the standard deviation of the j column of x swcenterxc or equivalently swcenterx2 is the columnwise centre reduction of the values of x It returns in the entry sij the value xijxbarhisigmahi with xbarhi the mean of the values of the i row and sigmahi the standard deviation of the i row of x Examples x02113249 00002211 06653811 07560439 03303271 06283918 swcenterx swcenterxr swcenterxc See Also center Authors Carlos Klimann 1866 Name cmoment central moments of all orders momcmomentxord momcmomentxordr or momcmomentxord1 momcmomentxordc or momcmomentxord2 Parameters x real or complex vector or matrix ord positive integer Description cmomentxord is the central moment or order ord of the elements of x If a third argument of type string r or 1 or c or 2 is used we get in the first case a row vector mom such that momj contains the central moment of order ord of the j column of x cmomentxordc is used in the same way for the central moments in the rows References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples x02113249 00002211 06653811 07560439 03303271 06283918 momcmomentx3 momcmomentx2r momcmomentx3c See Also sum median stdeviation mean meanf moment nanmean nanmeanf stdev stdevf variance variancef nanstdev Authors Carlos Klimann 1867 Name correl correlation of two variables rhocorrelxyfre Parameters x real or complex vector y real or complex vector fre matrix of type lengthx x lengthy Description correlxyfre computes the correlation of two variables x and y fre is a matrix of dimen sions lengthx x lengthy In fre the element of indices ij corresponds to the value or number or frequences of xiyj References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples x25 75 125 175 h0 1 2 fre03 12 0702 13 1101 13 1401 09 14 rhocorrelxhfre See Also covar Authors Carlos Klimann 1868 Name covar covariance of two variables scovarxyfre Parameters x real or complex vector y real or complex vector fre matrix of type lengthx x lengthy Description covarxyfre computes the covariance of two variables x and y fre is a matrix of dimensions lengthx x lengthy In fre the element of indices ij corresponds to the value or number or fre quences of xiyj References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples x10 20 30 40 y10 20 30 40 fre20 04 01 0 10 36 09 0 0 05 10 0 0 0 0 05 scovarxyfre Authors Carlos Klimann 1869 Name ftest Fischer ratio fftestsamples fpftestsamples Parameters samples real or complex matrix of type nr X nc Description fftestsamples computes the Fischer ratio of the nc samples whose values are in the columns of the matrix samples Each one of these samples is composed of nr values The Fischer ratio is the ratio between nr times the variance of the means of samples and the mean of variances of each sample fpftestsamples gives in p the pvalue of the computed Fischer ratio f References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples samples46 55 54 53 54 50 49 58 51 50 61 51 46 52 49 fpftestsamples See Also ftuneq Authors Carlos Klimann 1870 Name ftuneq Fischer ratio for samples of unequal size fftuneqsample1sample2sample3 fpftuneqsample1sample2sample3 Parameters sample1 sample2 sample3 real or complex matrix of any type Description This function computes the F ratio for samples of unequal size The most efficient design is to make all samples the same size n However when this is nor feasible it still is possible to modify the ANOVA calculations Note that the definition of xbarbar is no longer meanxbar but rather a weighted average with weights ni Additionnally it gives in p the pvalue of the computed Fischer ratio Given a number a of samples each of them composed of ni i from 1 to a observations this fonction computes in f the Fischer ratio it is the ratio between nr times the variance of the means of samples and the mean of the variances of each sample fftestsamples computes the Fischer ratio of the nc samples whose values are in the columns of the matrix samples Each one of these samples is composed of nr values The Fischer ratio is the ratio between nr times the variance of the means of samples and the mean of variances of each sample fpftestsamples gives in p the pvalue of the computed Fischer ratio f References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples samples46 55 5453 54 50 49 58 5150 61 5146 52 49 fpftestsamples See Also ftuneq Authors Carlos Klimann 1871 Name geomean geometric mean gmgeomeanx gmgeomeanxror equivalently gmgeomeanx1 gmgeomeanxcor equivalently gmgeomeanx2 Parameters x real or complex vector or matrix Description This function computes the geometric mean of a vector or matrix x For a vector or matrix x gmgeomeanx returns in scalar gm the geometric mean of all the entries of x gmgeomeanxr or equivalently gmgmeanx1 returns in each entry of the row vector gm the geometric mean of each column of x gmgeomeanxc or equivalently gmgmeanx2 returns in each entry of the column vector gm the geometric mean of each row of x Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1872 Name harmean harmonic mean hmharmeanx hmharmeanxror equivalently hmharmeanx1 hmharmeanxcor equivalently hmharmeanx2 Parameters x real or complex vector or matrix Description This function computes the harmonic mean of a vector or matrix x For a vector or matrix x hmharmeanx returns in scalar hm the harmonic mean of all the entries of x hmharmeanxr or equivalently hmharmeanx1 returns in each entry of the row vector hm the harmonic mean of each column of x hmharmeanxc or equivalently hmharmeanx2 returns in each entry of the column vector hm the harmonic mean of each row of x Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1873 Name iqr interquartile range qiqrx qiqrxr or equivalently qiqrx1 qiqrxc or equivalently qiqrx2 Parameters x real or complex vector or matrix Description This function computes the interquartile range IQR upper quartile lower quartile of a vector or a matrix x For a vector or a matrix x qiqrx returns in the scalar q the interquartile range of all the entries of x qiqrxr or equivalently qiqrx1 is the rowwise interquartile range It returns in each entry of the row vector q the interquartile range of each column of x qiqrxc or equivalently qiqrx2 is the columnwise interquartile range It returns in each entry of the column vector q the interquartile range of each row of x Authors Carlos Klimann Bibliography Wonacott THWonacott RJ Introductory Statistics JWileySons 1990 1874 Name labostat Statistical toolbox for Scilab Contents centre centering variables centrered centering and reducing variables cmoment central moments of all orders correl correlation covar covariance ftest fischer test and his pvalue geomean geometric mean harmean harmonic mean iqr interquartile range mad mean absolute deviation meanf arithmetic mean of a vector or matrix with a table of frequences median 50th percentile of a sample mn arithmetic mean of a vector or matrix moment moments of all orders msd mean squared deviation mvvacov multivariable matrix of variancecovariance nand2mean estimate of the difference of means of two independent samples nanmax maximum ignoring NaNs nanmean mean ignoring NaNs nanmeanf mean with frequency table ignoring NaNs nanmedian 50th percentile of a sample ignoring NaNs nanmin minimum ignoring NANs nanstdev standard deviation ignoring NaNs nanstdevf standard deviation with frequency table ignoring NaNs nansum sum ignoring NaNs nfreq frequency of the values of a sample pca principal component analysys pctl vector of percentiles of a sample in decreasing order perctl vector of percentiles of a sample in decreasing order quart quartils stdev standard deviation stdevf standard deviation with frequences strange distance between largest and smallest value tabul frequences of values var variance varf variance with frequence table References Wonacott TH Wonacott RJ Introductory Statistics 5th edition JWiley Sons 1990 Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 1875 Name mad mean absolute deviation s2madx s2madxr or s2madx1 s2madxc or s2madx2 Parameters x real or complex vector or matrix Description This function computes the mean absolute deviation of a real or complex vector or matrix x For a vector or matrix x s2madx returns in scalar s2 the mean absolute deviation of all the entries of x s2madxr or equivalently s2madx1 returns in each entry of the column vector s2 the mean absolute deviation of each column of x s2madxc or equivalently s2madx2 returns in each entry of the column vector s2 the mean absolute deviation of each row of x Bibliography Reference Wonacott TH Wonacott RJ Introductory Statistics 5th edition John Wiley 1990 1876 Name mean mean row mean column mean of vectormatrix entries ymeanx ymeanxr ymeanxc ymeanxm Parameters x real vector or matrix y scalar or vector Description For a vector or a matrix x ymeanx returns in the scalar y the mean of all the entries of x ymeanxr or equivalently ymeanx1 is the rowwise mean It returns a row vector yj meanxj ymeanxc or equivalently ymeanx2 is the columnwise mean It returns a column vector yi meanxi ymeanxm is the mean along the first non singleton dimension of x for compatibility with Matlab Examples A1210771701 meanA meanAr meanAc Amatrix11211232 in this case meanAm is equivalent to meanA3 the first non singleton dimension of A ymeanAm See Also sum median stdeviation 1877 Name meanf weighted mean of a vector or a matrix mmeanfvalfre mmeanfvalfrer or mmeanfvalfre1 mmeanfvalfrec or mmeanfvalfre2 Parameters Description This function computes the mean of a vector or matrix x For a vector or matrix x mmnx re turns in scalar m the mean of all the entries of x mmnxr or equivalently mmnx1 returns in each entry of the row vector m the mean of each column of x mmnxc or equivalently mmnx2 returns in each entry of the column vector m the mean of each row of x Examples x02113249 00002211 0665381107560439 03303271 06283918 mmeanfxrandx mmeanfx10 10 101 1 1r mmeanfx10 10 101 1 1c Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1878 Name median median row median column median of vectormatrixarray entries ymedianx ymedianxr ymedianxc ymedianxm ymedianxdim Parameters x real vector matrix or an array y scalarvector matrix or an array dim positive integer Description For a vector or a matrix x ymedianx returns in the scalar y the median of all the entries of x ymedianxr or equivalently ymedianx1 is the median along the row index It returns in each entry of the column vector y the median of each column of x ymedianxc or equivalently ymedianx2 is the median along the column index It returns in each entry of the row vector y the median of each row of x ymedianxm is the median along the first non singleton dimension of x for compatibility with matlab ymedianxdim is the median along the dimension dim of x for compatibility with matlab Examples A1210771701 medianA medianAr medianAc Amatrix9 3 8 6 74 39 12 6 89 23 65 34232 medianA3 medianAm See Also sum mean 1879 Name moment non central moments of all orders mommomentxord mommomentxordr or mommomentxord1 mommomentxordc or mommomentxord2 Parameters x real or complex vector or matrix ord positive integer Description momentxord is the non central moment or order ord of the elements of x If a third argument of type string r or 1 or c or 2 is used we get in the first case a row vector mom such that momj contains the non central moment of order ord of the j column of x momentxordc is used in the same way for the non central moments in the rows Examples x02113249 00002211 0665381107560439 03303271 06283918 mommomentx3 mommomentx2r mommomentx3c Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1880 Name msd mean squared deviation ymsdx ymsdxr or mmsdx1 ymsdxc or mmsdx2 Parameters x real or complex vector or matrix Description This function computes the mean squared deviation of the values of a vector or matrix x For a vector or a matrix x ymsdx returns in the scalar y the mean squared deviation of all the entries of x ymsdxr or equivalently ymsdx1 is the rowwise mean squared deviation It returns in each entry of the row vector y the mean squared deviation of each column of x ymsdxc or equivalently mmsdx2 is the columnwise mean squared deviation It returns in each entry of the column vector y the mean squared deviation of each row of x Examples x02113249 00002211 0665381107560439 03303271 06283918 mmsdx mmsdxr mmsdxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1881 Name mvvacov computes variancecovariance matrix vmvvacovx Parameters x real or complex vector or matrix Description This function computes v the matrix of variancecovariance of the tableau x x is a numerical matrix nxp who gives the values of p variables for n individuals the ij coefficient of v is vijExixibar xjxjbar where E is the first moment of a variable xi is the ith variable and xibar the mean of the xi variable Examples x02113249 00002211 0665381107560439 04453586 06283918 vmvvacovx Authors Carlos Klimann Bibliography Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 Mar dia KV Kent JT Bibby JM Multivariate Analysis Academic Press 1979 1882 Name nancumsum Thos function returns the cumulative sum of the values of a matrix s nancumsumxorient Parameters x x is a numerical vector or matrix orient is an optional parameter The possible values are 1 2 r or c s numerical scalar or vector It contains the cumulative sum of the values of x ignoring the NANs Description This function returns in scalar or vector s the cumulative sum of the values ignoring the NANs of a vector or matrix real or complex x This function for a vector or a matrix x snancumsumx or equivalently snancumsumx returns in scalar s the cumulative sum ignoring the NANs of all the entries of x taken columnwise snancumsumxr or equivalently snancumsumx1 returns in the colsx sized vector s the cumulative sum ignoring the NANs of the rows of x sinancumsumxi snancumsumxc or equivalently snancumsumx2 returns in the rowsx sized vector s the cumulative sum ignoring NANs of the columns of x sinancumsumxi For the last two cases if a row or column is in whole composed of NAN the corresponding place of s will contain a NAN Examples a1 2 34 5 6 snancumsuma snancumsumar snancumsumac See Also nansum cumsum Authors Carlos Klimann 1883 Name nand2mean difference of the means of two independent samples difnand2meansample1sample2 difnand2meansample1sample2conf Parameters sample1 real or complex vector or matrix sample2 real or complex vector or matrix conf real scalar between 0 and 1 Description This function computes an estimate dif1 for the difference of the means of two independent sam ples arrays sample1 and sample2 and gives the half amplitude of the range of variability of dif with an indicated confidence level dif2 The choice of the normal or t fonctions as the probability fonc tion depends on the sizes of sample1 and sample2 We suppose that the underlying variances of both populations are equal NAN values are not counted In Labostat NAN values stand for missing values in tables In absence of the confidence parameter a confidence level of 95 is assumed References Wonacott TH Wonacott RJ Introductory Statistics 5th edition JWiley Sons 1990 1884 Name nanmax max ignoring Nans mindexnanmaxx mindexnanmaxxr mindexnanmaxxc Parameters x real or complex vector or matrix Description This function gives for a real or a numerical matrix x his largest element m but ignoring the NANs For x a numerical vector or matrix mnanmaxx returns in scalar m the largest element of x ignoring the NANs The form mindex nanmaxxorient gives in addition of the value of the largest element of x ignoring the NANs in scalar m the index of this element in x as a 2vector mnanmaxxr gives in the 1xsizex2 matrix m the largest elements ignoring the NANs of each column of x If the form mindexnanmaxxr is used the elements of the 1xsizex2 matrix index are the indexes of the largest elements ignoring the NANs of each column of x in the corresponding column mnanmaxxc gives in the sizex2x1 matrix m the largest elements ignoring the NANs of each row of x If the form mindexnanmaxxc is used the elements of the sizex2x1 matrix index are the indexes of the largest elements ignoring the NANs of each row of x in the corresponding row In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 mnanmaxx mnanmaxxr mnanmaxxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1885 Name nanmean mean ignoring Nans mnanmeanval mnanmeanvalr or mnanmeanval1 mnanmeanvalc or mnanmeanval2 Parameters val real or complex vector or matrix Description This function returns in scalar m the mean of the values ignoring the NANs of a vector or matrix val For a vector or matrix val mnanmeanval or mnanmeanval returns in scalar m the mean of all the entries ignoring the NANs of val mnanmeanvalr or equivalently mnanmeanval1 returns in each entry of the row vector m of type 1xsizevalc the mean of each column of val ignoring the NANs mnanmeanfvalc or equivalently mnanmeanval2 returns in each entry of the column vector m of type sizevalcx1 the mean of each row of val ignoring the NANs In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 mnanmeanx mnanmeanx1 mnanmeanx2 Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1886 Name nanmeanf mean ignoring Nans with a given frequency mnanmeanvalfre mnanmeanvalfrer or mnanmeanvalfre1 mnanmeanvalfrec or mnanmeanvalfre2 Parameters val real or complex vector or matrix fre integer vector or matrix with same dimensions than val Description This function returns in scalar m the mean of the values ignoring the NANs of a vector or matrix val each counted with a frequency signaled by the corresponding values of the integer vector or matrix fre with the same type of val For a vector or matrix val mnanmeanfvalfre or mnanmeanfvalfre returns in scalar m the mean of all the entries ignoring the NANs of val each value counted with the multiplicity indicated by the corresponding value of fre mnanmeanfvalfrer or equivalently mnanmeanfvalfre1 returns in each entry of the row vector m of type 1xsizevalc the mean of each column of val ignoring the NANs each value counted with the multiplicity indicated by the corresponding value of fre mnanmeanfvalfrec or equivalently mnanmeanfvalfre2 returns in each entry of the column vector m of type sizevalcx1 the mean of each row of val ignoring the NANs each value counted with the multiplicity indicated by the corresponding value of fre In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 fre34 12 2512 23 5 mnanmeanfxfre mnanmeanfxfre1 mnanmeanfxfre2 Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1887 Name nanmedian median of the values of a numerical vector or matrix mnanmedianx mnanmedianxr or mnanmedianx1 mnanmedianxc or mnanmedianx2 Parameters x real or complex vector or matrix Description For a vector or a matrix x mnanmedianx returns in the vector m the median of the values ignoring the NANs of vector x mnanmedianxr or equivalently mnanmedianx1 are the rowwise medians It returns in each position of the row vector m the medians of data ignoring the NANs in the corresponding column of x mnanmedianxc or equivalently mnanmedianx2 are the columnwise ma dians It returns in each position of the column vector m the medians of data ignoring the NANs in the corresponding row of x In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 mnanmedianx mnanmedianx1 mnanmedianx2 Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1888 Name nanmin min ignoring Nans mindexnanminx mindexnanminxr mindexnanminxc Parameters x real or complex vector or matrix Description This function gives for a real or a numerical matrix x his largest element m but ignoring the NANs For x a numerical vector or matrix mnanminx returns in scalar m the largest element of x ignoring the NANs The form mindex nanminxorient gives in addition of the value of the largest element of x ignoring the NANs in scalar m the index of this element in x as a 2vector mnanminxr gives in the 1xsizex2 matrix m the largest elements ignoring the NANs of each column of x If the form mindexnanminxr is used the elements of the 1xsizex2 matrix index are the indexes of the largest elements ignoring the NANs of each column of x in the corresponding column mnanminxc gives in the sizex2x1 matrix m the largest elements ignoring the NANs of each row of x If the form mindexnanminxc is used the elements of the sizex2x1 matrix index are the indexes of the largest elements ignoring the NANs of each row of x in the corresponding row In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 mnanminx mnanminxr mnanminxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1889 Name nanstdev standard deviation ignoring the NANs snanstdevx snanstdevxr or mnanstdevx1 snanstdevxc or mnanstdevx2 Parameters x real or complex vector or matrix Description This function computes the standard deviation of the values of a vector or matrix x ignoring the NANs For a vector or a matrix x snanstdevx returns in the scalar s the standard deviation of all the entries of x ignoring the NANs snanstdevxr or equivalently snanstdevx1 is the rowwise standard devi ation It returns in each entry of the row vector s the standard deviation of each column of x ignoring the NANs snanstdevxc or equivalently snanstdevx2 is the columnwise standard devi ation It returns in each entry of the column vector s the standard deviation of each row of x ignoring the NANs In Labostat NAN values stand for missing values in tables Examples x02113249 00002211 06653811 07560439 nan 06283918 03 02 05 snanstdevx snanstdevxr snanstdevxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1890 Name nansum Sum of values ignoring NANs s nansumxorient Parameters x numerical vector or matrix orient nothing or r or 1 c or 2 s Numerical scalar or vector containig the value of the adding operation Description This function returns in s the sum of the values ignoring the NANs of a numerical vector or matrix x For a vector or matrix x snansumx or snansumx returns in scalar s the sum of values of all entries ignoring the NANs of a vector or matrix x snansumxror equivalently snansumx1 returns in each entry of the row vector s of type 1xsizexc the sum of each column of x ignoring the NANs snansumxcor equivalently snansumx2 returns in each entry of the column vector s of type sizexcx1 the sum of each row of x ignoring the NANs For the last two cases if a row or column is in whole composed of NAN the corresponding place of s will contain a NAN Examples x02113249 nan 0665381107560439 03303271 06283918 mnansumx mnansumx1 mnansumx2 See Also nancumsum sum Authors Carlos Klimann Bibliography Wonacott TH and Wonacott RJ Introductory Statistics 5th edition JWiley and Sons 1990 1891 Name nfreq frequence of the values in a vector or matrix mnfreqx Parameters x real or complex vector or matrix Description Frequence of the values in a real or complex vector or a real or complex matrix x For a real or complex vector or a real or complex matrix x mfreqx returns in the first column of the sizexx2 matrix m the values of x and in the second column of this matrix the frequences of the corresponding values Note that the tabul function is more efficient applies also to vector of strings and returns a sorted m Examples x2 8 0 3 7 6 8 7 9 1 mnfreqx See Also tabul dsearch histplot Authors Carlos Klimann 1892 Name pca Computes principal components analysis with standardized variables lambdafacprcomprinc pcax Parameters x is a nxp n individuals p variables real matrix Note that pca center and normalize the columns of x to produce principal components analysis with standardized variables lambda is a p x 2 numerical matrix In the first column we find the eigenvalues of V where V is the correlation p x p matrix and in the second column are the ratios of the corresponding eigenvalue over the sum of eigenvalues facpr are the principal factors eigenvectors of V Each column is an eigenvector element of the dual of Rp comprinc are the principal components Each column ciXui of this n x n matrix is the Morthogonal projection of individuals onto principal axis Each one of this columns is a linear combination of the variables x1 xp with maximum variance under condition ui M1 ui1 Description This function performs several computations known as principal component analysis The idea behind this method is to represent in an approximative manner a cluster of n individuals in a smaller dimensional subspace In order to do that it projects the cluster onto a subspace The choice of the kdimensional projection subspace is made in such a way that the distances in the projection have a minimal deformation we are looking for a kdimensional subspace such that the squares of the distances in the projection is as big as possible in fact in a projection distances can only stretch In other words inertia of the projection onto the k dimensional subspace must be maximal Warning the graphical part of the old version of pca as been removed It can now be performed using the showpca function Examples arand10010n lambdafacprcomprinc pcaa showpcalambdafacpr See Also showpca princomp Authors Carlos Klimann Bibliography Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 1893 Name perctl computation of percentils pperctlxy Parameters x real or complex vector or matrix y vector of positif integer values between 0 and 100 Description Compute the matrix p of percentils in increasing order column first of the real vector or matrix x The percentils are indicated by the entries of y the values of entries of y must be positive integers between 0 and 100 p is a matrix whose type is lengthy x 2 and the content of its first column are the percentils values The contents of its second column are the places of the computed percentiles in the input matrix x The minimum or maximum values in x are assigned to percentiles for percent values outside that range Examples x6 7 0 7 10 4 2 2 7 1 6 0 5 5 5 2 0 6 8 10 8 6 4 3 5 9 8 3 4 7 1 3 2 7 6 1 1 4 8 2 6 3 5 1 6 5 9 9 5 5 1 6 4 4 5 4 0 8 1 8 7 1 3 7 8 0 2 8 10 8 3 6 1 9 8 5 5 3 2 1 5 7 6 2 10 8 7 4 0 8 10 3 3 4 8 6 9 4 8 3 y10 20 30 pperctlxy Authors Carlos Klimann Bibliography HYNDMANRob J and FAN Yanan Sample Quantiles in Statistical Packages The American Statis tician Nov1996 Vol 50 No4 1894 Name princomp Principal components analysis facprcomprinclambdatsquare princompxeco Parameters x is a nbyp n individuals p variables real matrix eco a boolean use to allow economy size singular value decomposition facpr A pbyp matrix It contains the principal factors eigenvectors of the correlation matrix V comprinc a nbyp matrix It contains the principal components Each column of this matrix is the M orthogonal projection of individuals onto principal axis Each one of this columns is a linear combination of the variables x1 xp with maximum variance under condition ui M1 ui1 lambda is a p column vector It contains the eigenvalues of V where V is the correlation matrix tsquare a n column vector It contains the Hotellings T2 statistic for each data point Description This function performs principal component analysis on the nbyp data matrix x The idea behind this method is to represent in an approximative manner a cluster of n individuals in a smaller dimensional subspace In order to do that it projects the cluster onto a subspace The choice of the kdimensional projection subspace is made in such a way that the distances in the projection have a minimal deformation we are looking for a kdimensional subspace such that the squares of the distances in the projection is as big as possible in fact in a projection distances can only stretch In other words inertia of the projection onto the k dimensional subspace must be maximal To compute principal component analysis with standardized variables may use princompwcenterx1 or use the pca function Examples arand10010n facprcomprinclambdatsquare princompa See Also wcenter pca Authors Carlos Klimann princomp 1895 Bibliography Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 1896 Name quart computation of quartiles squartx squartxr or mquartx1 squartxc or mquartx2 Parameters x real or complex vector or matrix Description For a vector or a matrix x qquartxy returns in the vector q the quartiles of x qquartxr or equivalently qquartx1 are the rowwise percentiles It returns in each column of the matrix q the quartiles of data in the corresponding column of x qquartxc or equivalently qquartx2 are the columnwise quartiles It returns in each row of the matrix q the quartiles of data in the corresponding row of x Examples x6 7 0 7 10 4 2 2 7 1 6 0 5 5 5 2 0 6 8 10 8 6 4 3 5 9 8 3 4 7 1 3 2 7 6 1 1 4 8 2 6 3 5 1 6 5 9 9 5 5 1 6 4 4 5 4 0 8 1 8 7 1 3 7 8 0 2 8 10 8 3 6 1 9 8 5 5 3 2 1 5 7 6 2 10 8 7 4 0 8 10 3 3 4 8 6 9 4 8 3 qquartx qquartxr qquartxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1897 Name regress regression coefficients of two variables coefsregressxy Parameters xy real or complex vector Description This function computes the regresion coefficients of two variables x and y both numerical vectors of same number of elements n coefsa b be a 1x2 matrix such that YabX will be the equation of the ordinary least square approximation to our data References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples x05608486 06623569 07263507 01985144 05442573 02320748 02312237 y03616361 02922267 05664249 04826472 03321719 05935095 05015342 coefsregressxy See Also covar Authors Carlos Klimann 1898 Name sample Sampling with replacement s samplenXorient Parameters n positive integer size of sample X matrix Samples will be extracted from this matrix orient Optional parameter Admissible values are 1 2 r or c s vector or matrix containing sample Description This function gives a vector or matrix nx1 It contains a random sample of n extractions with re placement from the matrix X ssamplenX or ssamplenX returns a vector s whose values are a random sample of n values from X extracted with replacement from X ssamplenXr or equivalently ssamplenX1 returns a matrix of type sizeXrxn It contains a random sample of n rows extracted with replacement from the rows of X ssamplenXc or equivalently ssamplenX2 returns a matrix of type nxsizeXc It contains a random sample of n columns extracted with replacement from the columns of X Examples Xa dd arreu ber car zon ssample25X ssample25Xr ssample25Xc See Also samplef samwr Authors Carlos Klimann 1899 Name samplef sample with replacement from a population and frequences of his values s samplefnXforient Parameters n positive integer size of sample X matrix Samples will be extracted from this matrix f positive integer matrix with same type than X It indicates frequences of corresponding values of X orient Optional parameter Admissible values are 1 2 r or c s vector or matrix containing sample Description This function gives s a vector of lenght n It contains a sample of n extractions with replacement from the vector or matrix X each element counted with the frequence given by the corresponding value in vector f ssamplefnXf or ssamplefnXf returns a vector s whose values are a random sample of n values from X each value with a probability to be sampled proportional to the corresponding value of f extracted with replacement from X f must have same lenght than X ssamplefnXfr or equivalently ssamplefnXf1 returns a matrix of type sizeXrxn It con tains a random sample of n rows from X each row with a probability to be sampled proportional to the corresponding value of f extracted with replacement from the rows of X The lenght of f must be equal to the number of rows of X ssamplefnXfc or equivalently ssamplefnXf2 returns a matrix of type nxsizeXc It contains a random sample of n columns from X each column with a probability to be sampled pro portional to the corresponding value of f extracted with replacement from the columns of X The lenght of f must be equal to the number of columns of X Examples a3 7 922 4 2 f110 1 1 1 1 1 f21 15 f310 1 1 ssamplef15af1 ssamplef15af2r ssamplef15af3c See Also sample samwr Authors Carlos Klimann 1901 Name samwr Sampling without replacement s samwrsizamnumsampX Parameters sizam integer Size of a sample It must be less or equal than size of X numsamp integer Number of samples to be extracted X column vector It contains the population s matrix of type sizsam x numsamp It contains numsamp random samples the columns each of sizam sizeX extractions without replacement from the column vector X Description Gives samples without replacement from a column vector Examples a033 124 21 103 ssamwr412a See Also sample samplef Authors Carlos Klimann 1902 Name showpca Visualization of principal components analysis results showpcalambdafacprN Parameters lambda is a p x 2 numerical matrix In the first column we find the eigenvalues of V where V is the correlation p x p matrix and in the second column are the ratios of the corresponding eigenvalue over the sum of eigenvalues facpr are the principal factors eigenvectors of V Each column is an eigenvector element of the dual of Rp N Is a 2x1 integer vector Its coefficients point to the eigenvectors corresponding to the eigenvalues of the correlation matrix p by p ordered by decreasing values of eigenvalues If N is missing we suppose N1 2 Description This function visualize the pca results Examples arand10010n lambdafacprcomprinc pcaa showpcalambdafacpr See Also pca princomp Authors Carlos Klimann Bibliography Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 1903 Name stdeviation standard deviation row or columnwise of vectormatrix entries stdev standard deviation row or columnwise of vectormatrix entries ystdeviationx ystdeviationxr ystdeviationxc ystdevx ystdevxr ystdevxc Parameters x real vector or matrix y scalar or vector Description stdeviation computes the sample standard deviation that is it is normalized by N1 where N is the sequence length For a vector or a matrix x ystdeviationx returns in the scalar y the standard deviation of all the entries of x ystdeviationxr or equivalently ystdeviationx1 is the rowwise stan dard deviation It returns in each entry of the column vector y the standard deviation of each row of x ystdeviationxc or equivalently ystdeviationx2 is the columnwise stdeviation It returns in each entry of the row vector y the standard deviation of each column of x Examples A1210771701 stdeviationA stdeviationAr stdeviationAc See Also sum median mean nanstdev stdevf 1904 Name stdevf standard deviation sstdevfxfre sstdevfxfrer or sstdevfxfre1 sstdevfxfrec or sstdevfxfre2 Parameters x real or complex vector or matrix Description This function computes the standard deviation of the values of a vector or matrix x each of them counted with a frequency given by the corresponding values of the integer vector or matrix fre who has the same type of x For a vector or matrix x sstdevfxfre or sstdevfxfre returns in scalar s the standard deviation of all the entries of x each value counted with the multiplicity indicated by the corresponding value of fre sstdevfxfrer or equivalently sstdevfxfre1 returns in each entry of the row vector s of type 1xsizexc the standard deviation of each column of x each value counted with the multiplicity indicated by the corresponding value of fre sstdevfxfrec or equivalently sstdevfxfre2 returns in each entry of the column vector s of type sizexcx1 the standard deviation of each row of x each value counted with the multiplicity indicated by the corresponding value of fre Examples x02113249 00002211 0665381107560439 09546254 06283918 fre1 2 33 4 3 mstdevfxfre mstdevfxfrer mstdevfxfrec Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1905 Name strange range rstrangex rstrangexr or equivalently rstrangex1 rstrangexc or equivalently rstrangex2 Parameters x real or complex vector or matrix Description The range is the distance between the largest and smaller value rstrangex computes the range of vector or matrix x rstrangexr or equivalently rstrangex1 give a row vector with the range of each column rstrangexc or equivalently rstrangex2 give a column vector with the range of each row References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Authors Carlos klimann 1906 Name tabul frequency of values of a matrix or vector mtabulX order Parameters X vector or matrix of real or complex numbers or strings order optionnal a character equal to d or i default value d m a 2 columns matrix if X is a numerical vector or matrix or a list with 2 members if X is a string vector or matrix Description This function computes the frequency of values of the components of a vector or matrix X of numbers or string characters if X is a numerical vector or matrix then m is a two column matrix who contains in the first column the distinct values of X and in the other column the number of occurrences of those values mi2 is the number of occurrences of mi1 if X is a string vector or matrix then m is a list whose first member is a string column vector composed with the distinct values of X and the second member is a column vector whose components are the number of occurrences of those values mi2 is the number of occurrences of the string mi1 The optional parameter order must be d or i by default orderd and gives the order decreas ing or increasing the distinct values of X will be sorted Examples first example X 2 8 0 3 7 6 8 7 9 1 6 7 7 2 5 2 2 2 9 7 m1 tabulX m2 tabulX i second example X ba baba a A AA a aa aa aa A ba m tabulXi third example n 50000 X grandn1bin7005 m tabulXi clf plot2d3m1 m2n xtitleempirical probabilities of B7005 last example computes the occurrences of words of the scilab license tabul 1907 text readSCIlicensetxt11A read the scilab license bigstr strcattext put all the lines in a big string sep words separators words tokensbigstr sep cut the big string into words m tabulwords computes occurrences of each word occ p gsortm2 sort by decreasing frequencies results m1p stringocc display result See Also dsearch histplot Authors Carlos Klimann original author JS Giet and B Pincon new version Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1908 Name thrownan eliminates nan values nonannumbthrownanx Parameters x real or complex vector or matrix Description This function returns in vector nonan the values ignoring the NANs of a vector or matrix x and in the corresponding places of vector numb the indexes of the value For a vector or matrix x nonannumbthrownanx considers x whatever his dimensions are like a vector columns first In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 nonan numbthrownanx Authors Carlos Klimann 1909 Name trimmean trimmed mean of a vector or a matrix mtrimmeanxdiscard flag verbose Parameters x real or complex vector or matrix discard Optional real value between 0 and 100 representing the part of the data to discard It discard is not in the 0100 range an error is generated Default value for discard50 flag Optional string or real parameter which controls the behaviour when x is a matrix Available values for flag are all 1 2 r or c default is flagall The two values flagr and flag1 are equivalent The two values flagc and flag2 are equivalent verbose Optional integer If set to 1 then enables verbose logging Default is 0 Description A trimmed mean is calculated by discarding a certain percentage of the lowest and the highest scores and then computing the mean of the remaining scores For example a mean trimmed 50 is computed by discarding the lower and higher 25 of the scores and taking the mean of the remaining scores The median is the mean trimmed 100 and the arithmetic mean is the mean trimmed 0 A trimmed mean is obviously less susceptible to the effects of extreme scores than is the arithmetic mean It is therefore less susceptible to sampling fluctuation than the mean for extremely skewed distributions The efficiency of a statistic is the degree to which the statistic is stable from sample to sample That is the less subject to sampling fluctuation a statistic is the more efficient it is The efficiency of statistics is measured relative to the efficiency of other statistics and is therefore often called the relative efficiency If statistic A has a smaller standard error than statistic B then statistic A is more efficient than statistic B The relative efficiency of two statistics may depend on the distribution involved For instance the mean is more efficient than the median for normal distributions but not for some extremely skewed distributions The efficiency of a statistic can also be thought of as the precision of the estimate The more efficient the statistic the more precise the statistic is as an estimator of the parameter The trimmed mean is less efficient than the mean for normal distributions For a vector or matrix x ttrimmeanxdiscard returns in scalar t the mean of all the entries of x after discarding discard2 highest values and discard2 lowest values ttrimmeanxdiscardr or equivalently ttrimmeanxdiscard1 returns in each entry of the row vector t the trimmed mean of each column of x ttrimmeanxdiscardc or equivalently ttrimmeanxdiscard2 returns in each entry of the column vector t the trimmed mean of each row of x This function computes the trimmed mean of a vector or matrix x For a vector or matrix x mtrimmeanxdiscard returns in scalar m the trimmed mean of all the entries of x mtrimmeanxr or equivalently mtrimmeanx1 returns in each entry of the row vector m the trimmed mean of each column of x trimmean 1910 mtrimmeanxc or equivalently mtrimmeanx2 returns in each entry of the column vector m the trimmed mean of each row of x Example with x as vector In the following example one computes the trimmed mean of one data vector with the default discard value equals to 50 and verbose logging The data is made of 9 entries The algorithms sorts the vector and keeps only indices from 3 to 7 skipping indices 1 2 8 and 9 The value 4000 which is much larger than the others is not taken into account The computed trimmed mean is therefore 50 data 10 20 30 40 50 60 70 80 4000 computed trimmeandataverbose1 Example with x as matrix In the following example one computes the trimmed mean of one data matrix The chosen discard value is 50 The orientation is r which means that the data is sorted row by row For each column of the matrix one computes a trimmed mean The trimmed mean is the line vector 25 25 25 25 data 10 10 10 10 20 20 20 20 30 30 30 30 4000 4000 4000 4000 computed trimmeandata50orienr References Luis Angel GarciaEscudero and Alfonso Gordaliza Robustness Properties of Means and Trimmed Means JASA Volume 94 Number 447 Sept 1999 pp956969 Trimmed Mean httpdavidmlanecomhyperstatA11971html Authors Carlos Klimann 1911 Name variance variance of the values of a vector or matrix svariancexorienw svariancexr or mvariancex1 svariancexc or mvariancex2 Parameters x real or complex vector or matrix orien the orientation of the computation Valid values or the orien parameter are 1 r 2 and c w w type of normalization to use Valid values are 0 and 1 This depends on the number of columns of x if orien 1 is chosen the number of rows if orien 2 is chosen If w 0 normalizes with m1 provides the best unbiased estimator of the variance this is the default If w 1 normalizes with m this provides the second moment around the mean If no orien option is given the normalization is done with n m 1 where n m is the total number of elements in the matrix Description This function computes the variance of the values of a vector or matrix x For a vector or a matrix x svariancex returns in the scalar s the variance of all the entries of x svariancexr or equivalently svariancex1 is the rowwise variance It returns in each entry of the row vector s the variance of each column of x The generalized formulae is used which manages complex values svariancexc or equivalently svariancex2 is the columnwise standard devi ation It returns in each entry of the column vector s the variance of each row of x The generalized formulae is used which manages complex values Examples x02113249 00002211 0665381107560439 04453586 06283918 svariancex svariancexr svariancexc See Also mtlbvar Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1912 Name variancef standard deviation of the values of a vector or matrix svariancefxfre svariancefxfrer or svariancefxfre1 svariancefxfrec or svariancefxfre2 Parameters x real or complex vector or matrix Description This function computes the variance of the values of a vector or matrix x each of them counted with a frequency signaled by the corresponding values of the integer vector or matrix fre with the same type of x For a vector or matrix x svariancefxfre or svariancefxfre returns in scalar s the variance of all the entries of x each value counted with the multiplicity indicated by the corresponding value of fre svariancefxfreror equivalently svariancefxfre1 returns in each en try of the row vector s of type 1xsizexc the variance of each column of x each value counted with the multiplicity indicated by the corresponding value of fre svariancefxfrecor equivalently svariancefxfre2 returns in each en try of the column vector s of type sizexc x1 the variance of each row of x each value counted with the multiplicity indicated by the corresponding value of fre Examples x02113249 00002211 0665381107560439 09546254 06283918 fre1 2 33 4 3 mvariancefxfre mvariancefxfrer mvariancefxfrec Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 Parte XXXV ARnoldi PACKage 1914 Name dnaupd Interface for the Implicitly Restarted Arnoldi Iteration to compute approximations to a few eigenpairs of a real linear operator IDORESIDVIPARAMIPNTRWORKDWORKLINFO dnaupdID0BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLINFO Parameters ID0 Integer INPUTOUTPUT Reverse communication flag IDO must be zero on the first call to dnaupd IDO will be set internally to indicate the type of operation to be performed Control is then given back to the calling routine which has the responsibility to carry out the requested operation and call dnaupd with the result The operand is given in WORKDIPNTR1 the result must be put in WORKDIPNTR2 IDO 0 first call to the reverse communication interface IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y This is for the initialization phase to force the starting vector into the range of OP IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y In mode 3 and 4 the vector B X is already available in WORKDipntr3 It does not need to be recomputed in forming OP X IDO 2 compute Y B X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y IDO 3 compute the IPARAM8 real and imaginary parts of the shifts where INPTR14 is the pointer into WORKL for placing the shifts See Remark 5 below IDO 99 done BMAT Character specifies the type of the matrix B that defines the semiinner product for the operator OP I standard eigenvalue problem Ax lambdax G generalized eigenvalue problem Ax lambdaBx N Integer dimension of the eigenproblem WHICH string of length 2 Specify which of the Ritz values of OP to compute LM want the NEV eigenvalues of largest magnitude SM want the NEV eigenvalues of smallest magnitude LR want the NEV eigenvalues of largest real part SR want the NEV eigenvalues of smallest real part LI want the NEV eigenvalues of largest imaginary part SI want the NEV eigenvalues of smallest imaginary part NEV Integer number of eigenvalues of OP to be computed 0 NEV N1 dnaupd 1915 TOL scalar Stopping criterion the relative accuracy of the Ritz value is considered acceptable if BOUNDSI TOLABSRITZI If TOL 0 is passed the machine precision is set RESID array of length N INPUTOUTPUT On INPUT If INFO0 a random initial residual vector is used else RESID contains the initial residual vector possibly from a previous run On OUTPUT RESID contains the final residual vector NCV Integer number of columns of the matrix V NCV must satisfy the two inequalities 2 NCV NEV and NCV N This will indicate how many Arnoldi vectors are generated at each iteration After the startup phase in which NEV Arnoldi vectors are generated the algorithm generates approximately NCVNEV Arnoldi vectors at each subsequent update iteration Most of the cost in generating each Arnoldi vector is in the matrixvector operation OPx NOTE 2 NCVNEV in order that complex conjugate pairs of Ritz values are kept together See remark 4 below V N by NCV array Contains the final set of Arnoldi basis vectors IPARAM array of length 11 INPUTOUTPUT IPARAM1 ISHIFT method for selecting the implicit shifts The shifts selected at each iteration are used to restart the Arnoldi iteration in an implicit fashion ISHIFT 0 the shifts are provided by the user via reverse communication The real and imaginary parts of the NCV eigenvalues of the Hessenberg matrix H are returned in the part of the WORKL array corresponding to RITZR and RITZI See remark 5 below ISHIFT 1 exact shifts with respect to the current Hessenberg matrix H This is equivalent to restarting the iteration with a starting vector that is a linear combination of approximate Schur vectors associated with the wanted Ritz values IPARAM2 LEVEC No longer referenced IPARAM3 MXITER On INPUT maximum number of Arnoldi update iterations allowed On OUTPUT actual number of Arnoldi update iterations taken IPARAM4 NB blocksize to be used in the recurrence The code currently works only for NB 1 IPARAM5 NCONV number of converged Ritz values This represents the number of Ritz values that satisfy the convergence criterion IPARAM6 IUPD No longer referenced Implicit restarting is ALWAYS used IPARAM7 MODE On INPUT determines what type of eigenproblem is being solved Must be 1234 See under Description of dnaupd for the five modes available IPARAM8 NP When ido 3 and the user provides shifts through reverse communication IPARAM10 dnaupd returns NP the number of shifts the user is to provide dnaupd 1916 0 NP NCVNEV See Remark 5 below IPARAM9 NUMOP IPARAM10 NUMOPB IPARAM11 NUMREO On OUTPUT NUMOP total number of OPx operations NUMOPB total number of Bx operations if BMATG NUMREO total number of steps of reorthogonalization IPNTR array of length 14 Pointer to mark the starting locations in the WORKD and WORKL arrays for matricesvectors used by the Arnoldi iteration IPNTR1 pointer to the current operand vector X in WORKD IPNTR2 pointer to the current result vector Y in WORKD IPNTR3 pointer to the vector B X in WORKD when used in the shiftandinvert mode IPNTR4 pointer to the next available location in WORKL that is untouched by the program IPNTR5 pointer to the NCV by NCV upper Hessenberg matrix H in WORKL IPNTR6 pointer to the real part of the ritz value array RITZR in WORKL IPNTR7 pointer to the imaginary part of the ritz value array RITZI in WORKL IPNTR8 pointer to the Ritz estimates in array WORKL associated with the Ritz values lo cated in RITZR and RITZI in WORKL IPNTR14 pointer to the NP shifts in WORKL See Remark 5 below Note IPNTR913 is only referenced by dneupd See Remark 2 IPNTR9 pointer to the real part of the NCV RITZ values of the original system IPNTR10 pointer to the imaginary part of the NCV RITZ values of the original system IPNTR11 pointer to the NCV corresponding error bounds IPNTR12pointer to the NCV by NCV upper quasitriangular Schur matrix for H IPNTR13 pointer to the NCV by NCV matrix of eigenvectors of the upper Hessenberg matrix H Only referenced by dneupd if RVEC 1 See Remark 2 below WORKD Double precision work array of length 3N REVERSE COMMUNICATION Distributed array to be used in the basic Arnoldi iteration for reverse communication The us er should not use WORKD as temporary workspace during the iteration Upon termination WORKD1N contains BRESID1N If an invariant subspace associated with the converged Ritz values is desired see remark 2 below subroutine dneupd uses this output See Data Distri bution Note below WORKL work array of length at least 3NCV2 6NCV OUTPUTWORKSPACE Private replicat ed array on each PE or array allocated on the front end See Data Distribution Note below INFO Integer INPUTOUTPUT If INFO 0 a randomly initial residual vector is used else RESID contains the initial residual vector possibly from a previous run dnaupd 1917 Error flag on output 0 Normal exit 1 Maximum number of iterations taken All possible eigenvalues of OP has been found IPARAM5 returns the number of wanted converged Ritz values 2 No longer an informational error Deprecated starting with release 2 of ARPACK 3 No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration One possibility is to increase the size of NCV relative to NEV See remark 4 below 1 N must be positive 2 NEV must be positive 3 NCVNEV 2 and less than or equal to N 4 The maximum number of Arnoldi update iterations allowed must be greater than zero 5 WHICH must be one of LM SM LR SR LI SI 6 BMAT must be one of I or G 7 Length of private work array WORKL is not sufficient 8 Error return from LAPACK eigenvalue calculation 9 Starting vector is zero 10 IPARAM7 must be 1234 11 IPARAM7 1 and BMAT G are incompatable 12 IPARAM1 must be equal to 0 or 1 9999 Could not build an Arnoldi factorization IPARAM5 returns the size of the current Arnoldi factorization The user is advised to check that enough workspace and array storage has been allocated Description Reverse communication interface for the Implicitly Restarted Arnoldi iteration This subroutine com putes approximations to a few eigenpairs of a linear operator OP with respect to a semiinner product defined by a symmetric positive semidefinite real matrix B B may be the identity matrix NOTE If the linear operator OP is real and symmetric with respect to the real positive semidefinite symmetric matrix B ie BOP OPB then subroutine dsaupd should be used instead The computed approximate eigenvalues are called Ritz values and the corresponding approximate eigenvectors are called Ritz vectors dnaupd is usually called iteratively to solve one of the following problems Mode 1 Ax lambdax OP A B I Mode 2 Ax lambdaMx M symmetric positive definite OP invMA B M If M can be factored see remark 3 below Mode 3 Ax lambdaMx M symmetric positive semidefinite OP RealPart invA sigmaMM B M shiftandinvert mode in real arithmetic If OPx amux then amu 12 1lambdasigma 1lambdaconjgsigma dnaupd 1918 Note If sigma is real ie imaginary part of sigma is zero RealPart invA sigmaMM invA sigmaMM amu 1lambdasigma Mode 4 Ax lambdaMx M symmetric semidefinite OP ImaginaryPart invA sigmaMM B M shiftandinvert mode in real arithmetic If OPx amux then amu 12i 1lambdasigma 1lamb daconjgsigma Both mode 3 and 4 give the same enhancement to eigenvalues close to the complex shift sigma However as lambda goes to infinity the operator OP in mode 4 dampens the eigenvalues more strong ly than does OP defined in mode 3 NOTE The action of w invA sigmaMv or w invMv should be accomplished either by a direct method using a sparse matrix factorization and solving A sigmaMw v or Mw v or through an iterative method for solving these systems If an iterative method is used the convergence test must be more stringent than the accuracy requirements for the eigenvalue approximations Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 v zerosnxncv workd zeros3nx11 workev zeros3ncv1 workl zeros3ncvncv6ncv1 Build the test matrix A diag10onesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts dnaupd 1919 iparam3 maxitr iparam7 mode1 sigmar 0 the real part of the shift sigmai 0 the imaginary part of the shift M A I N L O O P Reverse communication iter 0 whileitermaxiter infodnaupd 0 iter iter 1 Repeatedly call the routine DNAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfodnaupd dnaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklinfodnaupd if ido99 then BE CAREFUL DONT CALL dneupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call DNAUPD again continue end if infodnaupd 0 then printf Error with dnaupd info d infodnaupd printfCheck the documentation of dnaupd else PostProcess using DNEUPD rvec 1 howmany A infodneupd 0 dd12vresidviparamipntrworkdworklinfodneupd dneupdrvechowmanyselectdd12vsigmarsigmaiworkev bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfodneupd if infodneupd0 then printf Error with dneupd info d infodneupd printfCheck the documentation of dneupd end Print additional convergence information if infodneupd1 then printf Maximum number of iterations reached elseif infodneupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end dnaupd 1920 printf DNSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol Remarks 1 The computed Ritz values are approximate eigenvalues of OP The selection of WHICH should be made with this in mind when Mode 3 and 4 After convergence approximate eigenvalues of the original problem may be obtained with the ARPACK subroutine dneupd 2 If a basis for the invariant subspace corresponding to the converged Ritz values is needed the user must call dneupd immediately following completion of dnaupd This is new starting with release 2 of ARPACK 3 If M can be factored into a Cholesky factorization M LL then Mode 2 should not be selected Instead one should use Mode 1 with OP invLAinvL Appropriate triangular linear systems should be solved with L and L rather than computing inverses After convergence an approximate eigenvector z of the original problem is recovered by solving Lz x where x is a Ritz vector of OP 4 At present there is no apriori analysis to guide the selection of NCV relative to NEV The only formal requrement is that NCV NEV 2 However it is recommended that NCV 2NEV1 If many problems of the same type are to be solved one should experiment with increasing NCV while keeping NEV fixed for a given test problem This will usually decrease the required number of OPx operations but it also increases the work and storage required to maintain the orthogonal basis vectors The optimal crossover with respect to CPU time is problem dependent and must be determined empirically See Chapter 8 of Reference 2 for further information 5 When IPARAM1 0 and IDO 3 the user needs to provide the NP IPARAM8 real and imaginary parts of the shifts in locations real part imaginary part 1 WORKLIPNTR14 WORKLIPNTR14NP 2 WORKLIPNTR141 WORKLIPNTR14NP1 NP WORKLIPNTR14NP1 WORKLIPNTR142NP1 Only complex conjugate pairs of shifts may be applied and the pairs must be placed in con secutive locations The real part of the eigenvalues of the current upper Hessenberg matrix are located in WORKLIPNTR6 through WORKLIPNTR6NCV1 and the imaginary part in WORKLIPNTR7 through WORKLIPNTR7NCV1 They are ordered according to the order defined by WHICH The complex conjugate pairs are kept together and the associated Ritz estimates are located in WORKLIPNTR8 WORKLIPNTR81 WORKLIPNTR8NCV1 dnaupd 1921 See Also dsaupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett The Symmetric Eigenvalue Problem PrenticeHall 1980 4 BN Parlett B NourOmid Towards a Black Box Lanczos Program Computer Physics Com munications 53 1989 pp 169179 5 B NourOmid BN Parlett T Ericson PS Jensen How to Implement the Spectral Transforma tion Math Comp 48 1987 pp 663673 6 RG Grimes JG Lewis and HD Simon A Shifted Block Lanczos Algorithm for Solving Sparse Symmetric Generalized Eigenproblems SIAM J Matr Anal Apps January 1993 7 L Reichel WB Gragg Algorithm 686 FORTRAN Subroutines for Updating the QR decompo sition ACM TOMS December 1990 Volume 16 Number 4 pp 369377 8 RB Lehoucq DC Sorensen Implementation of Some Spectral Transformations in a kStep Arnoldi Method In Preparation Used Functions Based on ARPACK routine dnaupd 1922 Name dneupd Interface for the Implicitly Restarted Arnoldi Iteration to compute the converged approx imations to eigenvalues of Az lambdaBz approximations to a few eigenpairs of a real linear operator DrDiZRESIDVIPARAMIPNTRWORKDWORKLINFO dneupdRVECHOWMANYSELECTDrDiZSIGMArSIGMAiWORKev BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLINFO Parameters RVEC Integer INPUT Specifies whether a basis for the invariant subspace corresponding to the converged Ritz value approximations for the eigenproblem Az lambdaBz is computed RVEC 0 Compute Ritz values only RVEC 1 Compute the Ritz vectors or Schur vectors See Remarks below HOWMANY Character INPUT Specifies the form of the basis for the invariant subspace corresponding to the converged Ritz values that is to be computed A Compute NEV Ritz vectors P Compute NEV Schur vectors S compute some of the Ritz vectors specified by the integer array SELECT SELECT Integer array of dimension NCV INPUT If HOWMANY S SELECT specifies the Ritz vectors to be computed To select the Ritz vector corresponding to a Ritz value DRj DIj SELECTj must be set to 1 If HOWMANY A or P SELECT is used as internal workspace DR Double precision array of dimension NEV1 OUTPUT If IPARAM7 12 or 3 and SIGMAI00 then on exit DR contains the real part of the Ritz approximations to the eigenvalues of Az lambdaBz If IPARAM7 3 4 and SIGMAI is not equal to zero then on exit DR contains the real part of the Ritz values of OP computed by DNAUPD A further computation must be performed by the user to transform the Ritz values computed for OP by DNAUPD to those of the original system Az lambdaBz See remark 3 below DI Double precision array of dimension NEV1 OUTPUT On exit DI contains the imaginary part of the Ritz value approximations to the eigenvalues of Az lambdaBz associated with DR NOTE When Ritz values are complex they will come in complex conjugate pairs If eigenvectors are requested the corresponding Ritz vectors will also come in conjugate pairs and the real and imaginary parts of these are represented in two consecutive columns of the array Z see below dneupd 1923 Z Double precision N by NEV1 array if RVEC 1 and HOWMANY A OUTPUT On exit if RVEC 1 and HOWMANY A then the columns of Z represent approximate eigen vectors Ritz vectors corresponding to the NCONVIPARAM5 Ritz values for eigensystem Az lambdaBz The complex Ritz vector associated with the Ritz value with positive imag inary part is stored in two consecutive columns The first column holds the real part of the Ritz vector and the second column holds the imaginary part The Ritz vector associated with the Ritz value with negative imaginary part is simply the complex conjugate of the Ritz vector associated with the positive imaginary part If RVEC 0 or HOWMANY P then Z is not referenced NOTE If if RVEC 1 and a Schur basis is not required the array Z may be set equal to first NEV1 columns of the Arnoldi basis array V computed by DNAUPD In this case the Arnoldi basis will be destroyed and overwritten with the eigenvector basis SIGMAR Double precision INPUT If IPARAM7 3 or 4 represents the real part of the shift Not referenced if IPARAM7 1 or 2 SIGMAI Double precision INPUT If IPARAM7 3 or 4 represents the imaginary part of the shift Not referenced if IPARAM7 1 or 2 See remark 3 below WORKEV Double precision work array of dimension 3NCV WORKSPACE NOTE The remaining arguments BMAT N WHICH NEV TOL RESID NCV V IPARAM IP NTR WORKD WORKL LWORKL INFO must be passed directly to DNEUPD following the last call to DNAUPD These arguments MUST NOT BE MODIFIED between the the last call to DNAUPD and the call to DNEUPD Three of these parameters V WORKL INFO are also output parameters V Double precision N by NCV array INPUTOUTPUT Upon INPUT the NCV columns of V contain the Arnoldi basis vectors for OP as constructed by DNAUPD Upon OUTPUT If RVEC 1 the first NCONVIPARAM5 columns contain approximate Schur vectors that span the desired invariant subspace See Remark 2 below NOTE If the array Z has been set equal to first NEV1 columns of the array V and RVEC1 and HOWMANY A then the Arnoldi basis held by V has been overwritten by the desired Ritz vectors If a separate array Z has been passed then the first NCONVIPARAM5 columns of V will contain approximate Schur vectors that span the desired invariant subspace WORKL Double precision work array of length LWORKL OUTPUTWORKSPACE dneupd 1924 WORKL1ncvncv3ncv contains information obtained in dnaupd They are not changed by dneupd WORKLncvncv3ncv13ncvncv6ncv holds the real and imaginary part of the untrans formed Ritz values the upper quasitriangular matrix for H and the associated matrix represen tation of the invariant subspace for H Note IPNTR913 contains the pointer into WORKL for addresses of the above information computed by dneupd IPNTR9 pointer to the real part of the NCV RITZ values of the original system IPNTR10 pointer to the imaginary part of the NCV RITZ values of the original system IPNTR11 pointer to the NCV corresponding error bounds IPNTR12 pointer to the NCV by NCV upper quasitriangular Schur matrix for H IPNTR13 pointer to the NCV by NCV matrix of eigenvectors of the upper Hessenberg matrix H Only referenced by dneupd if RVEC 1 See Remark 2 below INFO Error flag on output 0 Normal exit 1 The Schur form computed by LAPACK routine dlahqr could not be reordered by LAPACK routine dtrsen Reenter subroutine dneupd with IPARAM5NCV and increase the size of the arrays DR and DI to have dimension at least dimension NCV and allocate at least NCV columns for Z NOTE Not necessary if Z and V share the same space Please notify the authors if this error occurs 1 N must be positive 2 NEV must be positive 3 NCVNEV 2 and less than or equal to N 5 WHICH must be one of LM SM LR SR LI SI 6 BMAT must be one of I or G 7 Length of private work WORKL array is not sufficient 8 Error return from calculation of a real Schur form Informational error from LAPACK rou tine dlahqr 9 Error return from calculation of eigenvectors Informational error from LAPACK routine dtrevc 10 IPARAM7 must be 1234 11 IPARAM7 1 and BMAT G are incompatible 12 HOWMANY S not yet implemented 13 HOWMANY must be one of A or P if RVEC 1 14 DNAUPD did not find any eigenvalues to sufficient accuracy 15 DNEUPD got a different count of the number of converged Ritz values than DNAUPD got This indicates the user probably made an error in passing data from DNAUPD to DNEUPD or that the data was modified before entering DNEUPD dneupd 1925 Description This subroutine returns the converged approximations to eigenvalues of Az lambdaBz and op tionally 1 The corresponding approximate eigenvectors 2 An orthonormal basis for the associated approximate invariant subspace 3 Both There is negligible additional cost to obtain eigenvectors An orthonormal basis is always computed There is an additional storage cost of nnev if both are requested in this case a separate array Z must be supplied The approximate eigenvalues and eigenvectors of Az lambdaBz are derived from approximate eigenvalues and eigenvectors of of the linear operator OP prescribed by the MODE selection in the call to DNAUPD DNAUPD must be called before this routine is called These approximate eigenvalues and vectors are commonly called Ritz values and Ritz vectors respec tively They are referred to as such in the comments that follow The computed orthonormal basis for the invariant subspace corresponding to these Ritz values is re ferred to as a Schur basis See documentation in the header of the subroutine DNAUPD for definition of OP as well as other terms and the relation of computed Ritz values and Ritz vectors of OP with respect to the given problem Az lambdaBz For a brief description see definitions of IPARAM7 MODE and WHICH in the documentation of DNAUPD Remarks 1 Currently only HOWMNY A and P are implemented Let transX denote the transpose of X 2 Schur vectors are an orthogonal representation for the basis of Ritz vectors Thus their numerical properties are often superior If RVEC 1 then the relationship A V1IPARAM5 V1IPARAM5 T and transV1IPARAM5 V1IPARAM5 I are approximately satisfied Here T is the leading submatrix of order IPARAM5 of the real upper quasitriangular matrix stored worklipntr12 That is T is block upper triangular with 1by1 and 2by2 diagonal blocks each 2by2 diagonal block has its diagonal elements equal and its offdiagonal elements of opposite sign Corresponding to each 2by2 diagonal block is a complex conjugate pair of Ritz values The real Ritz values are stored on the diagonal of T 3 If IPARAM7 3 or 4 and SIGMAI is not equal zero then the user must form the IPARAM5 Rayleigh quotients in order to transform the Ritz values computed by DNAUPD for OP to those of Az lambdaBz Set RVEC 1 and HOWMNY A and compute transZI A ZI if DII 0 If DII is not equal to zero and DII1 DI then the desired real and imaginary parts of the Ritz value are dneupd 1926 transZI A ZI transZI1 A ZI1 transZI A ZI1 transZI1 A ZI respectively Another possibility is to set RVEC 1 and HOWMANY P and compute transV1IPARAM5 A V1IPARAM5 and then an upper quasitriangular matrix of order IPARAM5 is computed See remark 2 above Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 v zerosnxncv workd zeros3nx11 workev zeros3ncv1 workl zeros3ncvncv6ncv1 Build the test matrix A diag10onesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts iparam3 maxitr iparam7 mode1 sigmar 0 the real part of the shift sigmai 0 the imaginary part of the shift dneupd 1927 M A I N L O O P Reverse communication iter 0 whileitermaxiter infodnaupd 0 iter iter 1 Repeatedly call the routine DNAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfodnaupd dnaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklinfodnaupd if ido99 then BE CAREFUL DONT CALL dneupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call DNAUPD again continue end if infodnaupd 0 then printf Error with dnaupd info d infodnaupd printfCheck the documentation of dnaupd else PostProcess using DNEUPD rvec 1 howmany A infodneupd 0 dd12vresidviparamipntrworkdworklinfodneupd dneupdrvechowmanyselectdd12vsigmarsigmaiworkev bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfodneupd if infodneupd0 then printf Error with dneupd info d infodneupd printfCheck the documentation of dneupd end Print additional convergence information if infodneupd1 then printf Maximum number of iterations reached elseif infodneupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end printf DNSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx dneupd 1928 printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also dsaupd dnaupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett The Symmetric Eigenvalue Problem PrenticeHall 1980 4 BN Parlett B NourOmid Towards a Black Box Lanczos Program Computer Physics Com munications 53 1989 pp 169179 5 B NourOmid BN Parlett T Ericson PS Jensen How to Implement the Spectral Transforma tion Math Comp 48 1987 pp 663673 6 RG Grimes JG Lewis and HD Simon A Shifted Block Lanczos Algorithm for Solving Sparse Symmetric Generalized Eigenproblems SIAM J Matr Anal Apps January 1993 7 L Reichel WB Gragg Algorithm 686 FORTRAN Subroutines for Updating the QR decompo sition ACM TOMS December 1990 Volume 16 Number 4 pp 369377 8 RB Lehoucq DC Sorensen Implementation of Some Spectral Transformations in a kStep Arnoldi Method In Preparation Used Functions Based on ARPACK routine dneupd 1929 Name dsaupd Interface for the Implicitly Restarted Arnoldi Iteration to compute approximations to a few eigenpairs of a real and symmetric linear operator IDORESIDVIPARAMIPNTRWORKDWORKLINFO dsaupdID0BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLINFO Parameters ID0 Integer INPUTOUTPUT Reverse communication flag IDO must be zero on the first call to dsaupd IDO will be set internally to indicate the type of operation to be performed Control is then given back to the calling routine which has the responsibility to carry out the requested operation and call dsaupd with the result T he operand is given in WORKDIPNTR1 the result must be put in WORKDIPNTR2 If Mode 2 see remark 5 below IDO 0 first call to the reverse communication interface IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y This is for the initialization phase to force the starting vector into the range of OP IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y In mode 34 and 5 the vector B X is already available in WORKDipntr3 It does not need to be recomputed in forming OP X IDO 2 compute Y B X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y IDO 3 compute the IPARAM8 shifts where IPNTR11 is the pointer into WORKL for placing the shifts See remark 6 below IDO 99 done BMAT Character INPUT Specifies the type of the matrix B that defines the semiinner product for the operator OP I standard eigenvalue problem Ax lambdax G generalized eigenvalue problem Ax lambdaBx N Integer Dimension of the eigenproblem WHICH String of length 2 Specify which of the Ritz values of OP to compute LA compute the NEV largest algebraic eigenvalues SA compute the NEV smallest algebraic eigenvalues dsaupd 1930 LM compute the NEV largest in magnitude eigenvalues SM compute the NEV smallest in magnitude eigenvalues BE compute NEV eigenvalues half from each end of the spectrum When NEV is odd compute one more from the high end than from the low end see remark 1 below NEV Integer Number of eigenvalues of OP to be computed 0 NEV N TOL scalar Stopping criterion the relative accuracy of the Ritz value is considered acceptable if BOUNDSI TOLABSRITZI If TOL 0 is passed the machine precision is set RESID Array of length N INPUTOUTPUT On INPUT If INFO0 a random initial residual vector is used else RESID contains the initial residual vector possibly from a previous run On OUTPUT RESID contains the final residual vector NCV Integer Number of columns of the matrix V less than or equal to N This will indicate how many Lanczos vectors are generated at each iteration After the startup phase in which NEV Lanczos vectors are generated the algorithm generates NCVNEV Lanczos vectors at each subsequent update iteration Most of the cost in generating each Lanczos vector is in the matrixvector product OPx See remark 4 below V N by NCV array The NCV columns of V contain the Lanczos basis vectors IPARAM array of length 11 INPUTOUTPUT IPARAM1 ISHIFT method for selecting the implicit shifts The shifts selected at each iteration are used to restart the Arnoldi iteration in an implicit fashion ISHIFT 0 the shifts are provided by the user via reverse communication The NCV eigen values of the current tridiagonal matrix T are returned in the part of WORKL array corre sponding to RITZ See remark 6 below ISHIFT 1 exact shifts with respect to the reduced tridiagonal matrix T This is equivalent to restarting the iteration with a starting vector that is a linear combination of Ritz vectors associated with the wanted Ritz values IPARAM2 LEVEC No longer referenced See remark 2 below IPARAM3 MXITER On INPUT maximum number of Arnoldi update iterations allowed On OUTPUT actual number of Arnoldi update iterations taken dsaupd 1931 IPARAM4 NB blocksize to be used in the recurrence The code currently works only for NB 1 IPARAM5 NCONV number of converged Ritz values This represents the number of Ritz values that satisfy the convergence criterion IPARAM6 IUPD No longer referenced Implicit restarting is ALWAYS used IPARAM7 MODE On INPUT determines what type of eigenproblem is being solved Must be 12345 See under Description of dsaupd for the five modes available IPARAM8 NP When ido 3 and the user provides shifts through reverse communication IPARAM10 dsaupd returns NP the number of shifts the user is to provide 0 NP NCVNEV See Remark 6 below IPARAM9 NUMOP IPARAM10 NUMOPB IPARAM11 NUMREO OUTPUT NUMOP total number of OPx operations NU MOPB total number of Bx operations if BMATG NUMREO total number of steps of reorthogonalization IPNTR array of length 11 Pointer to mark the starting locations in the WORKD and WORKL arrays for matricesvectors used by the Lanczos iteration IPNTR1 pointer to the current operand vector X in WORKD IPNTR2 pointer to the current result vector Y in WORKD IPNTR3 pointer to the vector B X in WORKD when used in the shiftandinvert mode IPNTR4 pointer to the next available location in WORKL that is untouched by the program IPNTR5 pointer to the NCV by 2 tridiagonal matrix T in WORKL IPNTR6 pointer to the NCV RITZ values array in WORKL IPNTR7 pointer to the Ritz estimates in array WORKL associated with the Ritz values lo cated in RITZ in WORKL IPNTR11 pointer to the NP shifts in WORKL See Remark 6 below Note IPNTR810 is only referenced by dseupd See Remark 2 IPNTR8 pointer to the NCV RITZ values of the original system IPNTR9 pointer to the NCV corresponding error bounds IPNTR10 pointer to the NCV by NCV matrix of eigenvectors of the tridiagonal matrix T Only referenced by dseupd if RVEC 1 See Remarks WORKD work array of length 3N REVERSE COMMUNICATION Distributed array to be used in the basic Arnoldi iteration for reverse communication The us er should not use WORKD as temporary workspace during the iteration Upon termination WORKD1N contains BRESID1N If the Ritz vectors are desired subroutine dseupd uses this output See Data Distribution Note below WORKL work array of length at least NCV2 8NCV OUTPUTWORKSPACE dsaupd 1932 Private replicated array on each PE or array allocated on the front end See Data Distribution Note below add here the parameter description INFO Integer INPUTOUTPUT If INFO 0 a randomly initial residual vector is used else RESID contains the initial residual vector possibly from a previous run Error flag on output 0 Normal exit 1 Maximum number of iterations taken All possible eigenvalues of OP has been found IPARAM5 returns the number of wanted converged Ritz values 2 No longer an informational error Deprecated starting with release 2 of ARPACK 3 No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration One possibility is to increase the size of NCV relative to NEV See remark 4 below 1 N must be positive 2 NEV must be positive 3 NCV must be greater than NEV and less than or equal to N 4 The maximum number of Arnoldi update iterations allowed must be greater than zero 5 WHICH must be one of LM SM LA SA or BE 6 BMAT must be one of I or G 7 Length of private work array WORKL is not sufficient 8 Error return from trid eigenvalue calculation Informatinal error from LAPACK routine dsteqr 9 Starting vector is zero 10 IPARAM7 must be 12345 11 IPARAM7 1 and BMAT G are incompatable 12 IPARAM1 must be equal to 0 or 1 13 NEV and WHICH BE are incompatable 9999 Could not build an Arnoldi factorization IPARAM5 returns the size of the current Arnoldi factorization The user is advised to check that enough workspace and array storage has been allocated Description Reverse communication interface for the Implicitly Restarted Arnoldi Iteration For symmetric prob lems this reduces to a variant of the Lanczos method This method has been designed to compute approximations to a few eigenpairs of a linear operator OP that is real and symmetric with respect to a real positive semidefinite symmetric matrix B ieBOP OPB Another way to express this condition is xOPy OPxy where zw zBw dsaupd 1933 In the standard eigenproblem B is the identity matrix A denotes transpose of A The computed approximate eigenvalues are called Ritz values and the corresponding approximate eigenvectors are called Ritz vectors dsaupd is usually called iteratively to solve one of the following problems Mode 1 Ax lambdax A symmetric OP A and B I Mode 2 Ax lambdaMx A symmetric M symmetric positive definite OP invMA and B M If M can be factored see remark 3 below Mode 3 Kx lambdaMx K symmetric M symmetric positive semidefinite OP invK sigmaMM and B M ShiftandInvert mode Mode 4 Kx lambdaKGx K symmetric positive semidefinite KG symmetric indefinite OP invK sigmaKGK and B K Buckling mode Mode 5 Ax lambdaMx A symmetric M symmetric positive semidefinite OP invA sigmaMA sigmaM and B M Cayley transformed mode NOTE The action of w invA sigmaMv or w invMv should be accomplished either by a direct method using a sparse matrix factorization and solving A sigmaMw v or Mw v or through an iterative method for solving these systems If an iterative method is used the convergence test must be more stringent than the accuracy requirements for the eigenvalue approximations Remarks 1 The converged Ritz values are always returned in ascending algebraic order The computed Ritz values are approximate eigenvalues of OP The selection of WHICH should be made with this in mind when Mode 345 After convergence approximate eigenvalues of the original problem may be obtained with the ARPACK subroutine dseupd 2 If the Ritz vectors corresponding to the converged Ritz values are needed the user must call dseupd immediately following completion of dsaupd This is new starting with version 21 of ARPACK 3 If M can be factored into a Cholesky factorization M LL then Mode 2 should not be selected Instead one should use Mode 1 with OP invLAinvL Appropriate triangular linear systems should be solved with L and L rather than computing inverses After convergence an approximate eigenvector z of the original problem is recovered by solving Lz x where x is a Ritz vector of OP 4 At present there is no apriori analysis to guide the selection of NCV relative to NEV The only formal requrement is that NCV NEV However it is recommended that NCV 2NEV If many problems of the same type are to be solved one should experiment with increasing NCV while keeping NEV fixed for a given test problem This will usually decrease the required number of OPx operations but it also increases the work and storage required to maintain the orthogonal basis vectors The optimal crossover with respect to CPU time is problem dependent and must be determined empirically 5 If IPARAM7 2 then in the Reverse commuication interface the user must do the following When IDO 1 Y OP X is to be computed When IPARAM7 2 OP invBA After computing AX the user must overwrite X with AX Y is then the solution to the linear set of equations BY AX 6 When IPARAM1 0 and IDO 3 the user needs to provide the NP IPARAM8 shifts in locations 1 WORKLIPNTR11 2 WORKLIPNTR111 NP WORKLIPNTR11NP1 The eigenvalues of the current tridiagonal matrix are located in WORKLIPNTR6 through WORKLIPNTR6NCV1 They are in the order defined by WHICH The associated Ritz estimates are located in WORKLIPNTR8 WORKLIPNTR81 WORKLIPNTR8NCV1 dsaupd 1934 Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 v zerosnxncv workd zeros3nx11 workl zerosncvncv8ncv1 Build the symmetric test matrix A diag10onesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts iparam3 maxitr iparam7 mode1 sigma 0 the real part of the shift M A I N L O O P Reverse communication iter 0 whileitermaxiter infodsaupd 0 iter iter 1 Repeatedly call the routine DSAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfodsaupd dsaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklinfodsaupd if ido99 then dsaupd 1935 BE CAREFUL DONT CALL dseupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call DSAUPD again continue end if infodsaupd 0 then printf Error with dsaupd info d infodsaupd printfCheck the documentation of dsaupd else PostProcess using DSEUPD rvec 1 howmany A infodseupd 0 dd12vresidviparamipntrworkdworklinfodseupd dseupdrvechowmanyselectdd12vsigma bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfodseupd if infodseupd0 then printf Error with dseupd info d infodseupd printfCheck the documentation of dseupd end if infodseupd1 then printf Maximum number of iterations reached elseif infodseupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end Done with program dssimp printf DSSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also dnaupd dsaupd 1936 Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett and Y Saad Complex Shift and Invert Strategies for Real Matrices Linear Algebra and its Applications vol 8889 pp 575595 1987 Used Functions Based on ARPACK routine dsaupd 1937 Name dsaupd Interface for the Implicitly Restarted Arnoldi Iteration to compute approximations to the converged approximations to eigenvalues of Az lambdaBz DZRESIDVIPARAMIPNTRWORKDWORKLINFO dseupdRVECHOWMANYSELECTDZSIGMABMATNWHICH NEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLINFO Parameters RVEC Integer INPUT Specifies whether Ritz vectors corresponding to the Ritz value approximations to the eigenprob lem Az lambdaBz are computed RVEC 0 Compute Ritz values only RVEC 1 Compute Ritz vectors HOWMNY Character1 INPUT Specifies how many Ritz vectors are wanted and the form of Z the matrix of Ritz vectors See remark 1 below A compute NEV Ritz vectors S compute some of the Ritz vectors specified by the integer array SELECT SELECT Integer array of dimension NCV INPUTWORKSPACE If HOWMANY S SELECT specifies the Ritz vectors to be computed To select the Ritz vector corresponding to a Ritz value Dj SELECTj must be set to 1 If HOWMANY A SELECT is used as a workspace for reordering the Ritz values D Double precision array of dimension NEV OUTPUT On exit D contains the Ritz value approximations to the eigenvalues of Az lambdaBz The values are returned in ascending order If IPARAM7 345 then D represents the Ritz values of OP computed by dsaupd transformed to those of the original eigensystem Az lambdaBz If IPARAM7 12 then the Ritz values of OP are the same as the those of Az lambdaBz Z Double precision N by NEV array If HOWMNY A OUTPUT On exit Z contains the Borthonormal Ritz vectors of the eigen system Az lambdaBz corresponding to the Ritz value approximations If RVEC 0 then Z is not referenced NOTE The array Z may be set equal to first NEV columns of the ArnoldiLanczos basis array V computed by DSAUPD SIGMA Double precision INPUT If IPARAM7 345 represents the shift Not referenced if IPARAM7 1 or 2 dsaupd 1938 NOTE The remaining arguments BMAT N WHICH NEV TOL RESID NCV V IPARAM IP NTR WORKD WORKL LWORKL INFO must be passed directly to DSEUPD following the last call to DSAUPD These arguments MUST NOT BE MODIFIED between the the last call to DSAUPD and the call to DSEUPD Two of these parameters WORKL INFO are also output parameters WORKL Double precision work array of length LWORKL OUTPUTWORKSPACE WORKL14ncv contains information obtained in dsaupd They are not changed by dseupd WORKL4ncv1ncvncv8ncv holds the untransformed Ritz values the computed error es timates and the associated eigenvector matrix of H Note IPNTR810 contains the pointer into WORKL for addresses of the above information computed by dseupd IPNTR8 pointer to the NCV RITZ values of the original system IPNTR9 pointer to the NCV corresponding error bounds IPNTR10 pointer to the NCV by NCV matrix of eigenvectors of the tridiagonal matrix T Only referenced by dseupd if RVEC 1 See Remarks INFO Integer OUTPUT Error flag on output 0 Normal exit 1 N must be positive 2 NEV must be positive 3 NCV must be greater than NEV and less than or equal to N 5 WHICH must be one of LM SM LA SA or BE 6 BMAT must be one of I or G 7 Length of private work WORKL array is not sufficient 8 Error return from trid eigenvalue calculation Information error from LAPACK routine dsteqr 9 Starting vector is zero 10 IPARAM7 must be 12345 11 IPARAM7 1 and BMAT G are incompatible 12 NEV and WHICH BE are incompatible 14 DSAUPD did not find any eigenvalues to sufficient accuracy 15 HOWMNY must be one of A or S if RVEC 1 16 HOWMNY S not yet implemented 17 DSEUPD got a different count of the number of converged Ritz values than DSAUPD got This indicates the user probably made an error in passing data from DSAUPD to DSEUPD or that the data was modified before entering DSEUPD dsaupd 1939 Description This subroutine returns the converged approximations to eigenvalues of Az lambdaBz and op tionally 1 the corresponding approximate eigenvectors 2 an orthonormal Lanczos basis for the associated approximate invariant subspace 3 Both There is negligible additional cost to obtain eigenvectors An orthonormal Lanczos basis is always computed There is an additional storage cost of nnev if both are requested in this case a separate array Z must be supplied These quantities are obtained from the Lanczos factorization computed by DSAUPD for the lin ear operator OP prescribed by the MODE selection see IPARAM7 in DSAUPD documentation DSAUPD must be called before this routine is called These approximate eigenvalues and vectors are commonly called Ritz values and Ritz vectors respec tively They are referred to as such in the comments that follow The computed orthonormal basis for the invariant subspace corresponding to these Ritz values is re ferred to as a Lanczos basis See documentation in the header of the subroutine DSAUPD for a definition of OP as well as other terms and the relation of computed Ritz values and vectors of OP with respect to the given problem Az lambdaBz The approximate eigenvalues of the original problem are returned in ascending algebraic order The user may elect to call this routine once for each desired Ritz vector and store it peripherally if desired There is also the option of computing a selected set of these vectors with a single call Remarks 1 The converged Ritz values are always returned in increasing algebraic order c 2 Currently only HOWMNY A is implemented It is included at this stage for the user who wants to incorporate it Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 dsaupd 1940 resid zerosnx1 v zerosnxncv workd zeros3nx11 workl zerosncvncv8ncv1 Build the symmetric test matrix A diag10onesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts iparam3 maxitr iparam7 mode1 sigma 0 the real part of the shift M A I N L O O P Reverse communication iter 0 whileitermaxiter infodsaupd 0 iter iter 1 Repeatedly call the routine DSAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfodsaupd dsaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklinfodsaupd if ido99 then BE CAREFUL DONT CALL dseupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call DSAUPD again continue end if infodsaupd 0 then printf Error with dsaupd info d infodsaupd printfCheck the documentation of dsaupd else PostProcess using DSEUPD rvec 1 howmany A infodseupd 0 dsaupd 1941 dd12vresidviparamipntrworkdworklinfodseupd dseupdrvechowmanyselectdd12vsigma bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfodseupd if infodseupd0 then printf Error with dseupd info d infodseupd printfCheck the documentation of dseupd end if infodseupd1 then printf Maximum number of iterations reached elseif infodseupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end Done with program dssimp printf DSSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also dsaupd dneupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett and Y Saad Complex Shift and Invert Strategies for Real Matrices Linear Algebra and its Applications vol 8889 pp 575595 1987 Used Functions Based on ARPACK routine dsaupd 1942 Name znaupd Interface for the Implicitly Restarted Arnoldi Iteration to compute a few eigenpairs of a complex linear operator OP with respect to a semiinner product defined by a hermitian positive semidefinite real matrix B IDORESIDVIPARAMIPNTRWORKDWORKLRWORKINFO znaupdID0BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLRWORKINFO Parameters IDO Integer INPUTOUTPUT Reverse communication flag IDO must be zero on the first call to znaupd IDO will be set inter nally to indicate the type of operation to be performed Control is then given back to the calling routine which has the responsibility to carry out the requested operation and call znaupd with the result The operand is given in WORKDIPNTR1 the result must be put in WORKDIPNTR2 IDO 0 first call to the reverse communication interface IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y This is for the initialization phase to force the starting vector into the range of OP IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y In mode 3 the vector B X is already available in WORKDipntr3 It does not need to be recomputed in forming OP X IDO 2 compute Y M X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y IDO 3 compute and return the shifts in the first NP locations of WORKL IDO 99 done After the initialization phase when the routine is used in the shiftandinvert mode the vector M X is already available and does not need to be recomputed in forming OPX BMAT Character INPUT BMAT specifies the type of the matrix B that defines the semiinner product for the operator OP I standard eigenvalue problem Ax lambdax G generalized eigenvalue problem Ax lambdaMx N Integer INPUT Dimension of the eigenproblem WHICH Characters INPUT LM want the NEV eigenvalues of largest magnitude SM want the NEV eigenvalues of smallest magnitude znaupd 1943 LR want the NEV eigenvalues of largest real part SR want the NEV eigenvalues of smallest real part LI want the NEV eigenvalues of largest imaginary part SI want the NEV eigenvalues of smallest imaginary part NEV Integer INPUT Number of eigenvalues of OP to be computed 0 NEV N1 TOL Double precision scalar INPUT Stopping criteria the relative accuracy of the Ritz value is considered acceptable if BOUNDSI LE TOLABSRITZI where ABSRITZI is the magnitude when RITZI is complex DEFAULT dlamchEPS machine precision as computed by the LAPACK auxiliary subroutine dlamch RESID Complex16 array of length N INPUTOUTPUT On INPUT If INFO EQ 0 a random initial residual vector is used If INFO NE 0 RESID contains the initial residual vector possibly from a previous run On OUTPUT RESID contains the final residual vector NCV Integer INPUT Number of columns of the matrix V NCV must satisfy the two inequalities 1 NCVNEV and NCV N This will indicate how many Arnoldi vectors are generated at each iteration After the startup phase in which NEV Arnoldi vectors are generated the algorithm generates approximately NCV NEV Arnoldi vectors at each subsequent update iteration Most of the cost in generating each Arnoldi vector is in the matrixvector operation OPx See remark 4 below V Complex16 array N by NCV OUTPUT Contains the final set of Arnoldi basis vectors IPARAM Integer array of length 11 INPUTOUTPUT IPARAM1 ISHIFT method for selecting the implicit shifts The shifts selected at each iteration are used to filter out the components of the unwanted eigenvector ISHIFT 0 the shifts are to be provided by the user via reverse communication The NCV eigenvalues of the Hessenberg matrix H are returned in the part of WORKL array corre sponding to RITZ ISHIFT 1 exact shifts with respect to the current Hessenberg matrix H This is equivalent to restarting the iteration from the beginning after updating the starting vector with a linear combination of Ritz vectors associated with the wanted eigenvalues ISHIFT 2 other choice of internal shift to be defined IPARAM2 No longer referenced znaupd 1944 IPARAM3 MXITER On INPUT maximum number of Arnoldi update iterations allowed On OUTPUT actual number of Arnoldi update iterations taken IPARAM4 NB blocksize to be used in the recurrence The code currently works only for NB 1 IPARAM5 NCONV number of converged Ritz values This represents the number of Ritz values that satisfy the convergence criterion IPARAM6 IUPD No longer referenced Implicit restarting is ALWAYS used IPARAM7 MODE On INPUT determines what type of eigenproblem is being solved Must be 123 See under Description of znaupd for the four modes available IPARAM8 NP When ido 3 and the user provides shifts through reverse communication IPARAM10 naupd returns NP the number of shifts the user is to provide 0 NP NCVNEV IPARAM9 NUMOP IPARAM10 NUMOPB IPARAM11 NUMREO OUTPUT NUMOP total number of OPx operations NU MOPB total number of Bx operations if BMATG NUMREO total number of steps of reorthogonalization IPNTR Integer array of length 14 OUTPUT Pointer to mark the starting locations in the WORKD and WORKL arrays for matricesvectors used by the Arnoldi iteration IPNTR1 pointer to the current operand vector X in WORKD IPNTR2 pointer to the current result vector Y in WORKD IPNTR3 pointer to the vector B X in WORKD when used in the shiftandinvert mode IPNTR4 pointer to the next available location in WORKL that is untouched by the program IPNTR5 pointer to the NCV by NCV upper Hessenberg matrix H in WORKL IPNTR6 pointer to the ritz value array RITZ IPNTR7 pointer to the projected ritz vector array Q IPNTR8 pointer to the error BOUNDS array in WORKL IPNTR14 pointer to the NP shifts in WORKL See Remark 5 below Note IPNTR913 is only referenced by zneupd See Remark 2 below IPNTR9 pointer to the NCV RITZ values of the original system IPNTR10 Not Used IPNTR11 pointer to the NCV corresponding error bounds IPNTR12 pointer to the NCV by NCV upper triangular Schur matrix for H IPNTR13 pointer to the NCV by NCV matrix of eigenvectors of the upper Hessenberg matrix H Only referenced by zneupd if RVEC 1 See Remark 2 below znaupd 1945 WORKD Complex16 work array of length 3N REVERSE COMMUNICATION Distributed array to be used in the basic Arnoldi iteration for reverse communication The user should not use WORKD as temporary workspace during the iteration See Data Distribution Note below WORKL Complex16 work array of length 3NCV2 5NCV OUTPUTWORKSPACE Private replicated array on each PE or array allocated on the front end See Data Distribution Note below RWORK Double precision work array of length NCV WORKSPACE Private replicated array on each PE or array allocated on the front end INFO Integer INPUTOUTPUT If INFO 0 a randomly initial residual vector is used If INFO 0 RESID contains the initial residual vector possibly from a previous run Error flag on output 0 Normal exit 1 Maximum number of iterations taken All possible eigenvalues of OP has been found IPARAM5 returns the number of wanted converged Ritz values 2 No longer an informational error Deprecated starting with release 2 of ARPACK 3 No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration One possibility is to increase the size of NCV relative to NEV See remark 4 below 1 N must be positive 2 NEV must be positive 3 NCVNEV 1 and less than or equal to N 4 The maximum number of Arnoldi update iteration must be greater than zero 5 WHICH must be one of LM SM LR SR LI SI 6 BMAT must be one of I or G 7 Length of private work array is not sufficient 8 Error return from LAPACK eigenvalue calculation 9 Starting vector is zero 10 IPARAM7 must be 123 11 IPARAM7 1 and BMAT G are incompatible 12 IPARAM1 must be equal to 0 or 1 9999 Could not build an Arnoldi factorization User input error highly likely Please check actual array dimensions and layout IPARAM5 returns the size of the current Arnoldi factor ization znaupd 1946 Description Reverse communication interface for the Implicitly Restarted Arnoldi iteration This is intended to be used to find a few eigenpairs of a complex linear operator OP with respect to a semiinner product defined by a hermitian positive semidefinite real matrix B B may be the identity matrix NOTE if both OP and B are real then dsaupd or dnaupd should be used The computed approximate eigenvalues are called Ritz values and the corresponding approximate eigenvectors are called Ritz vectors znaupd is usually called iteratively to solve one of the following problems Mode 1 Ax lambdax OP A and B I Mode 2 Ax lambdaMx M hermitian positive definite OP invMA and B M If M can be factored see remark 3 below Mode 3 Ax lambdaMx M hermitian semidefinite OP invA sigmaMM and B M shiftandinvert mode If OPx amux then lambda sigma 1amu NOTE The action of w invA sigmaMv or w invMv should be accomplished either by a direct method using a sparse matrix factorization and solving A sigmaMw v or Mw v or through an iterative method for solving these systems If an iterative method is used the convergence test must be more stringent than the accuracy requirements for the eigenvalue approximations Remarks 1 The computed Ritz values are approximate eigenvalues of OP The selection of WHICH should be made with this in mind when using Mode 3 When operating in Mode 3 setting WHICH LM will compute the NEV eigenvalues of the original problem that are closest to the shift SIGMA After convergence approximate eigenvalues of the original problem may be obtained with the ARPACK subroutine zneupd 2 If a basis for the invariant subspace corresponding to the converged Ritz values is needed the user must call zneupd immediately following completion of znaupd This is new starting with release 2 of ARPACK 3 If M can be factored into a Cholesky factorization M LL then Mode 2 should not be select ed Instead one should use Mode 1 with OP invLAinvL Appropriate triangular linear systems should be solved with L and L rather than computing inverses After convergence an approximate eigenvector z of the original problem is recovered by solving Lz x where x is a Ritz vector of OP 4 At present there is no apriori analysis to guide the selection of NCV relative to NEV The only formal requirement is that NCV NEV 1 However it is recommended that NCV ge 2NEV If many problems of the same type are to be solved one should experiment with increasing NCV while keeping NEV fixed for a given test problem This will usually decrease the required number of OPx operations but it also increases the work and storage required to maintain the orthogonal basis vectors The optimal crossover with respect to CPU time is problem dependent and must be determined empirically See Chapter 8 of Reference 2 for further information znaupd 1947 5 When IPARAM1 0 and IDO 3 the user needs to provide the NP IPARAM8 complex shifts in locations WORKLIPNTR14 WORKLIPNTR141 WORKLIPNTR14NP Eigenvalues of the current upper Hessenberg matrix are located in WORKLIPNTR6 through WORKLIPNTR6NCV1 They are ordered according to the order defined by WHICH The associated Ritz estimates are located in WORKLIPNTR8 WORKLIPNTR81 WORKLIPNTR8NCV1 Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 0i v zerosnxncv 0i workd zeros3nx11 0i workev zeros3ncv1 rwork zerosncv1 workl zeros3ncvncv5ncv1 0i Build the complex test matrix A diag10onesnx1ionesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts iparam3 maxitr iparam7 mode1 sigma 0 the real part of the shift M A I N L O O P Reverse communication znaupd 1948 iter 0 whileitermaxiter infoznaupd 0 iter iter 1 Repeatedly call the routine ZNAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfoznaupd znaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklrworkinfoznaupd if ido99 then BE CAREFUL DONT CALL zneupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call ZNAUPD again continue end if infoznaupd 0 then printf Error with znaupd info d infoznaupd printfCheck the documentation of znaupd else PostProcess using ZNEUPD rvec 1 howmany A infozneupd 0 dd12vresidviparamipntrworkdworklinfozneupd zneupdrvechowmanyselectdd12vsigmaworkev bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfozneupd if infozneupd0 then printf Error with zneupd info d infozneupd printfCheck the documentation of zneupd end if infozneupd1 then printf Maximum number of iterations reached elseif infozneupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end Done with program znsimp printf ZNSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which znaupd 1949 printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also dnaupd dneupd zneupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett and Y Saad Complex Shift and Invert Strategies for Real Matrices Linear Algebra and its Applications vol 8889 pp 575595 1987 Used Functions Based on ARPACK routine znaupd 1950 Name zneupd Interface for the Implicitly Restarted Arnoldi Iteration to compute approximations to the converged approximations to eigenvalues of Az lambdaBz DZRESIDIPARAMIPNTRWORKDWORKLRWORKINFO zneupdRVECHOWMANYSELECTDZSIGMAWORKev BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLRWORKINFO Parameters RVEC Integer INPUT Specifies whether a basis for the invariant subspace corresponding to the converged Ritz value approximations for the eigenproblem Az lambdaBz is computed RVEC 0 Compute Ritz values only RVEC 1 Compute Ritz vectors or Schur vectors See Remarks below HOWMANY Character INPUT Specifies the form of the basis for the invariant subspace corresponding to the converged Ritz values that is to be computed A Compute NEV Ritz vectors P Compute NEV Schur vectors S compute some of the Ritz vectors specified by the integer array SELECT SELECT Integer array of dimension NCV INPUT If HOWMANY S SELECT specifies the Ritz vectors to be computed To select the Ritz vector corresponding to a Ritz value Dj SELECTj must be set to 1 If HOWMANY A or P SELECT need not be initialized but it is used as internal workspace D Complex16 array of dimension NEV1 OUTPUT On exit D contains the Ritz approximations to the eigenvalues lambda for Az lambdaBz Z Complex16 N by NEV array OUTPUT On exit If RVEC 1 and HOWMANY A then the columns of Z represents approximate eigenvectors Ritz vectors corresponding to the NCONVIPARAM5 Ritz values for eigensystem Az lambdaBz If RVEC 0 or HOWMANY P then Z is NOT REFERENCED NOTE If if RVEC 1 and a Schur basis is not required the array Z may be set equal to first NEV1 columns of the Arnoldi basis array V computed by ZNAUPD In this case the Arnoldi basis will be destroyed and overwritten with the eigenvector basis SIGMA Complex16 INPUT If IPARAM7 3 then SIGMA represents the shift zneupd 1951 Not referenced if IPARAM7 1 or 2 WORKev Complex16 work array of dimension 2NCV WORKSPACE NOTE The remaining arguments BMAT N WHICH NEV TOL RESID NCV V IPARAM IPN TR WORKD WORKL LWORKL RWORK INFO must be passed directly to ZNEUPD following the last call to ZNAUPD These arguments MUST NOT BE MODIFIED between the the last call to ZNAUPD and the call to ZNEUPD Three of these parameters V WORKL and INFO are also output parameters V Complex16 N by NCV array INPUTOUTPUT Upon INPUT the NCV columns of V contain the Arnoldi basis vectors for OP as constructed by ZNAUPD Upon OUTPUT If RVEC 1 the first NCONVIPARAM5 columns contain approximate Schur vectors that span the desired invariant subspace NOTE If the array Z has been set equal to first NEV1 columns of the array V and RVEC1 and HOWMANY A then the Arnoldi basis held by V has been overwritten by the desired Ritz vectors If a separate array Z has been passed then the first NCONVIPARAM5 columns of V will contain approximate Schur vectors that span the desired invariant subspace WORKL Double precision work array of length LWORKL OUTPUTWORKSPACE WORKL1ncvncv2ncv contains information obtained in znaupd They are not changed by zneupd WORKLncvncv2ncv13ncvncv4ncv holds the untransformed Ritz values the un transformed error estimates of the Ritz values the upper triangular matrix for H and the associ ated matrix representation of the invariant subspace for H Note IPNTR913 contains the pointer into WORKL for addresses of the above information computed by zneupd IPNTR9 pointer to the NCV RITZ values of the original system IPNTR10 Not used IPNTR11 pointer to the NCV corresponding error estimates IPNTR12 pointer to the NCV by NCV upper triangular Schur matrix for H IPNTR13 pointer to the NCV by NCV matrix of eigenvectors of the upper Hessenberg matrix H Only referenced by zneupd if RVEC 1 See Remark 2 below INFO Integer OUTPUT Error flag on output 0 Normal exit 1 The Schur form computed by LAPACK routine csheqr could not be reordered by LAPACK routine ztrsen Reenter subroutine zneupd with IPARAM5NCV and increase the size of the array D to have dimension at least dimension NCV and allocate at least NCV columns for Z NOTE Not necessary if Z and V share the same space Please notify the authors if this error occurs zneupd 1952 1 N must be positive 2 NEV must be positive 3 NCVNEV 1 and less than or equal to N 5 WHICH must be one of LM SM LR SR LI SI 6 BMAT must be one of I or G 7 Length of private work WORKL array is not sufficient 8 Error return from LAPACK eigenvalue calculation This should never happened 9 Error return from calculation of eigenvectors Informational error from LAPACK routine ztrevc 10 IPARAM7 must be 123 11 IPARAM7 1 and BMAT G are incompatible 12 HOWMANY S not yet implemented 13 HOWMANY must be one of A or P if RVEC true 14 ZNAUPD did not find any eigenvalues to sufficient accuracy 15 ZNEUPD got a different count of the number of converged Ritz values than ZNAUPD got This indicates the user probably made an error in passing data from ZNAUPD to ZNEUPD or that the data was modified before entering ZNEUPD Description This subroutine returns the converged approximations to eigenvalues of Az lambdaBz and op tionally 1 The corresponding approximate eigenvectors 2 An orthonormal basis for the associated approximate invariant subspace 3 Both There is negligible additional cost to obtain eigenvectors An orthonormal basis is always computed There is an additional storage cost of nnev if both are requested in this case a separate array Z must be supplied The approximate eigenvalues and eigenvectors of Az lambdaBz are derived from approximate eigenvalues and eigenvectors of of the linear operator OP prescribed by the MODE selection in the call to ZNAUPD ZNAUPD must be called before this routine is called These approximate eigenvalues and vectors are commonly called Ritz values and Ritz vectors respec tively They are referred to as such in the comments that follow The computed orthonormal basis for the invariant subspace corresponding to these Ritz values is re ferred to as a Schur basis The definition of OP as well as other terms and the relation of computed Ritz values and vectors of OP with respect to the given problem Az lambdaBz may be found in the header of ZNAUPD For a brief description see definitions of IPARAM7 MODE and WHICH in the documentation of ZNAUPD zneupd 1953 Remarks 1 Currently only HOWMNY A and P are implemented 2 Schur vectors are an orthogonal representation for the basis of Ritz vectors Thus their numerical properties are often superior If RVEC 1 then the relationship A V1IPARAM5 V1IPARAM5 T and transpose V1IPARAM5 V1IPARAM5 I are approximately satisfied Here T is the leading submatrix of order IPARAM5 of the upper triangular matrix stored worklipntr12 Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 0i v zerosnxncv 0i workd zeros3nx11 0i workev zeros3ncv1 rwork zerosncv1 workl zeros3ncvncv5ncv1 0i Build the complex test matrix A diag10onesnx1ionesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts zneupd 1954 iparam3 maxitr iparam7 mode1 sigma 0 the real part of the shift M A I N L O O P Reverse communication iter 0 whileitermaxiter infoznaupd 0 iter iter 1 Repeatedly call the routine ZNAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfoznaupd znaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklrworkinfoznaupd if ido99 then BE CAREFUL DONT CALL zneupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call ZNAUPD again continue end if infoznaupd 0 then printf Error with znaupd info d infoznaupd printfCheck the documentation of znaupd else PostProcess using ZNEUPD rvec 1 howmany A infozneupd 0 dd12vresidviparamipntrworkdworklinfozneupd zneupdrvechowmanyselectdd12vsigmaworkev bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfozneupd if infozneupd0 then printf Error with zneupd info d infozneupd printfCheck the documentation of zneupd end if infozneupd1 then printf Maximum number of iterations reached elseif infozneupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end Done with program znsimp printf ZNSIMP zneupd 1955 printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also znaupd dnaupd dneupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett and Y Saad Complex Shift and Invert Strategies for Real Matrices Linear Algebra and its Applications vol 8889 pp 575595 1987 Used Functions Based on ARPACK routine zneupd Parte XXXVI Funções de Compatibilidade 1957 Name asciimat string matrix ascii conversions aasciimattxt txtasciimata Parameters txt character string or matrix of strings a vector or matrix of integer ASCII codes Description This function convert Scilab string to ASCII code or a matrix of ASCII code to Scilab string Output is a matrix having same number of lines than input what is not the case with ascii See Also ascii Authors VC 1958 Name firstnonsingleton Finds first dimension which is not 1 dimfirstnonsingletonAopt Parameters dim first dimension of A which is not 1 A a variable of any Scilab data type opt a character string giving the type of output we want num returned value is a numerical value str returned value is a character string if possible r instead of 1 and c instead of 2 Description This function is used by mfile2sci to emulate Matlab behavior under Scilab particularly for func tions which treat the values along the first nonsingleton dimension of A in Matlab while in Scilab they treat all values of A Examples A 1 2 34 5 6 Scilab max M maxA Matlab max emulation M maxAfirstnonsingletonA Authors VC 1959 Nom makecell Creates a cell array s makecelldimsa1a2an Parameters dims a vector with positive integer elements the cell array dimension a1a2an Sequence of Scilab variables n must be equal to proddims s resulting cell array Description s makecelldimsa1a2an creates a cell array of dimensions given by dims with the given input arguments The ai are stored along the last dimension first Examples makecell23123xyz See Also cell Authors Farid Belhacen INRIA 1960 Name mstr2sci character string matrix to character matrix conversion amstr2scitxt Parameters txt character string or string matrix a character vector or matrix Description This function converts a Scilab character string to a vector of characters Result is the Scilab equivalent for a Matlab string Caution mstr2sci has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 1961 Name mtlb0 Matlab nonconjugate transposition emulation function Description Matlab and Scilab nonconjugate transposition behave differently in some particular cases With character strings operands The operator is used to transpose whole character strings in Scilab while Matlab realizes the transposition of each character The function mtlb0A is used by mfile2sci to replace A when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlb0 calls If A is not a character string matrix mtlb0A may be replaced by A Caution mtlb0 has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 1962 Name mtlba Matlab addition emulation function Description Matlab and Scilab addition behave differently in some particular cases With character string operands The operator is used into Scilab to catenate character strings while Matlab realizes the sum of the operands ASCII codes With empty matrix In Scilab if one of the operands is an empty matrix the result of the addition is the other operand In Matlab if one of the operand is an empty matrix the result of the addition should be an error or an empty matrix The function mtlbaAB is used by mfile2sci to replace AB when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlba calls If A and B are character strings mtlbaAB may be replaced by asciimatAasciimatB If both A and B are not empty matrices mtlbaAB may be replaced by AB else mtlbaAB may be replaced by If mtlbmodeT then mtlbaAB may be replaced by AB in any case where A and B are not character string matrices Caution mtlba has not to be used for hand coded functions See Also mtlbmode Authors VC 1963 Name mtlball Matlab all emulation function Description Matlab all and Scilab and behave differently in some particular cases When used with one input allA Matlab all treats the values along the first nonsingleton dimension of A as vectors while Scilab and treats all A values When used with two inputs allAdim Matlab tolerates dim to be greater than the number of dimensions of A while Scilab returns an error message in this case The function R mtlballAdim is used by mfile2sci to replace allAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlball calls If A is a scalar or a vector R mtlballA may be replaced by R andA If A is a matrix R mtlballA may be replaced by R andA1 If A is an hypermatrix R mtlballA may be replaced by R andAfirstnonsingletonA or by R andAuserdefinedvalue if the first nonsingleton dimensions of A is known If dim is less equal to the number of dimensions of A R mtlballAdim may be replaced by R andAdim If dim is greater than then number of dimensions of A R mtlballAdim may be replaced by R A0 if A is not an empty matrix or by R A if A is an empty matrix Caution mtlball has not to be used for hand coded functions See Also firstnonsingleton Authors VC 1964 Name mtlbany Matlab any emulation function Description Matlab any and Scilab or behave differently in some particular cases When used with one input anyA Matlab any treats the values along the first nonsingleton dimension of A as vectors while Scilab or treats all A values When used with two inputs anyAdim Matlab tolerates dim to be greater than the number of dimensions of A while Scilab returns an error message in this case The function R mtlbanyAdim is used by mfile2sci to replace anyAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbany calls If A is a scalar or a vector R mtlbanyA may be replaced by R orA If A is a matrix R mtlbanyA may be replaced by R orA1 If A is an hypermatrix R mtlbanyA may be replaced by R orAfirstnonsingletonA or by R orAuserdefinedvalue if the first nonsingleton dimensions of A is known If dim is less equal to the number of dimensions of A R mtlbanyAdim may be replaced by R orAdim If dim is greater than then number of dimensions of A R mtlbanyAdim may be replaced by R A0 if A is not an empty matrix or by R A if A is an empty matrix Caution mtlbany has not to be used for hand coded functions See Also firstnonsingleton Authors VC 1965 Name mtlbaxis Matlab axis emulation function mtlbaxisX mtlbaxisst mtlbaxisaxeshandle modevisibilitydirectionmtlbaxisstate Parameters X a vector of reals xmin xmax ymin ymax or xmin xmax ymin ymax zmin zmax st a string auto manual tight ij xy equal square vis3d off on axeshandle handle of the current axes entity Description Matlab axis have not a Scilab equivalent function The function mtlbaxis is used by mfile2sci to replace axis when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will de termine the correct semantic at run time axis fill axis image and axis normal are not imple mented If you want to have a more efficient code it is possible to replace mtlbaxis call by getaxeshandle prop call prop is a axes property see axisproperties Caution mtlbaxis has not to be used for hand coded functions Authors FB 1966 Name mtlbbeta Matlab beta emulation function Description Matlab and Scilab beta behave differently in some particular cases With inputs having different sizes Matlab beta input parameters must have the same size unless one of them is a scalar In Scilab beta input parameters must have the same size even if one of them is a scalar The function mtlbbetaAB is used by mfile2sci to replace betaAB when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbbeta calls If A is a scalar but not B Y mtlbbetaAB may be replaced by CBCAY mtlbbetaCB If B is a scalar but not A Y mtlbbetaAB may be replaced by CACBY mtlbbetaAC Caution mtlbbeta has not to be used for hand coded functions Authors VC 1967 Name mtlbbox Matlab box emulation function Description There is no Scilab equivalent function for Matlab box but it can be easyly replaced The function mtlbboxaxeshandleval is used by mfile2sci to replace boxaxeshandleval when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbbox calls When called without input parameters mtlbbox may be replaced by agcaif aboxon then aboxoffelse aboxonend If axeshandle is a character string mtlbboxaxeshandle may be replaced by agcaaboxconvstraxeshandlel If axeshandle is a graphic handle mtlbboxaxeshandle may be replaced by if axeshandleboxon then axeshandleboxoffelse axeshandleboxonend If axeshandle is a graphic handle and val is a char acter string mtlbboxaxeshandleval may be replaced by axeshandleboxconvstrvall Caution mtlbbox has not to be used for hand coded functions See Also axesproperties Authors VC 1968 Name mtlbclose Matlab close emulation function Description Scilab equivalent for Matlab close is different according to the current figure type uicontrol or graphic one When current figure is a uicontrol one Scilab equivalent for Matlab close is close When current figure is a graphic one Scilab equivalent for Matlab close is xdel or delete In Scilab we do not get an error status The function mtlbcloseh is used by mfile2sci to replace closeh when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbclose calls If h is a uicontrol figure mtlbcloseh may be replaced by closeh If h is a graphic figure mtlbcloseh may be replaced by deleteh Caution mtlbclose has not to be used for hand coded functions See Also xdel delete winsid close Authors VC 1969 Name mtlbcolordef Matlab colordef emulation function Description There is no Scilab equivalent function for Matlab colordef but there are equivalent instructions The function h mtlbcolordefcoloroption or h mtlbcolordeffigcoloroption is used by mfile2sci to replace colordefcoloroption or colordeffigcoloroption when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbcolordef calls When called with one input parameter if coloroption is equal to black or none mtlbcolordefcoloroption may be replaced by fig gcffigbackground 1 When called with one input parameter if coloroption is equal to white mtlbcolordefcoloroption may be replaced by fig gcffigbackground 2 When called with two input parameters if fig is a graphic handle and coloroption is equal to black or none mtlbcolordefcoloroption may be replaced by figbackground 1 When called with two input parameters if fig is a graphic handle and coloroption is equal to white mtlbcolordefcoloroption may be replaced by figbackground 2 When called with two input parameters if fig is equal to new and coloroption is equal to black or none mtlbcolordefcoloroption may be replaced by fig scfmaxwinsid1figbackground 1 When called with two input parameters if fig is equal to new and coloroption is equal to white mtlbcolordefcoloroption may be replaced by fig scfmaxwinsid1figbackground 2 When called with one output parameter h just add h fig after equivalent instructions Caution mtlbcolordef has not to be used for hand coded functions See Also figureproperties Authors VC 1970 Name mtlbconv Matlab conv emulation function Description Matlab conv and Scilab convol behave differently in some particular cases With column vector inputs if at least input is a column vector Matlab conv returns a column vector but Scilab convol always returns a row vector The function mtlbconvuv is used by mfile2sci to replace convuv when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbconv calls If u and v are row vectors mtlbconvuv may be replaced by convoluv If u or v is a column vector mtlbconvuv may be replaced by convoluv If u and v are column vectors mtlbconvuv may be replaced by convoluv Scilab convol sometimes returns values that may be rounded using clean to have a closer result from Matlab one Caution mtlbconv has not to be used for hand coded functions See Also clean Authors VC 1971 Name mtlbcumprod Matlab cumprod emulation function Description Matlab and Scilab cumprod behave differently in some particular cases When used with one input cumprodA Matlab cumprod treats the values along the first non singleton dimension of A as vectors while Scilab cumprod treats all A values When used with two inputs cumprodAdim Matlab tolerates dim to be greater than the number of dimensions of A while Scilab returns an error message in this case The function R mtlbcumprodAdim is used by mfile2sci to replace cumprodAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbcumprod calls If dim is less equal to the number of dimensions of A R mtlbcumprodAdim may be replaced by R cumprodAdim If dim is greater than then number of dimensions of A R mtlbcumprodAdim may be replaced by R A Caution mtlbcumprod has not to be used for hand coded functions See Also firstnonsingleton Authors VC 1972 Name mtlbcumsum Matlab cumsum emulation function Description Matlab and Scilab cumsum behave differently in some particular cases When used with one input cumsumA Matlab cumsum treats the values along the first non singleton dimension of A as vectors while Scilab cumsum treats all A values When used with two inputs cumsumAdim Matlab tolerates dim to be greater than the num ber of dimensions of A while Scilab returns an error message in this case The function R mtlbcumsumAdim is used by mfile2sci to replace cumsumAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbcumsum calls If dim is less equal to the number of dimensions of A R mtlbcumsumAdim may be replaced by R cumsumAdim If dim is greater than then number of dimensions of A R mtlbcumsumAdim may be replaced by R A Caution mtlbcumsum has not to be used for hand coded functions See Also firstnonsingleton Authors VC 1973 Name mtlbdec2hex Matlab dec2hex emulation function Description Matlab and Scilab dec2hex behave differently in some particular cases With empty matrix Matlab dec2hex returns but in Scilab you get With complex inputs Matlab dec2hex automatically removes complex part of inputs but not Scilab one Matlab dec2hex always returns a row vector but in Scilab dec2hex returns a value which have the same size as the input Matlab dec2hex can have two inputs but not Scilab one The function mtlbdec2hexDN is used by mfile2sci to replace dec2hexDN when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdec2hex calls If D is not an empty matrix mtlbdec2hexD may be re placed by matrixdec2hexrealD11 if D is complex and by matrixdec2hexD11 else Caution mtlbdec2hex has not to be used for hand coded functions Authors VC 1974 Name mtlbdelete Matlab delete emulation function Description The function mtlbdeleteA is used by mfile2sci to replace deleteA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdelete calls If A is a character string mtlbdeleteA may be replaced by mdeleteA If A is a graphic handle mtlbdeleteA may be replaced by deleteA Caution mtlbdelete has not to be used for hand coded functions See Also mdelete Authors VC 1975 Name mtlbdiag Matlab diag emulation function Description Matlab and Scilab diag behave differently in some particular cases With character string matrices Scilab diag function considers each character string as an object while Matlab considers each character individually The function y mtlbdiagxdim is used by mfile2sci to replace y diagxdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdiag calls If x is not a character string matrix y mtlbdiagxdim may be replaced by y diagxdim Caution mtlbdiag has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 1976 Name mtlbdiff Matlab diff emulation function Description Matlab and Scilab diff behave differently in some particular cases With two input parameters Scilab diff considers all values of first input as a vector what Matlab does not With three input parameters If dimension of first input along dimension given by third parameter reaches 1 before n interations have been madeMatlab switches to next nonsingleton dimension what Scilab does not The function mtlbdiffAndim is used by mfile2sci to replace diffAndim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdiff calls With two inputs if A is a scalar or a vector mtlbdiffAn may be replaced by diffAn With three inputs if size of A along dimension given by dim can not reach 1 mtlbdiffAndim may be replaced by diffAndim Caution mtlbdiff has not to be used for hand coded functions Authors VC 1977 Name mtlbdir Matlab dir emulation function Description Matlab and Scilab dir behave differently When result is stored in a variable Matlab dir returns a structure but Scilab dir returns a dir tlist so data can not be extracted in the same way The function mtlbdirpath is used by mfile2sci to replace dirpath when out put is stored in a variable There is no replacement possibility for it else when mtlbdir is re placed by dir data can not be extracted like in Matlab For example Scilab equivalent for Matlab LdirfilenameL1name is LdirfilenameLname1 Caution mtlbdir has not to be used for hand coded functions Authors VC 1978 Name mtlbdouble Matlab double emulation function Description Matlab and Scilab double behave differently in some particular cases With character string input Scilab double does not work with this type of input while Matlab double returns a matrix of ASCII codes With boolean input Scilab double does not work with this type of input while Matlab double returns a matrix of double values The function mtlbdoubleA is used by mfile2sci to replace doubleA when it was not possible to know what were theinput while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdouble calls If A is a character string mtlbdoubleA may be replaced by asciimatA If A is a boolean matrix mtlbdoubleA may be replaced by bool2sA If A is a double matrix mtlbdoubleA may be replaced by A Caution mtlbdouble has not to be used for hand coded functions See Also asciimat bool2s Authors VC 1979 Name mtlbe Matlab extraction emulation function Description Matlab and Scilab extraction behave differently in some particular cases When extracting data from a matrix with a vector as index Matlab returns a row vector and Scilab returns a column vector When extracting data from a character string matrix due to the fact that character string matrices in Matlab can be adressed as any other matrix each character can be adressed extraction in such a type of matrix does not differ from other But in Scilab it cant be done so and part function has to be used The function mtlbeBk is used by mfile2sci to replace ABk when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbe calls If B is a vector AmtlbeBk may be replaced by ABk If B is a matrix AmtlbeBk may be replaced by ABk If B is a character string matrix and k is a scalar or a vector AmtlbeBk may be replaced by ApartBk Caution mtlbe has not to be used for hand coded functions See Also MatlabScilabcharacterstrings part Authors VC 1980 Name mtlbecho Matlab echo emulation function Description There is no equivalent for Matlab echo in Scilab but some cases can be replaced by calls to Scilab mode echo is equivalent to Scilab modeabsmode1 for scripts and noncompiled functions echo on is equivalent to Scilab mode1 for scripts and noncompiled functions echo off is equivalent to Scilab mode0 The function mtlbechoarg1arg2 is used by mfile2sci to replace echo arg1 arg2 when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbecho calls If arg1 is equal to on mtlbechoarg1 may be replaced by mode1 If arg1 is equal to off mtlbechoarg1 may be replaced by mode0 Caution mtlbecho has not to be used for hand coded functions See Also mode Authors VC 1981 Name mtlbeval Matlab eval emulation function Description Scilab equivalent for Matlab eval is different according to its inputs and outputs The function mtlbevalstr1str2 is used by mfile2sci to replace eval because it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbeval calls When called with one input and no output mtlbevalstr1 may be replaced by evstrstr1 if str1 is a valid Scilab expression or by execstrstr1 if str1 is a valid Scilab instruction When called with one input and one output valmtlbevalstr1 may be replaced by valevstrstr1 if str1 is a valid Scilab instruction When called with two inputs and no output mtlbevalstr1str2 may be replaced by if execstrstr1errcatch0 then execstrstr2end if str1 and str2 are valid Scilab instructions When called with more than one output and one in put val1val2mtlbevalstr1 may be replaced by execstrval1val2str1 if str1 is a valid Scilab instruction When called with two inputs and more than one output val1val2mtlbevalstr1str2 may be replaced by if execstrval1val2str1errcatch0 then execstrval1val2str2 end if str1 and str2 are valid Scilab instructions Caution mtlbeval has not to be used for hand coded functions See Also evstr execstr Authors VC 1982 Name mtlbexist Matlab exist emulation function Description There is no Scilab equivalent for Matlab exist except when input is a variable Scilab mtlbexist is a partial emulation of of this function The function r mtlbexistnamtp is used by mfile2sci to replace existnamtp when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbexist calls When called with one input and if nam is a variable name mtlbexistnam may be replaced by existsnam Caution mtlbexist has not to be used for hand coded functions See Also exists Authors VC 1983 Name mtlbeye Matlab eye emulation function Description Matlab and Scilab eye behave differently in some particular cases With a scalar input Matlab eye returns a n x n matrix while Scilab returns a 1 The function mtlbeyeA is used by mfile2sci to replace eyeA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbeye calls If A is a scalar mtlbeyeA may be replaced by eyeAA If A is not a scalar mtlbeyeA may be replaced by eyeA Caution mtlbeye has not to be used for hand coded functions Authors VC 1984 Name mtlbfalse Matlab false emulation function Description There is no Scilab equivalent for Matlab false However Scilab zeros returns a result interpreted in an equivalent way for Scilab Matlab false and Scilab zeros behave differently in some particular cases With a scalar input Matlab false returns a n x n matrix of zeros while Scilab zeros returns a 0 The function mtlbfalseA is used by mfile2sci to replace falseA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfalse calls If A is a scalar mtlbfalseA may be replaced by zerosAA If A is not a scalar mtlbfalseA may be replaced by zerosA Caution mtlbfalse has not to be used for hand coded functions Authors VC 1985 Name mtlbfft Matlab fft emulation function Description Matlab and Scilab fft behave differently in some particular cases With one input parameter If input is a scalar or vector Scilab equivalent for Matlab fft is fft1 else if input is a matrix Scilab equivalent for Matlab fft is fft121 The function mtlbfftXnjob is used by mfile2sci to replace fftXn job when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfft calls If X is a scalar or a vector mtlbfftX1 may be replaced by fftX1 If X is a matrix mtlbfftX1 may be replaced by fftX121 Caution mtlbfft has not to be used for hand coded functions Authors VC 1986 Name mtlbfftshift Matlab fftshift emulation function Description Matlab and Scilab fftshift behave differently in some particular cases With character string input due to the fact that character strings are not considered in the same way in Matlab and Scilab results can be different for this kind of input With two inputs Matlab fftshift can work even if dim parameter is greater than number of dimensions of first input The function mtlbfftshiftAdim is used by mfile2sci to replace fftshiftAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfftshift calls If A is not a character string matrix mtlbfftshiftA may be replaced by fftshiftA If A is not a character string matrix and dim is not greater than sizesizea mtlbfftshiftAdim may be replaced by fftshiftAdim Caution mtlbfftshift has not to be used for hand coded functions Authors VC 1987 Name mtlbfind Matlab find emulation function Description Matlab and Scilab find behave differently in some particular cases With column vectors and matrices as input Matlab find returns column vectors while Scilab returns row vectors When called with three outputs Matlab find can have three outputs but Scilab not The function ijv mtlbfindB is used by mfile2sci to replace ijv findB when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfind calls When called with one output if B is a row vector i mtlbfindB may be replaced by i findB When called with one output if B is not a row vector i mtlbfindB may be replaced by i matrixfindB11 When called with two outputs if B is a row vector ij mtlbfindB may be replaced by ij findB When called with two outputs if B is not a row vector ij mtlbfindB may be replaced by ij findBi matrixi11j matrixj11 Caution mtlbfind has not to be used for hand coded functions Authors VC 1988 Name mtlbfindstr Matlab findstr emulation function Description There is no Scilab equivalent for Matlab findstr The function mtlbfindstrAB is used by mfile2sci to replace findstrAB when it was not possible to know what were the operandsinputsCUSTOM while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfindstr calls If A is always longer than B ie findstr can be replaced by strfind in Matlab mtlbfindstrAB may be replaced by strindexAB Caution mtlbfindstr has not to be used for hand coded functions Authors VC 1989 Name mtlbfliplr Matlab fliplr emulation function Description Matlab and Scilab fliplr behave differently in some particular cases With character string matrices due to te fact that Scilab and Matlab do not consider character string matrices in the same way result can be different for input of this type The function mtlbfliplrA is used by mfile2sci to replace fliplrA when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfliplr calls If A is not a character string matrix mtlbfliplrA may be replaced by A11 Caution mtlbfliplr has not to be used for hand coded functions Authors VC 1990 Name mtlbfopen Matlab fopen emulation function Description Matlab fopen and Scilab mopen behave differently in some particular cases Scilab function returns no usable error message Scilab file identified does not exist in case of error but Matlab one is set to 1 Matlab function can work with inputs which do not exist in Scilab such as permission options The function mtlbfopenfilenamepermission is used by mfile2sci to replace mopenfilenamepermission when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfopen calls If error message is not used and no error can occurs mtlbfopenfilenamepermission may be replaced by mopenfilenamepermission0 Caution mtlbfopen has not to be used for hand coded functions Authors VC 1991 Name mtlbformat Matlab format emulation function Description Matlab and Scilab format behave differently in some particular cases Some Matlab formats do not exist in Scilab Calling sequence for format is different in Scilab and Matlab The function mtlbformattypeprec is used by mfile2sci to replace formattype prec when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbformat calls If type and prec mtlbformat may be replaced by formatv6 If type and prec mtlbformat may be replaced by format6 If typelong and prec mtlbformatlong may be replaced by for mat16 If typelong and prece mtlbformatlonge may be replaced by formate16 If typelong and precg mtlbformatlongg may be replaced by formate16 If typeshort and prec mtlbformatshort may be replaced by for mat6 If typeshort and prece mtlbformatshorte may be replaced by formate6 If typeshort and precg mtlbformatshortg may be replaced by formate6 Caution mtlbformat has not to be used for hand coded functions Authors VC 1992 Name mtlbfprintf Matlab fprintf emulation function Description There is no Scilab exact equivalent for Matlab fprintf Scilab mfprintf and Matlab fprintf behave differently in many cases but they are equivalents in some cases The function mtlbfprintfvarargin is used by mfile2sci to replace fprintf This function will determine the correct semantic at run time It is sometimes possible to replace calls to mtlbfprintf by calls to mfprintf Caution mtlbfprintf has not to be used for hand coded functions See Also mfprintf Authors VC 1993 Name mtlbfread Matlab fread emulation function Description There is no Scilab equivalent for Matlab fread Scilab mget and Matlab fread behave differently in many cases but they are equivalents in some cases The function mtlbfreadvarargin is used by mfile2sci to replace fread This func tion will determine the correct semantic at run time It is sometimes possible to replace calls to mtlbfread by calls to mget Caution mtlbfread has not to be used for hand coded functions See Also mget Authors VC 1994 Name mtlbfscanf Matlab fscanf emulation function Description There is no Scilab exact equivalent for Matlab fscanf Scilab mfscanf and Matlab fscanf be have differently in many cases but they are equivalents in some cases The function mtlbfscanfvarargin is used by mfile2sci to replace fscanf This func tion will determine the correct semantic at run time It is sometimes possible to replace calls to mtlbfscanf by calls to mfscanf Caution mtlbfscanf has not to be used for hand coded functions See Also mfscanf Authors VC 1995 Name mtlbfull Matlab full emulation function Description Matlab and Scilab full behave differently in some particular cases With character strings input Matlab full can be used with character string input while Scilab function cannot With boolean input Matlab full can be used with boolean input while Scilab function cannot The function mtlbfullA is used by mfile2sci to replace fullA when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfull calls If A is a double matrix mtlbfullA may be replaced by fullA If A is a boolean matrix mtlbfullA may be replaced by fullbool2sA Caution mtlbfull has not to be used for hand coded functions Authors VC 1996 Name mtlbfwrite Matlab fwrite emulation function Description There is no Scilab equivalent for Matlab fwrite Scilab mput and Matlab fwrite behave differ ently in many cases but they are equivalents in some cases The function mtlbfwritevarargin is used by mfile2sci to replace fwrite This func tion will determine the correct semantic at run time It is sometimes possible to replace calls to mtlbfwrite by calls to mput Caution mtlbfwrite has not to be used for hand coded functions See Also mput Authors VC 1997 Name mtlbgrid Matlab grid emulation function Description There is no Scilab equivalent function for Matlab grid but there are equivalent instructions The function mtlbgridflagorhandleflag is used by mfile2sci to replace gridflagorhandleflag when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbgrid calls With one input if flag is equal to on mtlbgridflag may be replaced by setgcagrid1 1 With one input if flag is equal to off mtlbgridflag may be replaced by setgcagrid1 1 With two inputs if flag is equal to on mtlbgridaxeshandleflag may be replaced by axeshandlegrid1 1 With two inputs if arg2 is equal to off mtlbgridaxeshandleflag may be replaced by axeshandlegrid1 1 Caution mtlbgrid has not to be used for hand coded functions See Also axesproperties Authors VC 1998 Name mtlbhold Matlab hold emulation function Description There is no Scilab equivalent function for Matlab hold but there are equivalent instructions The function mtlbholdflag is used by mfile2sci to replace hold flag when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbhold calls If flag is equal to on mtlbholdflag may be replaced by setgcaautoclearoff If flag is equal to off mtlbholdflag may be replaced by setgcaautoclearon Caution mtlbhold has not to be used for hand coded functions See Also axesproperties Authors VC 1999 Name mtlbi Matlab insertion emulation function Description Matlab and Scilab insertion behave differently in some particular cases When inserting a matrix in a variable Matlab automatically adjusts output variable to fit with matrix to insert but not Scilab For example with A1 A12341234 returns an error in Scilab while in Matlab we get A1234 If values miss comparing to indexes Matlab fills output value with 0 When inserting data into a character string matrix due to the fact that character string matrices in Matlab can be adressed as any other matrix each character can be adressed insertion in such a type of matrix does not differ from other But in Scilab it cant be done somtlbis is an alternative The function AmtlbiAkB is used by mfile2sci to replace AkB when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbi calls If A is not a vector AmtlbiAkB may be replaced by AkB If A and B are both row or column vectors AmtlbiAkB may be replaced by AkB Caution mtlbi has not to be used for hand coded functions See Also MatlabScilabcharacterstrings mtlbis Authors VC 2000 Name mtlbifft Matlab ifft emulation function Description Matlab ifft and Scilab fft behave differently in some particular cases With one input parameter If input is a scalar or vector Scilab equivalent for Matlab ifftA is fftA1 else if input is a matrix Scilab equivalent for Matlab fft is fftA121 The function mtlbifftXnjob is used by mfile2sci to replace ifftXn job when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbifft calls If X is a scalar or a vector mtlbifftX1 may be replaced by fftX1 If X is a matrix mtlbifftX1 may be replaced by fftX121 Caution mtlbifft has not to be used for hand coded functions Authors VC 2001 Name mtlbimp Matlab colon emulation function Description Matlab and Scilab colon behave differently in some particular cases With empty matrices The operator must be used with scalars in Scilab and gives an error message when used with empty matrices while Matlab returns in these cases The function mtlbimpABC is used by mfile2sci to replace ABC when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbimp calls If A B and C are not empty matrices mtlbimpABC may be replaced by ABC Caution mtlbimp has not to be used for hand coded functions Authors VC 2002 Name mtlbint16 Matlab int16 emulation function Description Matlab and Scilab int16 behave differently in some particular cases With complex input Matlab int16 can be used with complex values what Scilab function can not With inf Matlab int16 returns 32767 and Scilab returns 32768 With nan Matlab int16 returns 0 and Scilab returns 32768 With nan Matlab int16 returns 0 and Scilab returns 32768 The function mtlbint16A is used by mfile2sci to replace int16A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbint16 calls If A does not contain inf nan or nan values mtlbint16A may be replaced by int16A Caution mtlbint16 has not to be used for hand coded functions Authors VC 2003 Name mtlbint32 Matlab int32 emulation function Description Matlab and Scilab int32 behave differently in some particular cases With complex input Matlab int32 can be used with complex values what Scilab function can not With inf Matlab int32 returns 2147483647 and Scilab returns 2147483648 With nan Matlab int32 returns 0 and Scilab returns 2147483648 With nan Matlab int32 returns 0 and Scilab returns 2147483648 The function mtlbint32A is used by mfile2sci to replace int32A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbint32 calls If A does not contain inf nan or nan values mtlbint32A may be replaced by int32A Caution mtlbint32 has not to be used for hand coded functions Authors VC 2004 Name mtlbint8 Matlab int8 emulation function Description Matlab and Scilab int8 behave differently in some particular cases With complex input Matlab int8 can be used with complex values what Scilab function can not With inf Matlab int8 returns 127 and Scilab returns 0 With inf Matlab int8 returns 128 and Scilab returns 0 The function mtlbint8A is used by mfile2sci to replace int8A when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbint8 calls If A does not contain inf or inf values mtlbint8A may be replaced by int8A Caution mtlbint8 has not to be used for hand coded functions Authors VC 2005 Name mtlbis Matlab string insertion emulation function Description Matlab and Scilab insertion behave differently for strings due to the fact that they do not consider character strings in the same way The function str mtlbisstosfromij is used by mfile2sci to replace insertion operations for character strings This function will determine the correct semantic at run time There is no replacement possibility for it Caution mtlbis has not to be used for hand coded functions See Also MatlabScilabcharacterstrings mtlbi Authors VC 2006 Name mtlbisa Matlab isa emulation function Description There is no Scilab equivalent function for Matlab isa but some equivalent expressions can be used when the object class exists in Scilab The function mtlbisaOBJclass is used by mfile2sci to replace isaOBJclass when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbisa calls If class is equal to logical mtlbisaOBJclass may be replaced by typeOBJ4 If class is equal to char mtlbisaOBJclass may be replaced by typeOBJ10 If class is equal to numeric mtlbisaOBJclass may be replaced by ortypeOBJ158 If class is equal to intX X being equal to 8 16 or 32 mtlbisaOBJclass may be replaced by typeofOBJintX If class is equal to uintX X being equal to 8 16 or 32 mtlbisaOBJclass may be replaced by typeofOBJuintX If class is equal to single mtlbisaOBJclass may be replaced by typeOBJ1 If class is equal to double mtlbisaOBJclass may be replaced by typeOBJ1 If class is equal to cell mtlbisaOBJclass may be replaced by typeofOBJce If class is equal to struct mtlbisaOBJclass may be replaced by typeofOBJst If class is equal to functionhandle mtlbisaOBJclass may be replaced by typeOBJ13 If class is equal to sparse mtlbisaOBJclass may be replaced by typeOBJ5 If class is equal to lti mtlbisaOBJclass may be replaced by typeofOBJstatespace Caution mtlbisa has not to be used for hand coded functions See Also type typeof Authors VC 2007 Name mtlbisfield Matlab isfield emulation function Description There is no Scilab equivalent function for Matlab isfieldstf and equivalent expressions be have differently in some particular cases If st is not a structure Scilab equivalent returns an error message but Matlab returns 0 The function mtlbisfieldstf is used by mfile2sci to replace isfieldstf when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbisfield calls If st is a structure tf mtlbisfieldstf may be replaced by allfgetfield1sttforallf3f If st is not a structure tf mtlbisfieldstf may be replaced by tfF Caution mtlbisfield has not to be used for hand coded functions See Also getfield Authors VC 2008 Name mtlbisletter Matlab isletter emulation function Description There is no Scilab equivalent function for Matlab isletter and equivalent instructions are quite ugly so mfile2sci uses mtlbisletterA to replace isletterA If you want to have a more efficient code it is possible to replace mtlbisletter calls If A is not a character string tf mtlbisletterA may be replaced by tf zerosA If A is a character string tf mtlbisletterA may be replaced by tf asciimatA65asciimatA90 asciimatA97asciimatA122 Caution mtlbisletter has not to be used for hand coded functions Authors VC 2009 Name mtlbisspace Matlab isspace emulation function Description There is no Scilab function equivalent for Matlab isspace but its behavior can be reproduced The function mtlbisspaceA is used by mfile2sci to replace isspaceA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbisspace calls If A is a character string matrix mtlbisspaceA may be replaced by asciimatA32 If A is not a character string matrix mtlbisspaceA may be replaced by zerosA Caution mtlbisspace has not to be used for hand coded functions See Also asciimat Authors VC 2010 Name mtlbl Matlab left division emulation function Description Matlab and Scilab left division behave differently in some particular cases With character string operands The operator can not be used into Scilab with character strings while in Matlab it can And in this case result is transposed in a very strange way The function mtlblAB is used by mfile2sci to replace AB when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbl calls If both A and B are not character strings mtlblAB may be replaced by AB Caution mtlbl has not to be used for hand coded functions Authors VC 2011 Name mtlblegendre Matlab legendre emulation function P mtlblegendrenX P mtlblegendrenXnormflag Parameters X a scalar vector matrix or hypermatrix with elements in 11 n a positive scalar integer normflag a string sch or norm Description Matlab and Scilab legendre behave differently in some particular cases Scilab legendremnX evaluates the legendre function of degree n and order n for the X elements Matlab legendrenX evaluates the Legendre functions of degree n and order m01n emulated by mtlblegendre for the X elements The option normflag sch doesnt exist for Scilab legendre emulated If X is a hypermatrix then Scilab legendrenX doesnt work emulated The function mtlblegendrenXnormflag is used by mfile2sci to replace legendrenXnormflag when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblegendre call If X is a scalar a vector or a matrix mtlblegendrenXnorm may be replaced by legendren0nXnorm Caution mtlblegendre has not to be used for hand coded functions Authors FB 2012 Name mtlblinspace Matlab linspace emulation function Description Matlab and Scilab linspace behave differently in some particular cases With character string inputs Matlab linspaceABn returns a character string vector if A andor B are character strings but Scilab function does not work with such inputs The function mtlblinspaceABn is used by mfile2sci to replace linspaceABn when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblinspace calls If A and B are not character strings mtlblinspaceABn may be replaced by linspaceABn If A or B are character strings mtlblinspaceABn may be replaced by asciilinspaceasciiAasciiBn Caution mtlblinspace has not to be used for hand coded functions See Also ascii Authors VC 2013 Name mtlblogic Matlab logical operators emulation function Description Matlab and Scilab logical operator behave differently in some particular cases With complex operands The and operators can not be used into Scilab with complex operands while in Matlab they can And in this case only real part of complex operands is com pared With empty matrices If both operands of and operators are empty matrices Scilab returns an error message while Matlab returns an empty matrix For operators and if at least one operand is an empty matrix Matlab returns while Scilab returns a boolean value T or F The function mtlblogicAsymbolB with symbol a character string containing the oper ator symbol is used by mfile2sci to replace A symbol B when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblogic calls If both A and B are not complex values nor empty matrices mtlblogicAsymbolB may be replaced by A symbol B Caution mtlblogic has not to be used for hand coded functions Authors VC 2014 Name mtlblogical Matlab logical emulation function Description There is no Scilab equivalent function for Matlab logical but its behavior can be easyly reproduced The function mtlblogicalA is used by mfile2sci to replace logicalA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblogical calls If A is a boolean matrix mtlblogicalA may be replaced by A If A is not an empty matrix mtlblogicalA may be replaced by A If A is an empty matrix mtlblogicalA may be replaced by Caution mtlblogical has not to be used for hand coded functions Authors VC 2015 Name mtlblower Matlab lower emulation function Description Matlab lowerA and Scilab convstrAl behave differently in some particular cases If A is not a chacarter string matrix Matlab lower can be used with a notcharacterstring A but not Scilab convstr The function mtlblowerA is used by mfile2sci to replace lowerA when it was not pos sible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblower calls If A is a character string matrix mtlblowerA may be replaced by convstrAl If A is not a character string matrix mtlblowerA may be replaced by A Caution mtlblower has not to be used for hand coded functions See Also convstr Authors VC 2016 Name mtlbmax Matlab max emulation function Description Matlab and Scilab max behave differently in some particular cases With complex values Matlab max can be used with complex values but not Scilab function When called with one input Matlab max threats values along the first nonsingleton dimension but Scilab threats all input values When called with two inputs if one is an empty matrix Scilab returns an error message but Matlab returns When called with three inputs if dim parameter is greater than number of dimensions of first input Scilab returns an error message and Matlab returns the first input The function rk mtlbmaxABdim is used by mfile2sci to replace rk maxABdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbmax calls When called with one input if A is a vector or a scalar rk mtlbmaxA may be replaced by maxA When called with one input if A is a matrix rk mtlbmaxA may be replaced by maxAr When called with two inputs if A and B are real matrices and not empty matrices rk mtlbmaxAB may be replaced by maxAB When called with three inputs if dim is lesser than the number of dimensions of A rk mtlbmaxAdim may be replaced by maxAdim Caution mtlbmax has not to be used for hand coded functions See Also firstnonsingleton Authors VC 2017 Name mtlbmin Matlab min emulation function Description Matlab and Scilab min behave differently in some particular cases With complex values Matlab min can be used with complex values but not Scilab function When called with one input Matlab min threats values along the first nonsingleton dimension but Scilab threats all input values When called with two inputs if one is an empty matrix Scilab returns an error message but Matlab returns When called with three inputs if dim parameter is greater than number of dimensions of first input Scilab returns an error message and Matlab returns the first input The function rk mtlbminABdim is used by mfile2sci to replace rk minABdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbmin calls When called with one input if A is a vector or a scalar rk mtlbminA may be replaced by minA When called with one input if A is a matrix rk mtlbminA may be replaced by minAr When called with two inputs if A and B are real matrices and not empty matrices rk mtlbminAB may be replaced by minAB When called with three inputs if dim is lesser than the number of dimensions of A rk mtlbminAdim may be replaced by minAdim Caution mtlbmin has not to be used for hand coded functions See Also firstnonsingleton Authors VC 2018 Name mtlbmore Matlab more emulation function Description Matlab more and Scilab lines behave differently in some particular cases With character strings as input Matlab more can take on and off as input but not Scilab lines but there are equivalents 0 and 60 The function mtlbmorein is used by mfile2sci to replace morein when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbmore calls If in is equal to on mtlbmorein may be replaced by lines60 If in is equal to off mtlbmorein may be replaced by lines0 If in is a double value mtlbmorein may be replaced by linesin Caution mtlbmore has not to be used for hand coded functions Authors VC 2019 Name mtlbnum2str Matlab num2str emulation function Description Matlab num2str and Scilab equivalents string msprintf behave differently in some partic ular cases With two input parameters the second giving precision There is no Scilab equivalent function but msprintf can be used to emulate With two input parameters the second giving format Scilab equivalent for Matlab num2stringaformat is msprintfformata The function mtlbnum2strxf is used by mfile2sci to replace num2strxf when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbnum2str calls If f is a character string mtlbnum2strxf may be replaced by msprintffx Caution mtlbnum2str has not to be used for hand coded functions See Also string msprintf Authors VC 2020 Name mtlbones Matlab ones emulation function Description Matlab and Scilab ones behave differently in some particular cases With a scalar input Matlab ones returns a n x n matrix while Scilab returns a 1 The function mtlbonesA is used by mfile2sci to replace onesA when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbones calls If A is a scalar mtlbonesA may be replaced by onesAA If A is not a scalar mtlbonesA may be replaced by onesA Caution mtlbones has not to be used for hand coded functions Authors VC 2021 Name mtlbplot Matlab plot emulation function Description Matlab plot and Scilab plot2d behave differently The function mtlbplotvarargin is used by mfile2sci to replace plotvarargin when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbplot calls when there is no output value however in this case you have to set colors manualy With one input if Y is real mtlbplotY may be replaced by plot2dY With one input if Y is complex mtlbplotY may be replaced by plot2drealYimagY With two inputs X and Y if Y is not a character string mtlbplotXY may be replaced by plot2dXY Caution mtlbplot has not to be used for hand coded functions See Also plot2d Authors VC 2022 Name mtlbprod Matlab prod emulation function Description Matlab and Scilab prod behave differently in some particular cases When called with one input Matlab prod threts the values along the first nonsingleton dimension of input while Scilab prod threats all values of input When called with two inputs Matlab prod can be used with second input giving a nonexisting dimension of first input while Scilab prod returns an error message The function mtlbprodAdim is used by mfile2sci to replace prodAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbprod calls When called with one input if A is an empty matrix a scalar or a vector mtlbprodA may be replaced by prodA When called with one input if A is a notempty matrix mtlbprodA may be replaced by prodA1 When called with one input if A is a multidimensional array mtlbprodA may be replaced by prodAfirstnonsingletonA When called with two inputs if dim is lesser than the number of dimensions of A mtlbprodAdim may be replaced by prodAdim Caution mtlbprod has not to be used for hand coded functions See Also firstnonsingleton Authors VC 2023 Name mtlbrand Matlab rand emulation function Description Matlab and Scilab rand behave differently in some particular cases With a scalar input Matlab rand returns a n x n matrix while Scilab returns a scalar The function mtlbrandA is used by mfile2sci to replace randA when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrand calls If A is a scalar mtlbrandA may be replaced by randAA If A is not a scalar mtlbrandA may be replaced by randA Caution mtlbrand has not to be used for hand coded functions Authors VC 2024 Name mtlbrandn Matlab randn emulation function Description Matlab rand and Scilab randnormal behave differently in some particular cases With a scalar input Matlab randn returns a n x n matrix while Scilab randnormal returns a scalar The function mtlbrandnA is used by mfile2sci to replace randnA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrandn calls If A is a scalar mtlbrandnA may be replaced by randAAnormal If A is not a scalar mtlbrandnA may be replaced by randAnormal Caution mtlbrandn has not to be used for hand coded functions Authors VC 2025 Name mtlbrcond Matlab rcond emulation function Description Matlab and Scilab rcond behave differently in some particular cases With empty matrix Matlab rcond returns Inf and Scilab rcond returns The function mtlbrcondA is used by mfile2sci to replace rcondA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrcond calls If A is not an empty matrix mtlbrcondA may be replaced by rcondA Caution mtlbrcond has not to be used for hand coded functions Authors VC 2026 Name mtlbrealmax Matlab realmax emulation function Description Scilab equivalent for Matlab realmax is numberproperties but not all cases are implemented Scilab equivalent for Matlab realmax or realmaxdouble is numberpropertieshuge There is no Scilab equivalent for Matlab realmaxsingle The function mtlbrealmaxprec is used by mfile2sci to replace realmaxprec when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrealmax calls If prec is equal to double mtlbrealmaxprec may be replaced by numberpropertieshuge Caution mtlbrealmax has not to be used for hand coded functions See Also numberproperties Authors VC 2027 Name mtlbrealmin Matlab realmin emulation function Description Scilab equivalent for Matlab realmin is numberproperties but not all cases are implemented Scilab equivalent for Matlab realmin or realmindouble is numberpropertiestiny There is no Scilab equivalent for Matlab realminsingle The function mtlbrealminprec is used by mfile2sci to replace realminprec when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrealmin calls If prec is equal to double mtlbrealminprec may be replaced by numberpropertiestiny Caution mtlbrealmin has not to be used for hand coded functions See Also numberproperties Authors VC 2028 Name mtlbrepmat Matlab repmat emulation function Description There is no Scilab equivalent function for Matlab repmat but there are equivalent instructions The function mtlbrepmatMmn is used by mfile2sci to replace repmatMmn when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrepmat calls If A is of Double type and m is a scalar mtlbrepmatMm may be replaced by onesmmM and mtlbrepmatMmn may be replaced by onesmnM If A is of Boolean type and m is a scalar mtlbrepmatMm may be re placed by onesmmbool2sM and mtlbrepmatMmn may be replaced by onesmnbool2sM If A is of String type and m is a scalar mtlbrepmatMm may be replaced by asciimatonesmmasciimatM and mtlbrepmatMmn may be replaced by asciimatonesmnasciimatM If A is of Double type and m is a vector mtlbrepmatMm may be replaced by onesm1m2M If A is of Boolean type and m is a vector mtlbrepmatMm may be replaced by onesm1m2bool2sM If A is of String type and m is a vector mtlbrepmatMm may be replaced by asciimatonesm1m2asciimatM Caution mtlbrepmat has not to be used for hand coded functions See Also ones kron Authors VC 2029 Name mtlbs Matlab substraction emulation function Description Matlab and Scilab substraction behave differently in some particular cases With character string operands The operator can not be used into Scilab with character strings while Matlab realizes the substraction of the operands ASCII codes With empty matrix In Scilab if one of the operands is an empty matrix the result of the substraction is the other operand In Matlab if one of the operand is an empty matrix the result of the substraction should be an error or an empty matrix The function mtlbsAB is used by mfile2sci to replace AB when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbs calls If A and B are character strings mtlbsAB may be replaced by asciimatA asciimatB If both A and B are not empty matrices mtlbsAB may be replaced by AB else mtlbsAB may be replaced by If mtlbmodeT then mtlbsAB may be replaced by AB in any case where A and B are not character string matrices Caution mtlbs has not to be used for hand coded functions See Also mtlbmode Authors VC 2030 Name mtlbsetstr Matlab setstr emulation function Description Matlab setstr and Scilab ascii behave differently in some particular cases With character string input Matlab setstr returns a character string while Scilab ascii returns ASCII codes With double matrix input Matlab setstr returns a character matrix having the same size as input while Scilab ascii returns a single character string The function mtlbsetstrA is used by mfile2sci to replace setstrA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbsetstr calls If A is a character string or a character string matrix mtlbsetstrA may be replaced by A If A is a double row vector mtlbsetstrA may be replaced by asciiA Caution mtlbsetstr has not to be used for hand coded functions Authors VC 2031 Name mtlbsize Matlab size emulation function Description Matlab and Scilab size behave differently in some particular cases With two inputs Matlab size can be used with second parameter giving a notexisting dimension of first parameter returns 1 in this case but not Scilab one With more than one output if number of output is lesser than number of dimensions last output is the product of all remaining dimensions in Matlab but not in Scilab If number of output is greater than number of dimensions outputs corresponding to a notexisting dimension are set to 1 in Matlab but Scilab gives an error in this case The function d1d2 mtlbsizeXdim is used by mfile2sci to replace d1d2 sizeXdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbsize calls With two inputs if dim gives an existing dimension of X mtlbsizeXdim may be replaced by sizeXdim With more than one outputs if the number of outputs is equal to the number of dimensions of X d1d2 mtlbsizeX may be replaced by d1d2 sizeX Caution mtlbsize has not to be used for hand coded functions Authors VC 2032 Name mtlbsort Matlab sort emulation function P mtlbsortX P mtlbsortXdimmode Parameters X a scalar vector matrix of reals booleans or a string dim a positive scalar integer mode a string ascend or descend Description Matlab sort and Scilab gsort behave differently in some particular cases For a vector X the Matlab sortXgi function call is equivalent to the Scilab gsortX function call The value 1 resp 2 of the Matlab dim is equivalent to the Scilab r flag resp c The Matlab ascend resp descend mode is equivalent to the Scilab i resp d flag The function mtlbsortXdimmode is used by mfile2sci to replace sortXdimmode when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbsort call by gsort call Caution mtlbsort has not to be used for hand coded functions Authors FB 2033 Name mtlbstrcmp Matlab strcmp emulation function Description There is no Scilab function equivalent for Matlab strcmp there is equivalent instructions The function mtlbstrcmpAB is used by mfile2sci to replace strcmpAB when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbstrcmp calls If A and B are character strings mtlbstrcmpAB may be replaced by AB If A andor B is not a character string mtlbstrcmpAB may be replaced by 0 Caution mtlbstrcmp has not to be used for hand coded functions Authors VC 2034 Name mtlbstrcmpi Matlab strcmpi emulation function Description There is no Scilab function equivalent for Matlab strcmpi there is equivalent instructions The function mtlbstrcmpiAB is used by mfile2sci to replace strcmpiAB when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbstrcmpi calls If A and B are character strings mtlbstrcmpiAB may be replaced by convstrAconvstrB If A andor B is not a character string mtlbstrcmpiAB may be replaced by 0 Caution mtlbstrcmpi has not to be used for hand coded functions Authors VC 2035 Name mtlbstrfind Matlab strfind emulation function Description Matlab strfind and Scilab strindex behave differently in some particular cases With inputs which not character strings Matlab strfind can be used with not character strings inputs but not Scilab strindex The function mtlbstrfindAB is used by mfile2sci to replace strfindAB when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbstrfind calls If A and B are character strings mtlbstrfindAB may be replaced by strindexAB Caution mtlbstrfind has not to be used for hand coded functions Authors VC 2036 Name mtlbstrrep Matlab strrep emulation function Description Matlab strrep and Scilab strsubst behave differently in some particular cases With inputs which not character strings Matlab strrep can be used with not character strings inputs but not Scilab strsubst The function mtlbstrrepABC is used by mfile2sci to replace strrepABC when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbstrrep calls If A B and C are character strings mtlbstrrepABC may be replaced by strsubstABC Caution mtlbstrrep has not to be used for hand coded functions Authors VC 2037 Name mtlbsum Matlab sum emulation function Description Matlab and Scilab sum behave differently in some particular cases When called with one input Matlab sum threts the values along the first nonsingleton dimension of input while Scilab sum threats all values of input When called with two inputs Matlab sum can be used with second input giving a nonexisting dimension of first input while Scilab sum returns an error message The function mtlbsumAdim is used by mfile2sci to replace sumAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbsum calls When called with one input if A is an empty matrix a scalar or a vector mtlbsumA may be replaced by sumA When called with one input if A is a notempty matrix mtlbsumA may be replaced by sumA1 When called with one input if A is a multidimensional array mtlbsumA may be replaced by sumAfirstnonsingletonA When called with two inputs if dim is lesser than the number of dimensions of A mtlbsumAdim may be replaced by sumAdim Caution mtlbsum has not to be used for hand coded functions See Also firstnonsingleton Authors VC 2038 Name mtlbt Matlab transposition emulation function Description Matlab and Scilab transposition behave differently in some particular cases With character strings operands The operator is used to transpose whole character strings in Scilab while Matlab realizes the transposition of each character The function mtlbtA is used by mfile2sci to replace A when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbt calls If A is not a character string matrix mtlbtA may be replaced by A Caution mtlbt has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 2039 Name mtlbtoeplitz Matlab toeplitz emulation function Description Matlab and Scilab toeplitz behave differently in some particular cases With one input parameter if this parameter is complex or is a matrix output value of Matlab and Scilab toeplitz can be different With two input parameters if they are vectors and their first elements are not equal Scilab returns an error but Matlab gives priority to the column element If they are matrices output value of Matlab and Scilab toeplitz are different The function mtlbtoeplitzcr is used by mfile2sci to replace toeplitzcr when it was not possible to know what were the operandsinputsCUSTOM while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbtoeplitz calls When called with one input if c is a real scalar or vector mtlbtoeplitzc may be replaced by toeplitzc When called with two inputs if c and r are scalars or vectors and their first elements are equal mtlbtoeplitzcr may be replaced by toeplitzcr Caution mtlbtoeplitz has not to be used for hand coded functions Authors VC 2040 Name mtlbtril Matlab tril emulation function Description Matlab and Scilab tril behave differently in some particular cases With complex input Matlab tril can be used with complex data but not Scilab one With character strings inputs due to the fact the Matlab and Scilab do not consider character strings in the same way Scilab and Matlab tril do not give the same results for this type of input With boolean inputs Matlab tril can be used with boobean data but not Scilab one The function mtlbtrilxk is used by mfile2sci to replace trilxk when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbtril calls If X contains real double values mtlbtrilxk may be replaced by trilxk If X contains boolean values mtlbtrilxk may be replaced by trilbool2sxk Caution mtlbtril has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 2041 Name mtlbtriu Matlab triu emulation function Description Matlab and Scilab triu behave differently in some particular cases With complex input Matlab triu can be used with complex data but not Scilab one With character strings inputs due to the fact the Matlab and Scilab do not consider character strings in the same way Scilab and Matlab triu do not give the same results for this type of input With boolean inputs Matlab triu can be used with boobean data but not Scilab one The function mtlbtriuxk is used by mfile2sci to replace triuxk when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbtriu calls If X contains real double values mtlbtriuxk may be replaced by triuxk If X contains boolean values mtlbtriuxk may be replaced by triubool2sxk Caution mtlbtriu has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 2042 Name mtlbtrue Matlab true emulation function Description There is no Scilab equivalent for Matlab true However Scilab ones returns a result interpreted in an equivalent way for Scilab Matlab true and Scilab ones behave differently in some particular cases With a scalar input Matlab true returns a n x n matrix of ones while Scilab ones returns a 1 The function mtlbtrueA is used by mfile2sci to replace trueA when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbtrue calls If A is a scalar mtlbtrueA may be replaced by onesAA If A is not a scalar mtlbtrueA may be replaced by onesA Caution mtlbtrue has not to be used for hand coded functions Authors VC 2043 Name mtlbuint16 Matlab uint16 emulation function Description Matlab and Scilab uint16 behave differently in some particular cases With complex input Matlab uint16 can be used with complex values what Scilab function can not With inf Matlab uint16 returns 65535 and Scilab returns 0 The function mtlbuint16A is used by mfile2sci to replace uint16A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbuint16 calls If A does not contain inf values mtlbuint16A may be replaced by uint16A Caution mtlbuint16 has not to be used for hand coded functions Authors VC 2044 Name mtlbuint32 Matlab uint32 emulation function Description Matlab and Scilab uint32 behave differently in some particular cases With complex input Matlab uint32 can be used with complex values what Scilab function can not With inf Matlab uint32 returns 4294967295 and Scilab returns 0 The function mtlbuint32A is used by mfile2sci to replace uint32A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbuint32 calls If A does not contain inf values mtlbuint32A may be replaced by uint32A Caution mtlbuint32 has not to be used for hand coded functions Authors VC 2045 Name mtlbuint8 Matlab uint8 emulation function Description Matlab and Scilab uint8 behave differently in some particular cases With complex input Matlab uint8 can be used with complex values what Scilab function can not With inf Matlab uint8 returns 255 and Scilab returns 0 The function mtlbuint8A is used by mfile2sci to replace uint8A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbuint8 calls If A does not contain inf values mtlbuint8A may be replaced by uint8A Caution mtlbuint8 has not to be used for hand coded functions Authors VC 2046 Name mtlbupper Matlab upper emulation function Description Matlab upperA and Scilab convstrAu behave differently in some particular cases If A is not a chacarter string matrix Matlab upper can be used with a notcharacterstring A but not Scilab convstr The function mtlbupperA is used by mfile2sci to replace upperA when it was not pos sible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbupper calls If A is a character string matrix mtlbupperA may be replaced by convstrAu If A is not a character string matrix mtlbupperA may be replaced by A Caution mtlbupper has not to be used for hand coded functions See Also convstr Authors VC 2047 Name mtlbvar Matlab var emulation function Parameters x a real or a complex vector or matrix s a real scalar or real vector If x is a vector s is the variance of x If x is a matrix s is a row vector containing the variance of each column of x w type of normalization to use Valid values are depending on the number of columns m of x w 0 normalizes with m1 provides the best unbiased estimator of the variance this is the default w 1 normalizes with m this provides the second moment around the mean dim the dimension along which the variance is computed default is 1 ie column by column If dim is 2 the variance is computed row by row Description This function computes the variance of the values of a vector or matrix x It provides the same service as Octave and Matlab It differs from Scilabs variance primitive mtlbvar returns a real ie with a zero imaginary part variance even if x is a complex vector or matrix The Scilab variance primitive returns a complex value if the input vector x is complex and if no option additionnal is used Whatever the type of the input data x ie vector or matrix mtlbvar computes the variance either on dimension 1 or on dimension 2 while if no option is passed to the Scilabs variance primitive the variance is computed on all dimension at once Examples The following 3 examples illustrates the use of the mtlbvar function In the first case a column vector is passed to the function which returns the value 750 In the second case a matrix is passed to the function which returns the row vector 016 009 In the third case a complex column vector is passed to the function which returns a value close to 2 x 10 20 30 40 50 60 70 80 90 computed mtlbvarx x 09 07 01 01 05 04 computed mtlbvarx N1000 x grandN1nor01 igrandN1nor01 mtlbvar 2048 computed mtlbvarx See Also variance Authors Michael Baudin 2049 Name mtlbzeros Matlab zeros emulation function Description Matlab and Scilab zeros behave differently in some particular cases With a scalar input Matlab zeros returns a n x n matrix while Scilab returns a 0 The function mtlbzerosA is used by mfile2sci to replace zerosA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbzeros calls If A is a scalar mtlbzerosA may be replaced by zerosAA If A is not a scalar mtlbzerosA may be replaced by zerosA Caution mtlbzeros has not to be used for hand coded functions Authors VC Parte XXXVII Interface Java 2051 Name javasciSciBoolean Class to use boolean object with scilab Description Method Summary public SciBooleanString nameSciBoolean Obj public SciBooleanString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public SciBooleanString nameboolean Value public String getNameGet Name of scilab object public boolean getDataGet Value of scilab object public void GetGet in java object value of scilab object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void SendSend to scilab object value of java object public void dispdisp object Examples See SCImodulesjavasciexamples directory See Also javasciScilab Compile and run with Javasci SciBooleanArray SciDoubleArray SciString SciStringArray Authors AC 2053 Name javasciSciBooleanArray Class to use boolean matrix in Scilab Description Method Summary public SciBooleanArrayString nameSciBooleanArray Obj public SciBooleanArrayString nameint rint c public SciBooleanArrayString nameint rint cboolean x Constructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public boolean getData Get Value of scilab object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void GetGet in java object value of scilab object public void SendSend to scilab object value of java object public boolean GetElementint indr int indcGet a specific element of scilab object Examples javasciSciBooleanArray 2054 See SCImodulesjavasciexamples directory See Also javasciScilab Compile and run with Javasci SciBoolean SciDouble SciString SciStringArray Authors AC 2055 Name javasciSciComplex Class to use complex object with scilab Description Method Summary public SciComplexString nameSciComplex Obj public SciComplexString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public SciComplexString namedouble realpartdouble imaginary part Constructor public String getNameGet Name of scilab object public double getRealPartDataGet Real Part Value of scilab object public double getImaginaryPartDataGet Imaginary Part Value of scilab object public void GetGet in java object value of scilab object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void SendSend to scilab object value of java object public void dispdisp object javasciSciComplex 2056 public void toStringconvert complex to a string Examples See SCImodulesjavasciexamples directory See Also javasciScilab Compile and run with Javasci SciComplexArray SciString SciStringArray Sci DoubleArray SciDouble Authors AC 2057 Name javasciSciComplexArray Class to use complex matrix in Scilab javasciSciComplexArray 2058 Description javasciSciComplexArray 2059 Method Summary public SciComplexArrayString nameSciComplexArray Obj public SciComplexArrayString nameint rint c public SciComplexArrayString nameint rint cdouble realpartdouble imaginarypartConstructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public double getRealPartDataGet Real Part Value of scilab object public double getImaginaryPartDataGet Imaginary Part Value of scilab object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void GetGet in java object value of scilab object public void SendSend to scilab object value of java object public double GetRealPartElementint indr int indcGet a specific element of scilab object public double GetImaginaryPartElementint indr int indcGet a specific element of scilab object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciComplex SciDouble SciDoubleArray SciString SciStringArray Authors AC 2060 Name javasciSciDouble Class to use double object with scilab Description Method Summary public SciDoubleString nameSciDouble Obj public SciDoubleString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public SciDoubleString namedouble Value public String getNameGet Name of scilab object public double getDataGet Value of scilab object public void GetGet in java object value of scilab object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void SendSend to scilab object value of java object public void dispdisp object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciDoubleArray SciString SciStringArray Authors AC 2062 Name javasciSciDoubleArray Class to use real matrix in Scilab Description Method Summary public SciDoubleArrayString nameSciDoubleArray Obj public SciDoubleArrayString nameint rint c public SciDoubleArrayString nameint rint cdouble x Constructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public double getData Get Value of scilab object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void GetGet in java object value of scilab object public void SendSend to scilab object value of java object public double GetElementint indr int indcGet a specific element of scilab object Examples javasciSciDoubleArray 2063 See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciDouble SciString SciStringArray Authors AC 2064 Name javasciSciInteger Class to use integer object with scilab Description Method Summary public SciIntegerString nameSciInteger Obj public SciIntegerString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public SciIntegerString nameint Value public String getNameGet Name of scilab object public int getDataGet Value of scilab object public void GetGet in java object value of scilab object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void SendSend to scilab object value of java object public void dispdisp object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciIntegerArray SciString SciStringArray Authors AC 2065 Name javasciSciIntegerArray Class to use int matrix in Scilab Description Method Summary public SciIntegerArrayString nameSciIntegerArray Obj public SciIntegerArrayString nameint rint c public SciIntegerArrayString nameint rint cint x Constructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public int getData Get Value of scilab object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void GetGet in java object value of scilab object public void SendSend to scilab object value of java object public int GetElementint indr int indcGet a specific element of scilab object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciInteger SciString SciStringArray Authors AC 2066 Name javasciSciString Map a Java String into a Scilab string Description Method Summary public SciStringString nameSciString Obj public SciStringString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public String getNameGet Name of scilab object public void GetGet in java object value of scilab object public String getData Get Value of scilab object public void SendSend to scilab object value of java object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciDouble SciDoubleArray SciStringArray Authors AC 2068 Name javasciSciStringArray Classe to use String matrix in Scilab Description Method Summary public SciDoubleArrayString nameSciDoubleArray Obj public SciStringArrayString nameint rint c public SciStringArrayString nameint rint cString x Constructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public String getDataGet Value of scilab object public void Get Get in java object value of scilab object public void Send Send to scilab object value of java object public void disp disp object javasciSciStringArray 2069 public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public String GetElementint indr int indcGet a specific element of scilab object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciDouble SciDoubleArray SciString Authors AC 2070 Name javasciScilab This class provides the basic methods to execute Scilab code and scripts Description This class is static Since the Scilab environnement is persistant all variables will remain accessible with the Java application Method Summary public static void Events Execute a Scilab event public static boolean HaveAGraph Check if there is any scilab graphic window open return True if it is the case public static boolean ExecString job Execute a job in scilab return true if there is no error Note that the given expression must be consistent by itself Then a serie of Exec defining a function will not work Please consider calling it with a single string instruction or using a temporary file with the method ExecuteScilabScript For example ScilabExecfunction foo dispbar end function will work when ScilabExecfunction foo ScilabExecdispbar ScilabExecendfunction will not work since each statement being processed independently public static native boolean ExistVarString VarName Detect if VarName exists in Scilab return true if Varname exist public static native int TypeVarString VarName Return Scilab type of VarName See type public static native int GetLastErrorCode Return last Error code See lasterror public static boolean ExecuteScilabScriptString scilabscriptfile name Execute a scilab script sce return true if there is no error public static native boolean Finish Terminate scilab call scilabquit close a scilab object Examples A Scilab Java example Filename ScilabExamplejava import javasciScilab public class ScilabExample public static void mainString args String myVarmyVariable ScilabExecmyVarpi490dispmyVariable Simple display if ScilabExistVarmyVar SystemoutprintlnVariable myVar exists Type ScilabTypeVarmyVar if ScilabExecdispplop Error javasciScilab 2071 SystemerrprintlnLast error ScilabGetLastErrorCode Error ScilabFinish See Also Compile and run with Javasci SciDouble SciDoubleArray SciString SciStringArray type lasterror Authors AC 2072 Name Compile and run with javasci How to compile a Java application using Javasci Description To compile a Java code based on Javasci it is only necessary to have javascijar defined in the class path For example with the code defined in the example of this page the command would be on LinuxUnixMacOSX javac cp SCImodulesjavascijarjavascijar BasicExamplejava on Windows D javac cp SCImodulesjavascijarjavascijar BasicExamplejava To run Scilab there are a few other things to set up Some global variables must me set SCI Path to Scilab files LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilabsharescilab In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabsource tree Windows path of scilab root directory set SCICprogram filesscilab51 LDLIBRARYPATH Paths to libscilabso and libjavasciso or jnilib LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilablibscilab In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabmod ulesjavascilibs and pathtoscilablibs Windows Path to libscilabdll and javascidll equivalent to LDLIBRARYPATH on Windows is PATH set PATHSCIbinPATH To launch the Java Application you can either provide them with environnement variable LinuxUnixMacOSX LDLIBRARYPATHpathtolibjavasci SCIpathtoscilab java cp modulesjavascijarjavascijar BasicExample SCIpathtoscilab java Djavalibrarypathpathtolibjavas ci cp modulesjavascijarjavascijar BasicExample Compile and run with javasci 2073 or with the arguments Windows set SCIcprogram filesscilab51 set PATHSCIbinPATH Djava cp SCImodulesjavascijarjavascijar BasicExample optional options to launch java DjavacompilerJIT Xmx256m With these arguments you launch javasci with same initial options that standard scilab Note that two environnement variables are taken in account for specific needs SCIDISABLETK1 Disables Tk Tcls GUI SCIJAVAENABLEHEADLESS1 Launch Java in headless mode no AWTSwing Examples A simple Java example Filename BasicExamplejava import javasciScilab public class BasicExample public static void mainString args ScilabExecdisppi26 See Also Javasci Javasci FAQ SciDouble SciDoubleArray SciString SciStringArray Authors Allan Cornet Sylvestre Ledru 2074 Name javasci Call Scilab engine from a Java application Description Scilab offers the possibility to be called from a Java application This help describes the features of the javasci API Examples A simple Java example Filename DisplayPIjava import javasciScilab public class DisplayPI public static void mainString args ScilabExecdisppi See Also Compile and run with Javasci Javasci FAQ SciDouble SciDoubleArray SciString SciStringArray Authors Allan Cornet Sylvestre Ledru 2075 Name javasci FAQ The frequently asked questions Questions Answers 1 Running an application based on javasci I get the error Exception in thread main javalangNoClassDefFoundError javasciScilab javascijar is probably not defined in the CLASSPATH See See Also Javasci Compile and run with javasci Authors Sylvestre Ledru Parte XXXVIII Interface Maple 2077 Name sci2map Scilab to Maple variable conversion txtsci2mapaMapname Parameters a Scilab object matrix polynomial list string Mapname string name of the Maple variable txt vector of strings containing the corresponding Maple code Description Makes Maple code necessary to send the Scilab variable a to Maple the name of the variable in Maple is Mapname A Maple procedure maple2scilab can be found in SCIDIRmaple directory Examples txtsci2map1 23 4a sci2maps23s4p Parte XXXIX Dicas de Conversão de Matlab para Scilab 2079 Name AboutM2SCItools Generally speaking about tools to convert Matlab files to Scilab Description Scilab 30 includes a new version of useful tools to convert Matlab Mfiles to Scilab Taking a Matlab Mfile mfile2sci modifies this files so that it can be compiled by Scilab After that this compiled code is converted to a tree of instructions by macr2tree This tree is an imbrication of Scilab lists and tlists and is the basis for conversion Each instruction of this tree is converted to Scilab and inference is done to known what are the variables Once this tree is converted to Scilab code is generated using tree2code All tlists used for coding this tree and we call MSCI tlists are listed below funcall tlist representing a function call created by Funcall operation tlist representing an operation created by Operation variable tlist representing a variable created by Variable cste tlist representing a constant created by Cste equal tlist representing an instruction created by Equal ifthenelse tlist representing an IFTHENELSE control instruction created inside M2SCI kernel functions while tlist representing a WHILE control instruction created inside M2SCI kernel functions selectcase tlist representing a SELECTCASE control instruction created inside M2SCI kernel functions for tlist representing a FOR control instruction created inside M2SCI kernel functions The contents of these tlists is described in corresponding help pages Operations are converted using a fonction named opcode2sci with opcode the Scilab code for this operator See help page for overloading to have these codes All these functions are already written and are in directory SCImodulesm2scimacrospercent Function calls are converted using a function called sciMatlabfunctionname Some of these functions have been written and are in directory SCImodulesm2scimacrosscifiles We are working on increasing the set of Matlab functions converted However everybody can written such functions using help page scifiles Inference is done using tlists of type infer containing fields dims list of dimensions type type tlist AboutM2SCItools 2080 contents contents tlist if a Cell or a Struct Type is a tlist of type type containing fields vtype data type property property To have more details about inference see help page for m2scideclare See Also mfile2sci translatepaths overloading scifiles Funcall Operation Variable Cste Infer Type Equal m2scideclare Authors VC 2081 Name Contents Create a tree containing contents inference data contentsContentslistofindexlistofinfer Parameters listofindex list of indexes similar to indexes returned by macr2tree listofinfer list of infer tlists containing inference data for matching index contents a contents tlist Description This function create a tlist representing inference data for the contents of a Cell or a Struct when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists Un known1 in M2SCI Please ensure that for each entry you insert in listofindex you also insert an entry in listofinfer See Also getcontentsinfer Funcall Operation Variable Cste Infer Type Equal Authors VC 2082 Name Cste Create a tree representing a constant constCstevalue Parameters value constante value const a cste tlist Description This function create a tlist representing a constant when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Funcall Operation Variable Infer Contents Type Equal Authors VC 2083 Name Equal Create a tree representing an instruction eqEquallhslistexpression Parameters lhslist list of lhs parameters list of M2SCI tlists expression right member of equal an M2SCI tlist eq an equal tlist Description This function create a tlist representing an instruction when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Funcall Operation Variable Cste Infer Contents Type Authors VC 2084 Name Funcall Create a tree representing a function call fcFuncallnamelhsnbrhslistlhslist Parameters name function name character string lhsnb number of outputs constant rhslist list of inputs list of M2SCI tlists lhslist list of outputs list of M2SCI tlists fc a funcall tlist Description This function create a tlist representing a function call when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Operation Variable Cste Infer Contents Type Equal Authors VC 2085 Name Infer Create a tree containing inference data inferInfervarargin Parameters varargin data for inference varargin1 list of dimensions default value is listUnknownUnknown varargin2 type type tlist see Type help page default value is TypeUnknownUnknown varargin3 contents contents tlist see Contents help page default value is Contentslistlist This field is only used if represented data is a Cell or a Struct infer an infer tlist Description This function create a tlist representing inference data when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists Unknown1 in M2SCI See Also Funcall Operation Variable Cste Contents Type Equal Authors VC 2086 Name MatlabScilabcharacterstrings Generally speaking about Description Matlab and Scilab character strings are not considered in the same way Here is a little talk about differences between them Matlab considers a character string as Scilab considers a matrix of characters For example a Scilab equivalent for Matlab mystring could be mystring So in Scilab a character string is a object of type string 10 and always have size 1 x 1 but in Matlab a character string have size equal to 1 x numberofcharacters Considering this we can see that a Matlab character string matrix column can only be made of same size character strings what is not true in Scilab We can say that a Scilab character string matrix is equivalent to a Matlab cell of character strings All these differences can lead to different results while executing same commands in Scilab or in Matlab particularly for dimension functions such as length or size See Also mstr2sci Authors VC 2087 Name Operation Create a tree representing an operation opOperationoperatoroperandsout Parameters operator operator symbol character string operands list of operands list of M2SCI tlists out list of outputs list of M2SCI tlists op an operation tlist Description This function create a tlist representing an operation when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Funcall Variable Cste Infer Contents Type Equal Authors VC 2088 Name Type Create a tree containing type inference data tpTypevtypeproperty Parameters vtype data type see m2scideclare property property of data see m2scideclare tp a type tlist Description This function create a tlist representing type inference data when using M2SCI All input param eters values are verified to be compatible with M2SCI tlists Unknown1 in M2SCI See Also Funcall Operation Variable Cste Infer Contents Equal m2scideclare Authors VC 2089 Name Variable Create a tree representing a variable varVariablenameinfer Parameters var variable name character string infer inference data a tlist of type infer see Infer help page var a variable tlist Description This function create a tlist representing a variable when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Funcall Operation Cste Infer Contents Type Equal Authors VC 2090 Name getcontentsinfer Search for information in a M2SCi tlist contents inferposgetcontentsinferm2scitlistindex Parameters m2scitlist a M2SCI tlist index an index similar to indexes returned by macr2tree infer an infer tlist pos position of information in list Description This functions searches for inference informations of a given index in the contents of a Cell or a Struct taken in account the If no information has been found returned values are inferinfer and pos0 See Also Infer Contents Authors VC 2091 Name m2scideclare Giving tips to help M2SCI Description The main difficulty for M2SCI mfile2sci is to find what variables are dimensions type To help this tool just add comments beginning with m2scideclare in the Mfile to convert m2sciassume was used in previous Scilab versions and is now obsolete The syntax of this command is m2scideclare variablenamedimensionsdatatypeproperty with variablename name of the variable declared It can be a Struct field eg x12name or describe the contents of a Cell using syntax x12entries NOTE that for Cells and Structs can be used as an index see examples below dimensions dimensions of the variable declared separated by blanks if a dimension is unknown replace it by NOTE that String dimensions must be similar to Matlab ones eg 1 6 for character string string datatype data type of the variable which can be m2scideclare data type Scilab equivalent type Double 1 Boolean 4 Sparse 5 Int 8 Handle 9 String 10 Struct Matlab struct 16 Cell Matlab cell 17 Void No type 0 Unknown type property property of the variable which can be m2scideclare property Scilab equivalent Real Real data Complex Complex data Unknown property This field is ignored for following datatypes Cell Struct String and Boolean All data given by m2scideclare are compared with infered data in case of conflict infered data are kept and a warning message is displayed If you are sure about your data report a bug Some examples are given below m2scideclare var12 3DoubleRealvar1 is declared as a 2x3 Double matrix con taining real data m2scideclare 2092 m2scideclare var22 3 10DoubleComplexvar2 is declared as a 2x3x10 Double hypermatrix containing complex data m2scideclare var312name1 10Stringvar3 is declared as a Struct array containing a 1x10 character string in field name of struct at index 12 m2scideclare var415entries1 Booleanvar4 is declared as a Cell con taining a row boolean vector at index 15 m2scideclare var416entries Intvar4 is declared as a Cell containing a row boolean vector at index 15 and integer data at index 16 m2scideclare var5name1 Stringvar5 is declared as a Struct array containing a 1xn character string in all fields name m2scideclare var62entries1 3DoubleRealvar6 is declared as a Cell array containing a 1x3 double vector in each element of its second row Authors VC 2093 Name matfile2sci converts a Matlab 5 MATfile into a Scilab binary file matfile2scimatfilepathscifilepath Parameters matfilepath character string containing the path of the Matlab input file scifilepath character string containing the path of the Scilab output file Description Converts a Matlab 5 MATfile into a Scilab binary file compatible with the function load The Matlab data types are converted into the Scilab equivalents See Also loadmatfile load mfile2sci Authors Serge Steer INRIA Bibliography This function has been developped according to the document MATFile Format MatFile Format httpwwwmathworkscomaccesshelpdeskhelppdfdocmatlabmatfileformatpdf 2094 Name mfile2sci Matlab Mfile to Scilab conversion function mfile2sciMfilepath resultpath Recmode onlydouble verbosemode prettyprintoutput Parameters Mfilepath a character string which gives the path of Matlab Mfile to convert resultpath a character string which gives the directory where the result has to be written Default value is current directory Recmode Boolean flag used by translatepaths function for recursive conversion Must be F to convert a single mfile Default value f onlydouble Boolean flag if T mfile2sci considers that numerical function have been used only with numer ical data no Scilab overloading function is needed Default value F verbosemode display information mode 0 no information displayed 1 information written as comment is resulting SCIfile 2 information written as comment is resulting SCIfile and in logfile 3 information written as comment is resulting SCIfile in logfile and displayed in Scilab win dow prettyprintoutput Boolean flag if T generated code is beautified Default value F Description M2SCI and particularly mfile2sci is Matlab Mfile to Scilab function conversion tools It tries when ever possible to replace call to Matlab functions by the equivalent Scilab primitives and functions To convert a Matlab Mfile just enter the Scilab instruction mfile2scifile where file is a character string giving the path name of the Mfile mfile2sci will generate three files in the same directory functionnamesci the Scilab equivalent of the Mfile functionnamecat the Scilab help file associated to the function mfile2sci 2095 scifunctionnamesci the Scilab function required to convert the calls to this Matlab Mfile in other Matlab Mfiles This function may be improved by hand This function is only useful for conversion not for use of translated functions Some functions like eye ones size sum behave differently according to the dimension of their arguments When mfile2sci cannot infer dimensions it replaces these function call by a call to an emulation function named mtlbfunctionname For efficiency these functions may be re placed by the proper scilab equivalent instructions To get information about replacement enter help mtlbfunctionname in Scilab command window Some other functions like plot has no straightforward ï½quivalent in scilab They are also replaced by an emulation function named mtlbfunctionname When translation may be incorrect or may be improved mfile2sci adds a comment which begins by according to verbosemode When called without rhs mfile2sci launches a GUI to help to select a filedirectory and options Examples Create a simple Mfile writeTMPDIRrot90mfunction B rot90Ak mn sizeA if nargin 1 k 1 else k remk4 if k 0 k k 4 end end if k 1 A A B An11 elseif k 2 B Am11n11 elseif k 3 B Am11 B B else B A end Convert it to scilab mfile2sciTMPDIRrot90mTMPDIR Show the new code writeio2readTMPDIRrot90sci11a get it into scilab execTMPDIRrot90sci Execute it mrand42rot90m1 mfile2sci 2096 See Also translatepaths Authors V Couvert S Steer 2097 Name scifiles How to write conversion functions Description To convert calls to Matlab functions mfile2sci uses a function called sciMatlabfunctionname All these functions are defined in scifiles in directory SCImodulesm2scimacrosscifiles The set of scifiles given in Scilab distribution does not allow to convert calls to all Matlab functions yet However a Scilab user can add scifiles for Matlab functions or for user defined functions to Scilab using the following tips In M2SCI a function call is considered as a tree it is also the case for the instructions of the file to convert represented in Scilab by a tlist with following fields name Matlab function name lhsnb number of Matlab function output parameters lhs list of Matlab function output parameters rhs list of Matlab function input parameters A scifunction has one input called tree which is also the output of the function A scifunction has to convert this incoming tree so that it is compatible with Scilab by changing name lhsnb lhs andor rhs The other task that has to be done by this function is inference Incoming tree contains inference data in its lhs that have to be updated with what can be infered for the outputs of this function Some useful functions have been written to help to create M2SCI tlists while writing this conversion function Funcall create a tree representing a function call Operation create a tree representing an operation Variable create a tree representing a variable Cste create a tree representing a constante value Infer create a tree representing inference data Type create a tree representing type for inference Equal create a tree representing an instruction Some other functions have been designed to get properties of operandsinputs Considering A is tlist used in macro tree you can use the following functions Function returns T if scifiles 2098 isemptyA all dimensions of A are 0 notemptyA all dimensions of A are known and at least one dimension of A is not 0 isascalarA all dimensions of A are 1 notascalarA all dimensions of A are known and at least one dimension of A is not 1 isavectorA all dimensions of A are known and all dimensions of A but one are equal to 1 notavectorA all dimensions of A are known and at least two dimensions of A are greater than one isrealA A is real iscomplexA A is complex isdefinedvarA A is a variable already created in Mfile currently converted allunknownA all dimensions of A are unknown Some other functions have been written for specific needs while writing conversion files firstnonsingleton is an equivalent to firstnonsingleton for an M2SCI tlist Calling sequence dim firstnonsingletonA gettempvar generates a temporary variable having a name which does not already exist Calling sequence v gettempvar insert allows to insert instructions Calling sequence insertEqualopt with opt1 to insert before current instruction and opt1 to insert after it getoperands can be used to get each operand as a variable Calling sequence AB getoperandsoperationtlist getrhs can be used to get each parameter as a variable Calling sequence A getrhsfuncalltlist convert2double change type of input when this type is not implemented for a particular function is Scilab Calling sequence A convert2doubleA To have more information about how to write such files refer to directory SCImodulesm2scimacros scifiles which gives many examples from very simple ones eg sciabssci to very complex ones eg scizerossci See Also m2scideclare Funcall Operation Variable Cste Infer Type Equal Authors VC 2099 Name translatepaths convert a set of Matlab Mfiles directories to Scilab translatepathsdirspath respath Parameters dirspath a character string vector which gives the paths of Matlab Mfile directories to convert respath a character string which gives the path of the directory where the Scilab functions are written to Default value is current directory Description translatepaths converts all Matlab Mfile contained in a set of directories to Scilab functions Each function is converted by mfile2sci Trace of conversion information is stored in a file named log in the respath directory When called without rhs translatepaths launches a GUI to help to select a filedirectory and options See Also mfile2sci Authors V Couvert S Steer Parte XL Interfaces com TclTk 2101 Name ScilabEval tcl instruction Evaluate a string with scilab interpreter ScilabEval instruction ScilabEval instruction seq ScilabEval instruction sync ScilabEval instruction sync seq ScilabEval flush Parameters instruction tcl string character contains a Scilab instruction to evaluate with the current Scilab interpreter Description This function must be called in a tcltk script executed from Scilab It allows to associate Scilab actions to tcltk widgets graphic objects or to use Scilab to perform some computations within a tcl script ScilabEval instruction If the ScilabEval instruction syntax is used the instruction is first stored in a FIFO queue ScilabEval returns immediately Scilab executes the queued instructions when possible it should be at the prompt but also at the end of each instructions of the currently running function in the order they were submitted This syntax can be used to associate Scilab actions to tcltk widgets but not into a tcl script executed by TCLEvalFile or TCLEvalStr be cause in this situation the Scilab interpreter is blocked up to the end of the script Note that with the ScilabEval instruction syntax if there are many ScilabEval commands stored in the queue the execution of the second one can be started in the middle of the execution of the first one in particular if the first one contains more than a simple expression If the seq option is added the associated instruction evaluation should be finished or paused before the next queued instruction evaluation can be started The next callback stored in the com mand queue will only be taken into account when the current one will be finished or paused ScilabEval instruction sync If the ScilabEval instruction sync syntax is used the instruction is executed im mediately not queued and the ScilabEvalreturns when the instruction evaluation is finished The scilab instruction evaluation may be interrupted by new or queued commands If the seq option is added the associated instruction evaluation should be finished or paused before any queued instruction evaluation can be started The scilab instruction evaluation may not be interrupted by new or queued commands except if it is paused ScilabEval flush If the ScilabEval flush syntax is used all the previously queued instructions are executed immediately and the ScilabEval returns when the execution is finished Each in struction is executed with the option used at the time of queuing up ie seq or no option The evaluation context of all these cases is the current Scilab context when theinstruction eval uation starts Examples Callbacks and seq option usage ScilabEval 2102 create tcl instructions tclscripttoplevel w1 button w1b text Click here to execute without seq option command WithoutSeq button w1b1 text Click here to execute with seq option command WithSeq pack w1b w1b1 proc WithoutSeq ScilabEval contfcontt ScilabEval if cont then dispokelse dispwrongendcontf proc WithSeq ScilabEval contfcontt seq ScilabEval if cont then dispokelse dispwrongendcontf mputltclscriptTMPDIRtesttcl write them to a file Execute the tcl script contf TCLEvalFileTMPDIRtesttcl scripts and sync option usage without sync tclscript set t 0 while t 10 ScilabEval atmprintfd a incr t mputltclscriptTMPDIRtesttcl write them to a file Execute the tcl script TCLEvalFileTMPDIRtesttclmprintfTCLEvalFile finished The ScilabEval are executed after the and of TCLEvalFile with sync tclscript set t 0 while t 10 ScilabEval atmprintfd a sync incr t mputltclscriptTMPDIRtesttcl write them to a file Execute the tcl script TCLEvalFileTMPDIRtesttclmprintfTCLEvalFile finished The ScilabEval are executed synchronously with TCLEvalFile See Also TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar Authors Bertrand Guiheneuf 2103 Name TCLCreateSlave Create a TCL slave interpreter TCLCreateSlaveslaveName isSafe Parameters slaveName String Name of the TCL slave interpreter to create isSafe Boolean T to create a safe slave interpreter F otherwise The default value is F A safe slave is not allowed to perform some operations see the TCL documentation for more information Description This routine allows to create a TCL slave interpreter Examples TCLCreateSlaveTCLinterp TCLSetVararTCLinterp TCLExistVaraTCLinterp TCLExistVara TCLDeleteInterpTCLinterp TCLCreateSlaveTCLinterp T TCLSetVararTCLinterp TCLExistVaraTCLinterp TCLExistVara TCLDeleteInterpTCLinterp See Also TCLSetVar TCLExistVar TCLDeleteInterp Authors Allan CORNET VC 2104 Name TCLDeleteInterp delete TCL interpreter TCLDeleteInterpinterp TCLDeleteInterp Parameters interp character string parameter Name of the slave tcl interpreter to delete If not provided it defaults to the main tcl interpreter created by Scilab Description This routine allows to delete a TCL slave interpreter or the main scilab TCL interpreter Examples TCLSetVarScilabOK TCLExistVarScilab TCLDeleteInterp TCLExistVarScilab TCLCreateSlaveBisInterp TCLExistInterpBisInterp TCLSetVarScilabOKBisInterp TCLExistVarScilabBisInterp TCLDeleteInterpBisInterp TCLExistInterpBisInterp See Also TCLSetVar TCLExistVar TCLCreateSlave TCLExistInterp Authors Allan CORNET 2105 Name TCLEvalFile Reads and evaluate a tcltk file TCLEvalFilefilename interp Parameters filename character string Contains the name of the file to read and evaluate interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab Description With this routine one can read and evaluate the content of a file containing tcltk scripts This allows to create powerful tk interfaces The filename might be relative or absolute Advantages and drawbacks of this functionality This routines allows to use directly tcltk scripts This thus allows for instance to use Interface Builders such as SpecTcl to design the interface The interfaces built directly with tcltk scripts are much faster than the ones built with the Scilab Graphic Object library provided with tksci see uicontrol for exam ple Indeed those Objects are warpings around tk graphic widgets Nevertheless this way of creating graphic user interface should only be used when one aims at addressing directly specific tktcl features There are two main reasons for this First of all there is no simple way to manipulate Scilab objects from within a tcltk script Thus the interface designer has to write two sets of callbacks routines One to describe the changes occuring in the interface when the user acts on the widgets The second set of call routines will perform the pure Scilab reactions to the user actions Here is an example Suppose you design a scrollbar corresponding to a spline tension value You want the spline to be displayed in a graphic windows and updated each time the user moves the scrollbar At the same time you want the value of this tension parameter to be displayed within the Interface You will have to write a first tcltk callback function which will be automatically called by the tk scrollbar command option This callback function will update the displayed value of the parameter in the interface and will then call the scilab routine ScilabEval command to update the graph Remarks on the tcltk script style Because Scilab manages the tcltk events it creates the root window this window should not be destroyed nor directly used by your tcltk scripts You should thus always create your own toplevel windows Moreover since this module was written at a time when namespaces didnt exist some vari ables defined by scilab tcltk scripts could collide your code Running your scripts in a slave interpreter may help in such a case Examples TCLEvalFileSCImodulestclscidemostkpuzzle See Also ScilabEval TCLEvalStr TCLGetVar TCLSetVar TCLExistVar TCLUnsetVar TCLUpVar TCLEvalFile 2106 Authors Allan CORNET 2107 Name TCLEvalStr Evaluate a string whithin the TclTk interpreter TCLEvalStrstr interp res TCLEvalStrstr interp Parameters str string or matrix of strings contains a TclTk script in each element interp optional character string parameter Name of the slave Tcl interpreter in which the operation has to be performed If not provided it defaults to the main Tcl interpreter created by Scilab res result of the evaluation if it is successful This is a character string matrix giving the evaluation result for each element of the input argument str Description This routine allows to evaluate TclTk instructions with the TclTk interpreter launched with Scilab when the interp parameter is not given or in a slave interpreter When TclTk support is enabled in Scilab you can evaluate TclTk expression from Scilab interpreter In fact Scilab launches a main TclTk interpreter The Scilab instruction TCLEvalStr can be used to evaluate expressions without having to write TclTk instructions in a separated file this capability is provided by TCLEvalFile Examples with one call TCLEvalStrtoplevel foo1 label foo1l text TK married Scilab pack foo1l button foo1b text close command destroy foo1 pack foo1b step by step debugging TCLEvalStrtoplevel foo2 creates a toplevel TK window TCLEvalStrlabel foo2l text TK married Scilab create a static label TCLEvalStrpack foo2l pack the label widget It appears on the screen textbutton foo2b text close command destroy foo2 TCLEvalStrtext TCLEvalStrpack foo2b kill the windows by program TCLEvalStrdestroy foo1 TCLEvalStrdestroy foo2 TCLEvalStr 2108 with one call and in a slave interpreter TCLCreateSlaveTCLSlave TCLEvalStrset test in Slave TCL InterpTCLSlave TCLGetVartestTCLSlave TCLDeleteInterpTCLSlave return a result res TCLEvalStrexpr 11 res TCLEvalStrtkmessageBox message Hello type okcancel res TCLEvalStrexpr 45 lsearch all a b c a b c c list list a b c list d e f list g h i llength a b c d e See Also ScilabEval TCLEvalFile TCLGetVar TCLSetVar TCLExistVar TCLUnsetVar TCLUpVar Authors Allan CORNET 2109 Name TCLExistArray Return T if a tcl array exists OKTCLExistArrayarrayname interp Parameters arrayname character string Contains the name of the tcltk array interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab ok boolean T if arrayname exists Description This routine allows to test if a tcl array exists Examples TCLExistVarA aABCDEF TCLSetVarAa TCLExistVarA TCLExistArrayA See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar TCLUnsetVar TCLUpVar TCLCreateSlave Authors Allan CORNET 2110 Name TCLExistInterp Return T if a tcl slave interperter exists OKTCLExistInterpinterp Parameters interp character string parameter Name of the slave tcl interpreter ok boolean T if TCL interpreter exists Description This routine allows to test if TCL interpreter exists Examples TCLExistInterpSlaveInterp TCLCreateSlaveSlaveInterp TCLExistInterpSlaveInterp TCLDeleteInterpSlaveInterp See Also TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2111 Name TCLExistVar Return T if a tcl variable exists OKTCLExistVarvarname interp Parameters varname character string Contains the name of the tcltk variable interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab ok boolean T if varname exists Description This routine allows to test if a tcl variable exists Examples TCLSetVarScilabOK TCLGetVarScilab TCLUnsetVarScilab TCLExistVarScilab TCLSetVaraa1 TCLCreateSlaveSlaveInterp TCLSetVaraa2SlaveInterp TCLExistVaraa TCLGetVaraa TCLUnsetVaraa TCLGetVaraaSlaveInterp TCLUnsetVaraaSlaveInterp TCLExistVaraaSlaveInterp TCLDeleteInterpSlaveInterp See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar TCLUnsetVar TCLUpVar TCLCreateSlave Authors Allan CORNET 2112 Name TCLGetVar Get a tcltk variable value valueTCLGetVarVarname interp Parameters varname character string Contains the name of the tcltk variable interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab value may be a character string or a strings matrix Contains the value of the tcltk variable varname in the interpreter interp Description When tcltk support is enabled in Scilab this routine can be used to retreive the value of a tcltk variable Examples TCLEvalStrtoplevel tst1 creates a toplevel TK window TCLEvalStrentry tst1e textvariable tvar create an editable entry TCLEvalStrset tvar foobar set the entry value TCLEvalStrpack tst1e pack the entry widget It appears on the screen textTCLGetVartvar retrieve the variable value change the entry text and repeat the last command delete the toplevel TK window TCLEvalStrdestroy tst1 aABCDEF TCLSetVarAa AfromTCLTCLGetVarA b641235 TCLSetVarBb BfromTCLTCLGetVarB TCLGetVar 2113 TCLSetVarStringTCLstring StringFromTCLTCLGetVarStringTCL TCLSetVarScalarTCL122 ScalarFromTCLTCLGetVarScalarTCL Examples with a slave interpreter aAABBCCDDEEFF TCLCreateSlaveSlaveInterp TCLSetVarAslaveaSlaveInterp AfromTCLslaveTCLGetVarAslaveSlaveInterp TCLDeleteInterpSlaveInterp b664411223355 TCLCreateSlaveSlaveInterp1 TCLSetVarBslavebSlaveInterp1 BfromTCLslaveTCLGetVarBslaveSlaveInterp1 TCLDeleteInterpSlaveInterp1 TCLCreateSlaveSlaveInterp2 TCLSetVarStringTCLslavestring in slave interpreterSlaveInterp2 StringFromTCLslaveTCLGetVarStringTCLslaveSlaveInterp2 TCLDeleteInterpSlaveInterp2 TCLCreateSlaveSlaveInterp3 TCLSetVarScalarTCLslave122SlaveInterp3 ScalarFromTCLslaveTCLGetVarScalarTCLslaveSlaveInterp3 TCLDeleteInterpSlaveInterp3 See Also ScilabEval TCLEvalFile TCLEvalStr TCLSetVar TCLExistVar TCLUnsetVar TCLUpVar TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2114 Name TCLGetVersion get the version of the TCLTK library at runtime TCLGetVersion retTCLGetVersionnumbers Description get the version of the TCLTK library at runtime retTCLGetVersionnumbers returns a matrix with the version of the TCLTK library at runtime Examples TCLGetVersion TCLGetVersionnumbers Authors Allan CORNET 2115 Name TCLSetVar Set a tcltk variable value TCLSetVarvarname value interp Parameters varname character string Contains the name of the tcltk variable to set value may be a character string a scalar a real or string matrix m x n Contains the value to give to the tcltk variable interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab Description This routine allows to set a variable within a tcltk interpreter When tcltk support is enabled in scilab this routine can be used to set up the value of a tcltk variable This can be useful to change some value in the tcltk interpreter without having to build a tcltk instruction and use TCLEvalStr Examples TCLEvalStrtoplevel tst1 creates a toplevel TK window TCLEvalStrentry tst1e textvariable tvar create an editable entry TCLEvalStrset tvar foobar set the entry value TCLEvalStrpack tst1e pack the entry widget It appears on the screen textTCLGetVartvar retrieve the variable value change the entry text and repeat the last command delete the toplevel TK window TCLEvalStrdestroy tst1 aABCDEF TCLSetVarAa AfromTCLTCLGetVarA b641235 TCLSetVarBb BfromTCLTCLGetVarB TCLSetVar 2116 TCLSetVarStringTCLstring StringFromTCLTCLGetVarStringTCL TCLSetVarScalarTCL122 ScalarFromTCLTCLGetVarScalarTCL Examples with a slave interpreter TCLCreateSlaveTCLSlave aAABBCCDDEEFF TCLSetVarAslaveaTCLSlave AfromTCLslaveTCLGetVarAslaveTCLSlave TCLDeleteInterpTCLSlave TCLCreateSlaveTCLSlave b664411223355 TCLSetVarBslavebTCLSlave BfromTCLslaveTCLGetVarBslaveTCLSlave TCLDeleteInterpTCLSlave TCLCreateSlaveTCLSlave TCLSetVarStringTCLslavestring in slave interpreterTCLSlave StringFromTCLslaveTCLGetVarStringTCLslaveTCLSlave TCLDeleteInterpTCLSlave TCLCreateSlaveTCLSlave TCLSetVarScalarTCLslave122TCLSlave ScalarFromTCLslaveTCLGetVarScalarTCLslaveTCLSlave TCLDeleteInterpTCLSlave See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLExistVar TCLUnsetVar TCLUpVar TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2117 Name TCLUnsetVar Remove a tcl variable OKTCLUnsetVarvarname interp Parameters varname character string Contains the name of the tcltk variable to unset interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab ok boolean T if varname was deleted Description This routine allows to unset a tcl variable Examples TCLSetVarScilabOK TCLGetVarScilab TCLUnsetVarScilab TCLExistVarScilab TCLCreateSlaveInterpSlave TCLSetVarScilabGoodInterpSlave TCLGetVarScilabInterpSlave TCLUnsetVarScilabInterpSlave TCLExistVarScilabInterpSlave TCLDeleteInterpInterpSlave See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar TCLExistVar TCLUpVar TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2118 Name TCLUpVar Make a link from a tcl source variable to a tcl destination variable OKTCLUpVarvarname1varname2interp Parameters varname1 character string Contains the name of the tcl source variable varname2 character string Contains the name of the tcl destination variable interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab ok boolean T if it is ok Description Make a link from a tcl source variable to a tcl destination variable Examples TCLSetVarScilabOK TCLUpVarScilabScilabBis TCLGetVarScilabBis TCLSetVarScilabNOK TCLGetVarScilabBis TCLSetVarScilabBismodified TCLGetVarScilabBis TCLGetVarScilab TCLCreateSlaveInterpBis TCLSetVarScilabGoodInterpBis TCLUpVarScilabScilabBisInterpBis TCLGetVarScilabBisInterpBis TCLSetVarScilabNot goodInterpBis TCLGetVarScilabBisInterpBis TCLSetVarScilabBismodified againInterpBis TCLGetVarScilabBisInterpBis TCLGetVarScilabInterpBis TCLDeleteInterpInterpBis See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar TCLExistVar TCLUnsetVar TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2119 Name browsevar Scilab variable browser browsevar Description browsevar is an embedded Scilab variable browser written in TCLTK browsevar can show all variables and function like who browsevar can be costumized to show all or some type of variable Its also posibble exclude variable names Examples browsevar Authors Jaime Urzua 2120 Name config Scilab general configuration config Description config allows configure scilab parameters like lines to display stacksize ODEOPTIONS Authors Jaime Urzua 2121 Name editvar Scilab variable editor editvar varname Parameters varname variable name The variable must exist in scilab Description editvar is an embedded Scilab variable editor written in TCLTK editvar can edit the following variable type real or complex constant matrix type 1 boolean matrix type 4 an matrix of character strings type 10 Examples arand1010 editvar a bhellogood bye editvar b Authors Jaime Urzua 2122 Name tkgetdir dialog to get a directory path pathtkgetdirTitlestring pathtkgetdirstartdirTitlestring pathtkgetdirstartdirwindowtitle Parameters startdir a character string which gives the initial directory used for directory search By default tkgetdir uses the previously selected directory path is the user selected file path if user answers Ok or the string if user answers Cancel Titlestring Optional argument which gives the title for the tkgetdir window Warning Use the new vari able Title instead of the old variable title Description WARNING this function is deprecated see uigetdir as a replacement of tkgetdir It will be removed in Scilab 53 Creates a dialog window for file selection Examples tkgetdir tkgetdirSCImodules tkgetdirTitleChoose a directory name See Also uigetdir uigetfile file fileinfo 2123 Name tksavefile dialog to get a file path for writing pathtksavefileTitlestring pathtksavefilefilemaskTitlestring pathtksavefilefilemaskdirTitlestring pathtksavefilefilemaskdirstring Parameters filemask a character string which gives the file mask to use for file selection filemask is written with Unix convention the default value is dir a character string which gives the initial directory used for file search by default tksavefile uses the previously selected directory path is the user selected file path if user answers Ok or the string if user answers Cancel Titlestring Optional argument which gives the title for the tksavefile window Warning Use the new variable Title instead of the old variable title Description WARNING this function is obsolete see uigetfile as a replacement of tksavefile It will be removed in Scilab 53 Creates a dialog window for output file selection Examples tksavefile tksavefilesciSCImodulesgraphicsmacros tksavefileTitleChoose a file name See Also uigetfile uigetdir file fileinfo 2124 Name winclose close windows created by sciGUI winclosewinIds Parameters winIds matrix of integer greater than 0 window identificator Description winclosewinIds close windows created by sciGUI Examples CREATE SOME WINDOWS win1waitbarThis is an example win2waitbarHELLO winclosewin1win2 Authors Jaime Urzua 2125 Name winlist Return the winId of current window created by sciGUI winIdswinlist Parameters winIds matrix of integer greater than 0 window identificator Description winlist Return the winId of current window created by sciGUI Authors Jaime Urzua Parte XLI Texmacs 2127 Name pol2tex convert polynomial to TeX format This function is obsolete and will be removed in Scilab 53 Please use prettyprint ypol2texx Parameters x polynomial y list Description Latex source code for the polynomial x For use with texprint This function is obsolete and will be removed in Scilab 53 Please use prettyprint Examples spoly0s ps32s5 pol2texp See Also prettyprint 2128 Name texprint TeX output of Scilab object This function is obsolete and will be removed in Scilab 53 Please use prettyprint text texprinta Parameters a Scilab object text list Description returns the Tex source code of the Scilab variable a a is a matrix constant polynomial rational or a linear system syslin list This function is obsolete and will be removed in Scilab 53 Please use prettyprint Examples spoly0s texprint1ss2 See Also prettyprint pol2str Parte XLII Manipulação de Arquivos de Som 2130 Name analyze frequency plot of a sound signal Parameters fminfmaxratepoints scalars default values fmin100fmax1500rate22050points8192 Description Make a frequency plot of the signal w with sampling rate rate The data must be at least points long The maximal frequency plotted will be fmax the minimal fmin Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound ssin440tsin220t2sin880t2 nrncsizet snc2ncsin330tnc2nc analyzes 2131 Name auread load au sound file yaureadaufile yaureadaufileext yFsbitsaureadaufile yFsbitsaureadaufileext Parameters aufile string The au extension is appended if no extension is given Fs integer frequency sampling in Hz ext string size or snd or integer to read n samples or 1 x 2 integer vector n1n2 to read from n1 to n2 Description Utility function to read au sound file aureadaufile loads a sound file specified by the string aufile returning the sampled data in y Amplitude values are in the range 11 Supports multichannel data in the following formats 8bit mulaw 8 16 and 32bit linear and floating point yFsbitsaureadaufile returns the sample rate Fs in Hertz and the number of bits per sample used to encode the data in the file aureadaufilen returns the first n samples from each channel aureadaufilen1n2 returns samples n1 to n2 aureadaufilesize returns the size of the audio data contained in the file in place of the actual audio data returning the vector as samples channels aureadaufilesnd returns information about the sample and data as a tlist Examples ywavreadSCImodulessounddemoschimeswav default is 8bits mulaw auwriteyTMPDIRtmpau y1aureadTMPDIRtmpau maxiabsyy1 See Also savewave analyze mapsound 2132 Name auwrite writes au sound file auwriteyaufile auwriteyFsaufile auwriteyFsbitsaufile auwriteyFsbitsmethodaufile Parameters y real vector or matrix with entries in 11 aufile string The au extension is appended if no extension is given Fs integer frequency sampling in Hz bits integer number of bits in the encoding method string mu default or linear encoding method Description Utility function to save au sound file auwriteyaufile writes a sound file specified by the string aufile The data should be arranged with one channel per column Amplitude values outside the range 11 are ignored Supports multichannel data for 8bit mulaw and 8 16 32 64 bits linear formats auwriteyFsaufile specifies in Fs the sample rate of the data in Hertz auwriteyFsbitsaufile selects the number of bits in the encoder Allowable settings are bits in 8163264 auwriteyFsbitsmethodaufile allows selection of the encoding method which can be either mu or linear Note that bits must be 8 for mu choice The default method is 8bits mulaw enconding Examples Amatrix1623 auwriteA62205064linearTMPDIRfooau BaureadTMPDIRfooau maxiabsA roundB6 See Also auread wavread savewave analyze mapsound 2133 Name beep Produce a beep sound beep beepon beepoff sbeep Description beep produces your computers default beep sound beepon turns the beep on beepoff turns the beep off sbeep returns the current beep mode on or off Authors AC 2134 Name lin2mu linear signal to mulaw encoding mulin2muy Parameters y real vector mu real vector Description Utility fct converts linear signal to mulaw encoding mu lin2muy converts linear audio signal amplitudes in the range 1 y 1 to mulaw in the range 0 mu 255 See Also mu2lin 2135 Name loadwave load a sound wav file into scilab xloadwavefilename xyloadwavefilename Parameters filename a string The path of the wav file to be loaded x a matrix one line for each channel y vector as data format number of channels samples per second per channel estimate of bytes per second needed byte alignment of a basic sample block bits per sample length of sound data in bytes bytes per sample per channel Description Reads a wav sound file into Scilab as a matrix If y is given it is filled with information about the samples See the message sent by loadwave Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound a two channels sound ssin2pi440tsin2pi350t savewaveTMPDIRfoowavs s1loadwaveTMPDIRfoowav maxabss1s See Also savewave analyze mapsound 2136 Name mapsound Plots a sound map mapsound wdtfminfmaxsimplrate Parameters dtfminfmaxsimplrate scalars default values dt01fmin100fmax1500simpl1rate22050 Description Plots a sound map for a sound It does FFT at time increments dt rate is the sampling rate simpl points are collected for speed reasons fmin and fmax are used for graphic boundaries Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound ssin440tsin220t2sin880t2 nrncsizet snc2ncsin330tnc2nc mapsounds 2137 Name mu2lin mulaw encoding to linear signal mulin2muy Parameters y real vector mu real vector Description Utility fct ymu2linmu converts mulaw encoded 8bit audio signals stored in the range 0 mu 255 to linear signal amplitude in the range s y s where s 3212432768 9803 The input mu is often obtained using mgetuc to read byteencoded audio files Translation of C program by Craig Reese IDASupercomputing Research Center Joe Campbell Department of Defense See Also mu2lin 2138 Name playsnd sound player facility playsndy playsndyratebits command Parameters y A matrix Each line descibe a channel fs real number sampling frequency default value is 22050 bits real number number of bits usually 8 or 16 Unused yet command Only used on Unix systems it gives the name of the command to use for playing sound wav files The defaut value is play If set devaudio then a 8 bits mulaw raw sound file is created and send to devaudio Description Plays a multi channel signal given by a Scilab matrix were sound is sampled at rate given by rate Examples a two channel signal yloadwaveSCImodulessounddemoschimeswav playsndy See Also lin2mu wavread 2139 Name savewave save data into a sound wav file savewavefilenamex rate nbits Parameters filename a string The path of the output wav file x a mxn matrix where m is the number of channels and n the number of samples for each channel rate a scalar giving the sampling rate number of sample per second 22050 is the default value Description save x into a wav sound file you can transform other sound files into wav file with the sox program Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound ssin2pi440tsin2pi220t2sin2pi880t2 nrncsizet snc2ncsin2pi330tnc2nc savewaveTMPDIRfoowavs See Also loadwave analyze mapsound 2140 Name sound sound player facility soundy fsbitscommand Parameters y real vector fs real number sampling frequency in sample per second default value is 22050 bits real number number of bits unused command Only used on Unix systems it gives the name of the command to use for playing sound wav files The defaut value is aplay If set devaudio then a 8 bits mulaw raw sound file is created and send to devaudio Description soundyfsplays the sound signal given by matrix y with sample frequency fs In fact this func tion is just a wrapper for playsnd Values in y are assumed to be in the range 10 y 10 Values outside that range are truncated The number of rows of y gives the number of channels soundy plays the sound at the default sample rate of 22050 sample per second soundyfsnbits plays the sound using nbits bitssample if possible it is in fact unused Most platforms support bits8 or 16 Examples a two channel signal yloadwaveSCImodulessounddemoschimeswav soundy See Also playsnd 2141 Name soundsec generates n sampled seconds of time parameter tsoundsecn rate Parameters n an integer the number of seconds to generate rate an integer the number of samples per second Description generates a vector coding time from 0 to nseconds at sampled rate rate Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound ssin2pi440t analyzes20060022050 See Also playsnd analyze 2142 Name wavread load wav sound file ywavreadwavfile ywavreadwavfileext yFsbitswavreadwavfile yFsbitswavreadwavfileext Parameters wavfile string The wav extension is appended if no extension is given Fs integer frequency sampling in Hz number of samples per second ext string size or stringinfo or integer to read n samples or 1 x 2 integer vector n1n2 to read from n1 to n2 Description Utility function to read wav sound file wavreadwavfile loads a sound file specified by the string wavfile returning the sampled data in y Amplitude values are in the range 11 Supports multichannel data in the following formats 8bit mulaw 8 16 and 32bit linear and floating point yFsbitswavreadwavfile returns the sample rate Fs in Hertz and the number of bits per sample used to encode the data in the file wavreadwavfilen returns the first n samples from each channel wavreadwavfilen1n2 returns samples n1 to n2 wavreadwavfilesize returns the size of the audio data contained in the file in place of the actual audio data returning the vector as channels samples wavreadwavfileinfo returns information about the audio data contained in the file in place of the actual audio data returning the vector as data format number of channels samples per second per channel estimate of bytes per second needed byte alignment of a basic sample block bits per sample length of sound data in bytes bytes per sample per channel Examples wavreadSCImodulessounddemoschimeswavsize yFsbitswavreadSCImodulessounddemoschimeswavFsbits subplot211 plot2dy1 first channel subplot212 plot2dy2 second channel ywavreadSCImodulessounddemoschimeswav1 5 the first five samples See Also auread savewave analyze mapsound 2143 Name wavwrite writes wav sound file wavwritey wavfile wavwritey Fs wavfile wavwritey Fs nbits wavfile Parameters y real vector or matrix with entries in 11 wavfile string The wav extension is appended if no extension is given Fs integer frequency sampling in Hz 22500 is the default value nbits bitdepth 8 16 24 32 bits it describes the number of bits of information recorded for each sample 16 is the default value Description Utility function to save wav sound file wavwriteywavfile writes a sound file specified by the string wavfile The data should be arranged with one channel per column Amplitude values outside the range 11 are ignored wavwriteyFswavfile specifies in Fs the sample rate of the data in Hertz Examples Amatrix1623 wavwriteA6TMPDIRfoowav BwavreadTMPDIRfoowav See Also auread wavread savewave analyze mapsound Parte XLIII Randlib 2145 Name grand Random number generators Ygrandm n disttype p1pk YgrandX disttype p1pk Ygrandn disttype p1pk Sgrandaction q1ql Parameters m n integers size of the wanted matrix Y X a matrix whom only the dimensions say m x n are used disttype a string given the distribution which independants variates are to be generated bin nor poi etc p1 pk the parameters reals or integers required to define completly the distribution disttype Y the resulting m x n random matrix action a string given the action onto the base generators setgen to change the current base generator getgen to retrieve the current base generator name getsd to retrieve the state seeds of the current base generator etc q1 ql the parameters generally one string needed to define the action S output of the action generaly a string or a real column vector Description This function may be used to generate random numbers from various distributions In this case you must apply one of the three first forms of the possible calling sequences to get an m x n matrix The two firsts are equivalent if X is a m x n matrix and the third form corresponds to multivalued distributions eg multinomial multivariate gaussian etc where a sample is a column vector says of dim m and you get then n such random vectors as an m x n matrix The last form is used to undertake various manipulations onto the base generators like changing the base generator since v 27 you may choose between several base generators changing or retrieving its internal state seeds etc These base generators give random integers following a uniform dis tribution on a large integer interval lgi all the others distributions being gotten from it in general via a scheme lgi U01 wanted distribution Getting random numbers from a given distribution beta YgrandmnbetAB generates random variates from the beta distribution with pa rameters A and B The density of the beta is 0 x 1 grand 2146 A1 B1 x 1x betaAB A and B must be reals 1037 Related functions cdfbet binomial YgrandmnbinNp generates random variates from the binomial distribution with parameters N positive integer and p real in 01 number of successes in N independant Bernouilli trials with probability p of success Related functions binomial cdfbin negative binomial YgrandmnnbnNp generates random variates from the negative binomial distribu tion with parameters N positive integer and p real in 01 number of failures occurring before N successes in independant Bernouilli trials with probability p of success Related functions cdfnbn chisquare Ygrandmnchi Df generates random variates from the chisquare distribution with Df real 00 degrees of freedom Related functions cdfchi non central chisquare YgrandmnnchDfXnon generates random variates from the non central chisquare distribution with Df degrees of freedom real 10 and noncentrality parameter Xnonc real 00 Related functions cdfchn exponential YgrandmnexpAv generates random variates from the exponential distribution with mean Av real 00 F variance ratio YgrandmnfDfnDfd generates random variates from the F variance ratio distri bution with Dfn real 00 degrees of freedom in the numerator and Dfd real 00 degrees of freedom in the denominator Related functions cdff non central F variance ratio YgrandmnnfDfnDfdXnon generates random variates from the noncentral F variance ratio distribution with Dfn real 1 degrees of freedom in the numerator and Dfd real 0 degrees of freedom in the denominator and noncentrality parameter Xnonc real 0 Related functions cdffnc gamma Ygrandmngamshapescale generates random variates from the gamma distri bution with parameters shape real 0 and scale real 0 The density of the gamma is shape shape1 scale x scale x e gammashape Related functions gamma cdfgam Gauss Laplace normal YgrandmnnorAvSd generates random variates from the normal distribution with mean Av real and standard deviation Sd real 0 Related functions cdfnor multivariate gaussian multivariate normal YgrandnmnMeanCov generates n multivariate normal random variates Mean must be a m x 1 matrix and Cov a m x m symmetric positive definite matrix Y is then a m x n matrix grand 2147 geometric Ygrandmngeom p generates random variates from the geometric distribution with parameter p number of Bernouilli trials with probability succes of p until a succes is met p must be in pmin1 with pmin 13 10307 Y contains positive real numbers with integer values with are the number of trials to get a suc cess markov YgrandnmarkovPx0 generate n successive states of a Markov chain described by the transition matrix P Initial state is given by x0 If x0 is a matrix of size msizex0 then Y is a matrix of size m x n Yi is the sample path obtained from initial state x0i multinomial YgrandnmulnbP generates n observations from the Multinomial distribution class nb events in m categories put nb balls in m boxes Pi is the probability that an event will be classified into category i P the vector of probabilities is of size m1 the probability of category m being 1sumP Y is of size m x n each column Yj being an observation from multinomial distribution and Yij the number of events falling in category i for the j th observation sumYj nb Poisson Ygrandmnpoimu generates random variates from the Poisson distribution with mean mu real 00 Related functions cdfpoi random permutations Ygrandnprmvect generate n random permutations of the column vector m x 1 vect uniform def Ygrandmndef generates random variates from the uniform distribution over 01 1 is never return uniform unf YgrandmnunfLowHigh generates random reals uniformly distributed in Low High uniform uin YgrandmnuinLowHigh generates random integers uniformly distributed be tween Low and High included High and Low must be integers such that HighLow1 2147483561 uniform lgi Ygrandmnlgi returns the basic output of the current generator random integers following a uniform distribution over 0 232 1 for mt kiss and fsultra 0 2147483561 for clcg2 0 231 2 for clcg4 0 231 1 for urand Setget the current generator and its state Since Scilab27 you have the possibility to choose between different base generators which give random integers following the lgi distribution the others being gotten from it grand 2148 mt the MersenneTwister of M Matsumoto and T Nishimura period about 219937 state given by an array of 624 integers plus an index onto this array this is the default generator kiss The Keep It Simple Stupid of G Marsaglia period about 2123 state given by 4 integers clcg2 a Combined 2 Linear Congruential Generator of P LEcuyer period about 261 state given by 2 integers this was the only generator previously used by grand but slightly modified clcg4 a Combined 4 Linear Congruential Generator of P LEcuyer period about 2121 state given by 4 integers this one is splitted in 101 different virtual non overlapping generators which may be useful for different tasks see Actions specific to clcg4 and Test example for clcg4 urand the generator used by the scilab function rand state given by 1 integer period of 231 based on theory and suggestions given in de knuth 1969 vol 2 State This is the faster of this list but a little outdated dont use it for serious simulations fsultra a SubtractwithBorrow generator mixing with a congruential generator of Arif Zaman and George Marsaglia period more than 10356 state given by an array of 37 integers plus an index onto this array a flag 0 or 1 and another integer The differents actions common to all the generators are action getgen Sgrandgetgen returns the current base generator S is a string among mt kiss clcg2 clcg4 urand fsultra action setgen grandsetgengen sets the current base generator to be gen a string among mt kiss clcg2 clcg4 urand fsultra notes that this call returns the new current generator ie gen action getsd Sgrandgetsd gets the current state the current seeds of the current base generator S is given as a column vector of integers of dimension 625 for mt the first being an index in 1624 4 for kiss 2 for clcg2 40 for fsultra 4 for clcg4 for this last one you get the current state of the current virtual generator and 1 for urand action setsd grandsetsdS grandsetsds1s2s3s4 sets the state of the current base generator the new seeds for mt S is a vector of integers of dim 625 the first component is an index and must be in 1624 the 624 last ones must be in 0232 but must not be all zeros a simpler initialisation may be done with only one integer s1 s1 must be in 0232 for kiss 4 integers s1s2 s3s4 in 0232 must be provided for clcg2 2 integers s1 in 12147483562 and s2 in 12147483398 must be given for clcg4 4 integers s1 in 12147483646 s2 in 12147483542 s3 in 12147483422 s4 in 12147483322 are required CAUTION with clcg4 you set the seeds of the current virtual generator but you may lost the synchronisation between grand 2149 this one and the others virtuals generators ie the sequence generated is not warranty to be non overlapping with a sequence generated by another virtual generator use instead the setall option for urand 1 integer s1 in 0231 must be given for fsultra S is a vector of integers of dim 40 the first component is an index and must be in 037 the 2d component is a flag 0 or 1 the 3d an integer in 1232 and the 37 others integers in 0232 a simpler and recommanded initialisation may be done with two integers s1 and s2 in 0232 action phr2sd Sdgrandphr2sd phrase given a phrase character string generates a 1 x 2 vector Sd which may be used as seeds to change the state of a base generator initialy suited for clcg2 Options specific to clcg4 The clcg4 generator may be used as the others generators but it offers the advantage to be splitted in several 101 virtual generators with non overlapping sequences when you use a classic generator you may change the initial state seeds in order to get another sequence but you are not warranty to get a complete different one Each virtual generator corresponds to a sequence of 272 values which is further split into V231 segments or blocks of length W241 For a given virtual generator you have the possibility to return at the beginning of the sequence or at the beginning of the current segment or to go directly at the next segment You may also change the initial state seed of the generator 0 with the setall option which then change also the initial state of the other virtual generators so as to get synchronisation ie in function of the new initial state of gen 0 the initial state of gen 1100 are recomputed so as to get 101 non overlapping sequences action setcgn grandsetcgnG sets the current virtual generator for clcg4 when clcg4 is set this is the virtual clcg4 generator number G which is used the virtual clcg4 generators are numbered from 01100 and so G must be an integer in 0100 by default the current virtual generator is 0 action getcgn Sgrandgetcgn returns the number of the current virtual clcg4 generator action initgn grandinitgnI reinitializes the state of the current virtual generator I 1 sets the state to its initial seed I 0 sets the state to its last previous seed ie to the beginning of the current segment I 1 sets the state to a new seed W values from its last seed ie to the beginning of the next segment and resets the current segment parameters action setall grandsetalls1s2s3s4 sets the initial state of generator 0 to s1s2s3s4 The initial seeds of the other generators are set accordingly to have synchronisation For con straints on s1 s2 s3 s4 see the setsd action action advnst grandadvnstK advances the state of the current generator by 2K values and resets the initial seed to that value grand 2150 Test example for clcg4 An example of the need of the splitting capabilities of clcg4 is as follows Two statistical techniques are being compared on data of different sizes The first technique uses bootstrapping and is thought to be as accurate using less data than the second method which employs only brute force For the first method a data set of size uniformly distributed between 25 and 50 will be generated Then the data set of the specified size will be generated and analyzed The second method will choose a data set size between 100 and 200 generate the data and analyze it This process will be repeated 1000 times For variance reduction we want the random numbers used in the two methods to be the same for each of the 1000 comparisons But method two will use more random numbers than method one and without this package synchronization might be difficult With clcg4 it is a snap Use generator 0 to obtain the sample size for method one and generator 1 to obtain the data Then reset the state to the beginning of the current block and do the same for the second method This assures that the initial data for method two is that used by method one When both have concluded advance the block for both generators See Also rand Authors randlib The codes to generate sequences following other distributions than def unf lgi uin and geom are from Library of Fortran Routines for Random Number Generation by Barry W Brown and James Lovato Department of Biomathematics The University of Texas Houston mt The code is the mt19937intc by M Matsumoto and T Nishimura Mersenne Twister A 623 dimensionally equidistributed uniform pseudorandom number generator ACM Trans on Mod eling and Computer Simulation Vol 8 No 1 January pp330 1998 kiss The code was given by G Marsaglia at the end of a thread concerning RNG in C in several news groups whom scimathnumanalysis My offer of RNGs for C was an invitation to dance only kiss have been included in Scilab kiss is made of a combinaison of severals others which are not visible at the scilab level clcg2 The method is from P LEcuyer but the C code is provided at the Luc Devroye home page http cgmcsmcgillcalucrnghtml clcg4 The code is from P LEcuyer and Terry HAndres and provided at the P LEcuyer home page httpwwwiroumontrealcalecuyerpapershtml A paper is also provided and this new pack age is the logical successor of an old s one from P LEcuyer and S Cote Implementing a Ran dom Number Package with Splitting Facilities ACM Transactions on Mathematical Software 171pp 98111 fsultra code from Arif Zaman arifstatfsuedu and George Marsaglia geostatfsuedu scilab packaging By JeanPhilippe Chancelier and Bruno Pincon Parte XLIV Ferramentas de Desenvolvimento 2152 Name benchrun Launch benchmark tests benchrun benchrunmoduletestnameoptions Parameters module a vector of string It can be the name of a module or the absolute path of a toolbox testname a vector of string options a vector of string list list of the benchmark tests available in a module help displays some examples of use in the Scilab console nbrunvalue repeat the benchmark test value times Description Search for tst files in benchmark test library execute them and display a report about execution time The tst files are searched in directories SCImodulestestsbenchmark Special tags may be inserted in the tst file which help to control the processing of the corresponding test These tags are expected to be found in Scilab comments These are the available tags BENCH NB RUN 10 This test will be repeated 10 times BENCH START BENCH END The interesting part of the benchmark must be en closed by these tags Examples Some simple examples of invocation of benchrun Launch all tests benchrun benchrun benchrun Test one or several module benchruncore benchruncore benchruncorestring Launch one or several test in a specified module benchruncoretrycatchopcode benchrun 2153 With options benchrunlist benchrunhelp benchrunnbrun2000 An example of a benchmark file This file corresponds to the file SCImoduleslinearalgebratests benchmarksbenchcholtst Scilab httpwwwscilaborg This file is part of Scilab Copyright C 20072008 INRIA This file is distributed under the same license as the Scilab package Benchmark for chol function BENCH NB RUN 10 stacksize30000000 a 0 b 0 a rand900 900 n a aa BENCH START b chola BENCH END The result of the test benchrunlinearalgebrabenchchol Boucle For 019 µs 1000000 x 001001 linearalgebra benchchol 15157671 µs 10 x See Also testrun Authors Yann Collette 2154 Name tbxbuildcleaner Generate a cleanersce script toolbox compilation process tbxbuildloadertoolboxname tbxbuildloadertoolboxname toolboxpath Parameters toolboxname Toolbox short name that is the prefix of the start file of the toolbox which shall be in the etc subdirectory toolboxpath Root directory of toolbox sources the script will be generated here default current directory Examples Recommended usage tbxbuildcleanermytoolbox getabsolutefilepathbuildersce Authors Allan CORNET 2155 Name tbxbuildgateway Build a gateway toolbox compilation process tbxbuildgatewaylibname names files gatewaypath libs ldflags cflags fflags cc makename ismex Parameters libname a character string the generic name of the library without path and extension names 2 column string matrix giving the table of pairs scilabname interface name files string matrix giving objects files needed for shared library creation gatewaypath Path to the sources of the gateway in a normal toolbox it should be the directory containing the buildergatewaylangsce script which should be the script calling this function Default is current directory libs string matrix giving extra libraries needed for shared library creation ldflagscflagsfflags character strings to provide options for the loader the C compiler and the Fortran compiler cc character string The name of or path to the compiler makename character string The path of the Makefile file without extension ismex Internal variable to specify if we are working with mex or not Examples Recommended usage tbxbuildgatewaymytoolbox csumscicsumcsubscicsub scicsumcscicsubc getabsolutefilepathbuildergatewaycsce srcclibcsum See Also ilibbuild Authors SL 2156 Name tbxbuildgatewayclean Generate a cleanergatewaysce script toolbox compilation process tbxbuildgatewayloaderlangs tbxbuildgatewayloaderlangs gatewaypath Parameters langs Languages of source files gatewaypath Path to the sources of the gateway in a normal toolbox it should be the directory containing the buildergatewaysce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildgatewaycleanc fortran getabsolutefilepathbuildergatewaysce Authors Allan CORNET 2157 Name tbxbuildgatewayloader Generate a loadergatewaysce script toolbox compilation process tbxbuildgatewayloaderlangs tbxbuildgatewayloaderlangs gatewaypath Parameters langs Languages of source files gatewaypath Path to the sources of the gateway in a normal toolbox it should be the directory containing the buildergatewaysce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildgatewayloaderc fortran getabsolutefilepathbuildergatewaysce Authors SL 2158 Name tbxbuildhelp Generate help files toolbox compilation process tbxbuildhelptitle tbxbuildhelptitle helppath Parameters title Title of the chapter helppath Directory where the files will be generated in a normal toolbox it should be the directory con taining the buildhelpsce script which should be the script calling this function Default is cur rent directory Examples Recommended usage tbxbuildhelpToolbox Example getabsolutefilepathbuildhelpsce Authors SL 2159 Name tbxbuildhelploader Generate a addchaptersce script toolbox compilation process tbxbuildhelploadertitle tbxbuildhelploadertitle helppath Parameters title Title of the chapter helppath Directory where the script will be generated in a normal toolbox it should be the directory con taining the buildhelpsce script which should be the script calling this function Default is cur rent directory Examples Recommended usage tbxbuildhelploaderToolbox Example getabsolutefilepathbuildhelpsce Authors SL 2160 Name tbxbuildloader Generate a loadersce script toolbox compilation process tbxbuildloadertoolboxname tbxbuildloadertoolboxname toolboxpath Parameters toolboxname Toolbox short name that is the prefix of the start file of the toolbox which shall be in the etc subdirectory toolboxpath Root directory of toolbox sources the script will be generated here default current directory Examples Recommended usage tbxbuildloadermytoolbox getabsolutefilepathbuildersce Authors SL 2161 Name tbxbuildmacros Compile macros toolbox compilation process tbxbuildmacrostoolboxname tbxbuildmacrostoolboxname macrospath Parameters toolboxname Toolbox short name that is the prefix of the start file of the toolbox which shall be in the etc subdirectory macrospath Directory where the macros files can be found and where the compiled macros will be placed into in a normal toolbox it should be the directory containing the buildmacrossce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildmacrostoolboxexample getabsolutefilepathbuildmacrossce Authors SL 2162 Name tbxbuildsrc Build sources toolbox compilation process tbxbuildsrcnames files flag srcpath libs ldflags cflags fflags cc libname loadername makename Parameters names a string matrix giving the entry names which are to be linked files string matrix giving objects files needed for shared library creation flag a string flag c or f for C or Fortran entry points srcpath Path to the source files in a normal toolbox it should be the directory containing the buildersrclangsce script which should be the script calling this function Default is current directory libs string matrix giving extra libraries needed for shared library creation ldflags optional character string It can be used to add specific linker options in the generated Makefile Default value is cflags optional character string It can be used to add specific C compiler options in the generated Make file Default value is fflags optional character string It can be used to add specific Fortran compiler options in the generated Makefile Default value is cc optional character string It can be used to specify a C compiler Default value is libname optional character string The name of the generated shared library default value is and in this case the name is derived from names1 loadername character string The pathname of the loader file default value is loadersce makename character string The pathname of the Makefile file without extension default value Makelib Examples Recommended usage tbxbuildsrccsumcsub csumccsubc c getabsolutefilepathbuildercsce tbxbuildsrc 2163 See Also ilibforlink Authors SL 2164 Name tbxbuildergateway Run buildergatewaysce script if it exists toolbox compilation process tbxbuildergatewaytoolboxpath Parameters toolboxpath Root directory of toolbox sources buildergatewaysce script will be searched in the scigateway subdirectory of this directory Examples Recommended usage tbxbuildergatewaygetabsolutefilepathbuildersce Authors SL 2165 Name tbxbuildergatewaylang Run buildergatewaylanguagesce script if it exists toolbox compi lation process tbxbuildergatewaylanglang tbxbuildergatewaylanglang gwpath Parameters lang Language of sources files the buildergatewaylangsce script will be searched in the subdi rectory lang eg fortran of the gwpath directory gwpath Path to the sources of the gateway in a normal toolbox it should be the directory containing the buildergatewaysce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildergatewaylangfortran getabsolutefilepathbuildergatewaysce Authors SL 2166 Name tbxbuilderhelp Run builderhelpsce script if it exists toolbox compilation process tbxbuilderhelptoolboxpath Parameters toolboxpath Root directory of toolbox sources builderhelpsce script will be searched in the help subdirec tory of this directory Examples Recommended usage tbxbuilderhelpgetabsolutefilepathbuildersce Authors SL 2167 Name tbxbuilderhelplang Run buildhelpsce script if it exists toolbox compilation process tbxbuilderhelplanglang tbxbuilderhelplanglang helppath Parameters lang Language of help files to use the buildhelpsce script will be searched in the subdirectory lang eg enUS of the helppath directory helppath Path to help directory in a normal toolbox it should be the directory containing the builderhelpsce script which should be the script calling this function Default is current direc tory Examples Recommended usage tbxbuilderhelplangenUS getabsolutefilepathbuilderhelpsce Authors SL 2168 Name tbxbuildermacros Run buildmacrossce script if it exists toolbox compilation process tbxbuildermacrostoolboxpath Parameters toolboxpath Root directory of toolbox sources buildmacrossce script will be searched in the macros subdi rectory of this directory Examples Recommended usage tbxbuildermacrosgetabsolutefilepathbuildersce Authors SL 2169 Name tbxbuildersrc Run buildersrcsce script if it exists toolbox compilation process tbxbuildersrctoolboxpath Parameters toolboxpath Root directory of toolbox sources buildersrcsce script will be searched in the src subdirectory of this directory Examples Recommended usage tbxbuildersrcgetabsolutefilepathbuildersce Authors SL 2170 Name tbxbuildersrclang Run builderlanguagesce script if it exists toolbox compilation process tbxbuildersrclanglang tbxbuildersrclanglang srcpath Parameters lang Language of sources files the builderlangsce script will be searched in the subdirectory lang eg fortran of the srcpath directory srcpath Path to the sources in a normal toolbox it should be the directory containing the buildersrcsce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildersrclangfortran getabsolutefilepathbuildersrcsce Authors SL 2171 Name testrun Launch tests N testrun N testrunmoduletestnameoptions Parameters module a vector of string It can be the name of a module or the absolute path of a toolbox testname a vector of string options a vector of string nocheckref does not check if the dia and diaref are equal nocheckerroroutput createref create the diaref file and does not check if the dia and diaref are equal list does not perform the tests but displays a list of available tests help display some examples about how to use this command modenw add the nw option to the launch modenwni add the nwni option to the launch nonregtest runs only the nonregression tests skipping unit tests unittest runs only the unit tests skipping nonregression tests skiptests Description Search for tst files in the unit test and nonregression test library execute them and display a report about success of failures The tst files are searched in directories SCImodulestestsunittests and SCImodulestestsnonregtests Whenever a test is executed a dia file is generated which contains the full list of commands executed along with message which appears in the console When the script is done the dia file is compared with the diaref file which is expected to be in the same directory as the tst file If the two file are different the test fails Special tags may be inserted in the tst file which help to control the processing of the corresponding test These tags are expected to be found in Scilab comments These are the available tags INTERACTIVE TEST This test will be skipped because it is interactive NOT FIXED This test will be skipped because it is a known but unfixed bug TEST WITH GRAPHIC This test will not be executed if the option modenwni is used NO TRY CATCH testrun 2172 NO CHECK ERROR OUTPUT The error output file is not checked NO CHECK REF The dia and the diaref files are not compared ENGLISH IMPOSED This test will be executed with the l enUS option FRENCH IMPOSED This test will be executed with the l frFR option JVM NOT MANDATORY This test will be executed with the nwni mode by default WINDOWS ONLY If the operating system isnt Windows the test is skipped UNIX ONLY If the operating system isnt an unix OS the test is skipped LINUX ONLY If the operating system isnt Linux the test is skipped MACOSX ONLY If the operating system isnt MacOSX the test is skipped Each test is executed in a separated process created with the host command That enables the current command to continue even if the test as created an unstable environment It also enables the tests to be independent from one another Platformspecific tests It may happen that the output of a test depends on the platform on which it is executed In this case the ref file cannot be correct for all platforms and unit tests may fail for some platform In this case we can create a default ref and create additionnal ref file for each platform The various platformspecific ref files must have one of the following extensions unixdiaref for Unix platform linuxdiaref for Linux platform windiaref for Windows platform macosxdiaref for Mac OS X platform The algorithm is the following First the ref is considered If this file does not exist the plat formspecific ref file is examined depending on the current platform on windows platforms windiaref on Max OS X platforms unixdiaref macosxdiaref on Linux platforms unixdiaref linuxdiaref Examples Launch all tests testrun testrun testrun Test one or several module Test one module testrun 2173 testruntime Test several modules testruntimestring Test a submodule testrunoptimizationneldermead Refer to a module by its path testrunSCImodulescore Launch a specific test One specific test testruntimedatenum Several tests testruntimedatenumcalendar Skip some tests testruntimedatenumcalendarskiptests Options does not check if the dia and diaref are equal testruntimedatenumnocheckref Create the diaref file and does not check if the dia and diaref are equal testruncreateref Does not perform the tests but displays a list of available tests testrunlist Display some examples about how to use this command testrunhelp Runs only the nonregression tests skipping unit tests testrunnonregtest Runs only the unit tests skipping nonregression tests testrununittest Do not check the error output std err testrunbooleanbug2799nocheckerroroutput Combine several options testrunnocheckrefmodenw Internal Design The tests are performed in the temporary directory not in the directory which originaly contain the tests files The tst file is copied into the temporary directory the test is performed and the diaref is copied back into the original location testrun 2174 The tst script is not run as is Instead a header and a footer are inserted at the beginning and at the end of the tst at the time the script is copied into the temporary directory The role of this modification is to redirect the output messages into the dia file so that the user can have a log file once the test is performed Authors Pierre Maréchal Michael Baudin Parte XLV Ferramentas de Demonstração 2176 Nom demobegin begin a demonstration demobegin Description The function demobegin is used to begin a demonstration It sets the script and the values in mode of non display on the console save the environment variables in a temporary file and save the width of the console This function shall be used with the function demoend Voir Aussi demoend demorun demomessage Auteurs GH 2177 Name demochoose create a dialog box for the choice of options num demochoosefil Description The function demochoose create a dialog box for the choice of options It takes as argument the binary file fil This file is built by a sce file written like below It shall contain the variables choice an array of text within bracket the different options and titl the title of the dialog box After that the sce file shall save both variables in the binary file in argument Before the use of demochoose the sce file shall be executed The function demochoose returns the number of line chosen in the options array Examples execSCIdemoscontrolpidpidch2sce ndemochooseSCIdemoscontrolpidpidch2bin select n case 0 break case 1 mode1 case 2 mode1 end See Also xchoose demomdialog Authors GH 2178 Name democompiler test the presence of a compileur status democompiler Description The function democompiler asks the computer if it owns a compileur C or not It returns a boolean indicating wether the compiler exists or not Examples select num case 0 return case 2 then st democompiler The compiler will be used if stt then mode0 wheelbuildandload end case 1 then A precomputed value xreadpathxwrt8301 wheelgwheelgs showx end See Also findmsvccompiler Authors GH 2179 Nom demoend completes a demonstration demoend Description The function demoend is used to complete a demonstration It shall be used complementarily with the function demobegin It resets the state of the environment as it was before to use the function demobegin width of the console and the variables value Voir Aussi demobegin demorun demomessage Auteurs GH 2180 Name demofilechoice choose and executes an item within a list demofilechoicepathch Description The function demofilechoice choose and executes an item chosen in the demolist variable that shall be written above The variable demolist is a text matrix whose first column contains names of items displayed in an options window and whose second column contains the names of the files that will be executed The title of the options window is Choose a demo The path variable is the access to the files called in the second column The ch variable allows to avoid the special cases root and anim that are used in peculiar demonstrations of Scilab Then you have to enter another word than root or ch no for example If you choose to cancel the options window the console is put back to its previous width Examples demolistnpendulumnpendnpendgatewaysce Wheel simulationwheel2wheelgatewaysce Bike Simulationbikebikegatewaysce ODESodeodedem DAESdaedaedem demofilechoiceSCIdemossimulationno See Also demofunctionchoice Authors GH 2181 Name demofunctionchoice choose and execute an item within a list demofunctionchoice Description The function demofunctionchoice choose and execute an item chosen in the variable demolist that shall appear above The variable demolist is a text matrix whose first column contains item names displayed in an options window and whose second column contains the function that will be called The title of the options window is Choose a demo If the options window is cancelled the console is put back to its previous width Examples demolist Simulation of a binomial random variableset figurestyle newclfBinomialT Simulation of a discrete random variableset figurestyle newclfRndDiscT Simulation of a geometric random variableset figurestyle newclfGeomT1000 Simulation of a Poisson random variableset figurestyle newclfPoissonT Simulation of an exponential random variableset figurestyle newclfExpT Simulation of a Weibull random variableset figurestyle newclfWeibullT Simulation of an hyper geometric random variableset figurestyle newclfHyperGeomT Simulation of an Erlang random variableset figurestyle newclfErlangT demofunctionchoice See Also demofilechoice Authors GH 2182 Name demomdialog create a dialog box resp demomdialogfil Description The function demomdialog create a dialog box It takes as argument a binary file This file is built by a sce file written like below It shall contain the variables titl the title a the dialog box namevar the name of the fields to fill and value the values written by default After this these three variables shall be saved in the binary file The use of demomdialog shall be preceded by the execution of the sce associated The function demomdialog returns resp the values chosen by the user Examples execSCIdemoscontrolpidpiddial4sce defvdemomdialogSCIdemoscontrolpidpiddial4bin if defv then warningDemo stopsreturnend See Also demochoose xmdialog xdialog Authors GH 2183 Name demomessage display a message demomessagefil Description The function demomessage displays the text message within the file fil given in argument Examples demomessageSCIdemoscontrolpidpid3sce See Also demorun messagebox demobegin demoend Authors GH 2184 Name demorun script file execution demorunfil Description The function demorun executes a script in the file fil given in argument See Also exec demomessage demobegin demoend Authors GH Parte XLVI Planilhas 2186 Name readxls lê um arquivo Excel sheets readxlsfilepath Parâmetros filepath string o endereço do arquivo Excel sheets um mlist de tipo xls com um campo chamado sheets Descrição Dado um endereço de um arquivo Excel esta função retorna uma estrutura de dados mlist do tipo xls com um campo chamado sheets O campo sheets contém uma lista da estutura de dados folha sheetmlistxlssheetnametextvaluesheetnameTextValue onde sheetname é um string contendo o nome da folha Text é uma matriz de strings que contém os strings e todas as células Value é uma matriz de números que contém todos os valores das células AVISO apenas arquivos Excel BIFF8 última versão do Excel são manipulados Exemplos Sheets readxlsSCImodulesspreadsheetdemosxlst1xls algumas operações básicas sobre Sheets typeofSheets s1Sheets1 obtendo a primeira folha typeofs1 s1value obtendo o campo do valor da primeira folha s1text obtendo o campo do texto da primeira folha s12 obtendo a segunda linha da folha typeofs12 editvar s1 Ver Também xlsopen xlsread Autores Pierrick Mode INRIA Serge Steer INRIA Funções Utilizadas Esta função é baseada nas funções Scilab xlsopen e xlsread 2187 Name xlsopen abre um arquivo Excel para leitura fdSSTSheetnamesSheetpos xlsopenfilepath Parâmetros filepath string o endereço do arquivo Excel fd número a unidade lógica do fluxo de dados do Excel SST vetor de todos os strings que aparecem na folha do Excel Sheetnames vetor de strings os nomes das folhas Sheetpos vetor de númerosas posições dos inícios das folhas no fluxo de dados do Excel Descrição Esta função primeiro analisa a estrutura de dados ole2 associada ao dado arquivo para extrair o fluxo de dado do Excel no qual está contido Após isso o fluxo de dados do Excel é salvo no diretório TMDIR e aberto Uma unidade lógica fd aponta para este arquivo temporário Então a primeira folha neste fluxo é lida para se obter informações globais como o número de folhas o nome das folhas Sheetnames endereços das folhas dentro do fluxo Sheetpos e SST que contém todos os strings utilizados nas folhas Os dados fd e Sheetpos devem ser passados para xlsread para se ler as folhas de dados A função readxls pode ser usada para se ler todo um arquivo Excel em uma função através de uma única chamada de função AVISO apenas arquivos Excel BIFF8 última versão do Excel 2003 são manipulados Exemplos Decodificando o arquivo ole extraindo e abrindo o fluxo de dados do Excel fdSSTSheetnamesSheetpos xlsopenSCImodulesspreadsheetdemosxlsTest1xls Lendo a primeira folha de dados ValueTextInd xlsreadfdSheetpos1 fechando o fluxo da planilha mclosefd Ver Também xlsread readxls Autores Pierrick Mode INRIA xlsopen 2188 Serge Steer INRIA Bibliografia Esta função é baseada na documentação do arquivo ole2 da Microsoft httpchicagosourceforgenet develdocsole e na descrição do OpenOffice sobre fluxo de dados do Excel httpscopenofficeorg spreadsheetfileformatpdf Funções Utilizadas O procedure ripole014 httpwwwpldanielscomripole é utilizado para extrair do arquivo ole o fluxo de dados da planilha 2189 Name xlsread lê uma folha em um arquivo Excel ValueTextInd xlsreadfdSheetpos Parâmetros fd um número a unidade lógica do fluxo de dados do Excel retornado por xlsopen Sheetpos um número a posição do início da folha no fluxo de dados Excel Esta posição é uma daquelas retornadas por xlsopen Value matriz de números os dados numéricos encontrados na folha A célula sem valores numéricos é representada por valores NaN TextInd uma matriz de índices com o mesmo tamanho que Value Os índices zeros indicam que não ex istem strings na celula Excel correspondente Um índice positivo i aponta para o string SSTi onde SST é dado por xlsopen Descrição Esta função lê uma folha do Excel dada uma unidade lógica em um fluxo de dados do Excel e a posição do início da folha neste fluxo de dados Ela retorna os dados numéricos e os strings contidos nas células do Excel A função readxls pode ser utilizada para ler todo um arquivo Excel em uma função utilizando apenas uma chamada a função AVISO apenas arquivos Excel BIFF8 última versão do Excel são manipulados Exemplos decodificando um arquivo ole extraindo e abrindo um fluxo de dados do Excel fdSSTSheetnamesSheetpos xlsopenSCImodulesspreadsheetdemosxlsTest1xls lendo a primeira folha de dados ValueTextInd xlsreadfdSheetpos1 fechando o fluxo de dados da planilha mclosefd Ver Também xlsopen readxls Autores Pierrick Mode INRIA Serge Steer INRIA xlsread 2190 Bibliografia Esta função é baseada na descrição do OpenOffice sobre fluxo de dados httpscopenofficeorg spreadsheetfileformatpdf Funções Utilizadas Esta função utiliza o arquivo xlsc que pode ser encontrado em uma versãofonte do Scilab no diretório directory SCIDIRmodulesspreadsheetsrcc 2191 Name excel2sci obsolete see readcsv See Also readcsv writecsv 2192 Name readcsv Read commaseparated value file M readcsvfname sep Parameters fname a character string The file path sep a character string Field separator used default value is M a matrix of strings Description Given an ascii file with delimited fields for instance created by a spreadsheet using Text and comma format readcsvfname returns the corresponding Scilab matrix of strings Use readcsvfnamesep for another choice of separator Note You may eval all or part of M using function evstr in order to convert string variables into numeric variables Examples create a file with some data separated with tab A 150 mputlstrcatstringAascii9 TMPDIR foocsv read csv file B readcsvTMPDIR foocsv eval B C evstrB compares original data and result andA C See Also writecsv evstr Authors Allan CORNET 2193 Name writecsv Read commaseparated value file writecsvM filename Parameters filename a character string The file path M a matrix of strings Description writecsvM filename writes matrix M into filename as commaseparated values The filename input is a string Examples save a matrix as csv file format A 110 01 writecsvA TMPDIR datascsv read as text mgetlTMPDIR datascsv r readcsvTMPDIR datascsvascii9 r strsubstr evstrr See Also readcsv evstr mgetl Authors Allan CORNET Parte XLVII callscilab API 2195 Name Boolean management How to manage Scilabs boolean read and write process using callscilab and apiscilab Description This help describes how boolean and matrix of booleans can be handle through the Call Scilab API and api Scilab There are several functions which can be used to read write from the memory of Scilab These functions are described in dedicated pages Note Access to variables is done through api Scilab named variable Examples Write a matrix of boolean into Scilab BF F T F F F F T Note that it is done column by column int B00001001 Declare the matrix int rowB2 colB4 Size of the matrix char variableNameB B Write it into Scilabs memory createNamedMatrixOfBooleanpvApiCtx variableNameB rowB colB B Prior to Scilab 52 C2FcwritebmatvariableNameB rowB colB B strlenvariableNameB printfDisplay from Scilab of B SendScilabJobdispB Display B Read the previously declared matrix of boolean B int rowB 0 colB 0 lp 0 int i 0 j 0 int matrixOfBooleanB NULL Int instead of double char variableToBeRetrievedB B First retrieve the size of the matrix readNamedMatrixOfBooleanpvApiCtx variableToBeRetrievedB rowB colB NULL Prior to Scilab 52 C2FcmatbptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfBooleanBintmallocrowBcolBsizeofint Load the matrix Boolean management 2196 readNamedMatrixOfBooleanpvApiCtx variableToBeRetrievedB rowB colB matrixOfBooleanB Prior to Scilab 52 C2FcreadbmatvariableToBeRetrievedBrowBcolBmatrixOfBooleanBstrlenvariableToBeRetrievedB printf printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expects printfd matrixOfBooleanBi rowB j printf New row of the matrix See Also APIScilab Boolean reading APIScilab Boolean writing SendScilabJob StartScilab CallScilab Double Management CallScilab Complex Management CallScilab String Management APIScilab Double Reading APIScilab Double Writing APIScilab String Reading APIScilab String Writing Authors Sylvestre Ledru 2197 Name Complex management How to manage Scilabs complex variable read and write process using callscilab Description This help describes how doubles and matrix of complex can be handle through the Call Scilab API There are several functions which can be used to read write from the memory of Scilab These functions are described in dedicated pages Note Access to variables is done through api Scilab named variable Examples Write a matrix into Scilab B1i 4i 212i 3 3 9 842i 2 Note that it is done column by column double B13492832 double Bimg10233102054223123 Declare the matrix Prior to Scilab 52 double B1349283210233102054223123 int rowB2 colB4 Size of the matrix char variableNameB B Write it into Scilabs memory createNamedComplexMatrixOfDoublepvApiCtxvariableNameBrowBcolB B Bimg Prior to Scilab 52 2FcwritecmatvariableNameB rowB colB B strlenvariableNameB printf printfDisplay from Scilab of B SendScilabJobdispB Display B int rowB 0 colB 0 lp 0 int i 0j 0 double matrixOfComplexB NULL double matrixOfComplexBimg NULL char variableToBeRetrievedB B First retrieve the size of the matrix readNamedComplexMatrixOfDoublepvApiCtx variableToBeRetrievedB rowB colB NULL NULL Complex management 2198 Prior to Scilab 52 C2FcmatcptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfComplexB doublemallocrowBcolBsizeofdouble matrixOfComplexBimg doublemallocrowBcolBsizeofdouble Load the matrix readNamedComplexMatrixOfDoublepvApiCtx variableToBeRetrievedB rowB colB matrixOfComplexB matrixOfComplexBimg Prior to Scilab 52 C2FcreadcmatvariableToBeRetrievedBrowBcolBmatrixOfComplexBstrlenvariableToBeRetrievedB printf printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printf52f 52fi matrixOfComplexBi rowB jmatrixOfComplexBimgi rowB j printf New row of the matrix See Also CallScilabapi Scilabcwritecmat creadcmat SendScilabJob StartScilab CallScilab Complex Management CallScilab Boolean Management CallScilab String Management APIScilab Boolean Reading APIScilab Boolean Writing APIScilab String Reading APIScilab String Writing Authors Sylvestre Ledru 2199 Name DisableInteractiveMode Disables some features plotting gui creation TclTk and leaves only the computing engine Synopsis void DisableInteractiveModevoid Description Calling this fonction will disable some features of Scilab Examples A simple DisableInteractiveMode example DisableInteractiveMode int codeSendScilabJobplot3d This will failed since plot3d is among the disable features if code0 char lastjob4096 if GetLastJoblastjob4096 printfFailed command s lastjob See Also CallScilabapi ScilabCompile and run with callscilab SendScilabJob TerminateScilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2200 Name Double management How to manage Scilabs variable read and write process using callscilab and apiscilab Description This help describes how doubles and matrix of doubles can be handle through the Call Scilab API and api Scilab There are several functions which can be used to read write from the memory of Scilab These functions are described in dedicated pages Note that the default type of a numeric value in Scilab is double For example in a1 or a12 a will be consider as a double Note Access to variables is done through api Scilab named variable Examples Write a matrix into Scilab B1 4 2 3 3 9 8 2 Note that it is done column by column double B 13492832 Declare the matrix int rowB 2 colB 4 Size of the matrix char variableNameB B Write it into Scilabs memory createNamedMatrixOfDoublepvApiCtxvariableNameBrowBcolB B pvApiCtx is a global variable Prior to Scilab 52 C2FcwritematvariableNameB rowB colB B strlenvariableNameB printf printfDisplay from Scilab of B SendScilabJobdispB Display B Read the previously declared matrix of double B int rowB 0 colB 0 lp 0 double matrixOfDoubleB NULL int i 0 j 0 char variableToBeRetrievedB B First retrieve the size of the matrix readNamedMatrixOfDoublepvApiCtx variableToBeRetrievedB rowB colB NULL Prior to Scilab 52 C2FcmatptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Double management 2201 Alloc the memory matrixOfDoubleB doublemallocrowBcolBsizeofdouble Load the matrix readNamedMatrixOfDoublepvApiCtx variableToBeRetrievedB rowB colB matrixOfDoubleB Prior to Scilab 52 C2FcreadmatvariableToBeRetrievedBrowBcolBmatrixOfDoubleBstrlenvariableToBeRetrievedB printf printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printf52f matrixOfDoubleBi rowB j printf New row of the matrix See Also CallScilabapi ScilabAPIScilab Double reading APIScilab Double writing SendScilabJob StartScilab CallScilab BooleanManagement CallScilab ComplexManagement CallScilab StringManagement APIScilab Boolean Reading APIScilab Boolean Writing APIScilab String Reading APIScilab String Writing Authors Sylvestre Ledru 2202 Name GetLastJob Returns the latest job sent to Scilab engine Synopsis BOOL GetLastJobchar JOBint nbcharsJOB Description This fonction returns the latest job sent to Scilab engine with the command SendScilabJob or Send ScilabJobs This can be used to display a command which failed BOOL is just a simple typedef on int typedef int BOOL TRUE is defined on 1 define TRUE 1 and FALSE is defined on 0 define FALSE 0 Parameters JOB a standard C char which will be filled with the latest job nbcharsJOB The number of char of JOB returns 1 TRUE if the operation is successfull 0 FALSE if an error during initialization occured Examples A simple GetLastJob example See SCImodulescallscilabexamplesbasicExamplesGetLastJobc for the full code int codeSendScilabJobfailedMyCurrentJobpi30 if code0 char lastjob4096 if GetLastJoblastjob4096 printfFailed command s lastjob See Also CallScilabapi ScilabCompile and run with callscilab SendScilabJob TerminateScilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2203 Name ScilabHaveAGraph Check if any Scilab graphics have been opened Synopsis int ScilabHaveAGraphvoid Description Returns if there is any Scilab graphics opened Examples A simple ScilabHaveAGraph example int codeSendScilabJobplot3d This will failed since plot3d is among the disable features if ScilabHaveAGraph printfGraphics else printfNO Graphics See Also CallScilabapi ScilabCompile and run with callscilab SendScilabJob TerminateScilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2204 Name SendScilabJob Send a Scilab task from a CC code callscilab Synopsis int SendScilabJobchar job Description This fonction is provided in callscilab This function send a task which will be proccessed by the Scilab engine Parameters job a standard C char containing the Scilab instructions returns 0 is the operation is successfull 1 if Call Scilab has not been able to write the job into Scilab 2 or 3 if Call Scilab has not been able to read the error code from Scilab 4 if Call Scilab has not been able to allocate the job Examples A simple SendScilabJob example if SendScilabJobdispunfinished quote0 This will fail printfAn error occured SendScilabJobmyMatrixsamplefor the help See Also CallScilabapi ScilabCompile and run with callscilab SendScilabJob Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2205 Name SendScilabJobs Send Scilab tasks from a CC code callscilab Synopsis int SendScilabJobschar jobs int numberjobs Description This fonction is provided in callscilab This function send many tasks which will be proccessed by the Scilab engine Note that the ending is not mandatory at the end of a command Parameters jobs an array of standard C char containing the Scilab instructions numberjobs The number of the Scilab instructions returns 0 is all the operations are successful 10 if 0 and 10 when an error occurred in the execution Examples A simple SendScilabJobs example char jobs3 jobs0a 1 jobs1b 3 jobs2c a b SendScilabJobsjobs3 SendScilabJobdispc Will display 4 See Also CallScilabapi ScilabSendScilabJob Compile and run with callscilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2206 Name StartScilab Initializes and starts Scilab engine in Call Scilab Synopsis BOOL StartScilabchar SCIpath char ScilabStartup int Stacksize Description This fonction starts the Scilab engine This is mandatory to use SendScilabJob functions and to manage Scilabs data BOOL is just a simple typedef on int typedef int BOOL TRUE is defined on 1 define TRUE 1 and FALSE is defined on 0 define FALSE 0 Parameters SCIpath a standard C char containing the path to Scilab data This argument is mandatory under Linux Unix or Mac OS X Under Windows if SCIpath is NULL Scilab will find the path ScilabStartup a standard C char containing the path to Scilab startup script scilabstart If ScilabStartup is NULL Scilab will use the default path detected from SCIpath Stacksize a standard int defining the size of the Scilab stack If Stacksize is NULL Scilab will use the default stacksize of Scilab returns 1 TRUE if the operation is successfull 0 FALSE if an error during initialization occured Examples A simple StartScilab example if StartScilabgetenvSCINULLNULL FALSE fprintfstderrError while calling StartScilab return 1 See Also CallScilabapi Scilab Compile and run with callscilab SendScilabJob TerminateScilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2207 Name String management How to manage Scilabs String read and write process using callscilab and apiscilab Description This help describes how strings and matrix of strings can be handle through the Call Scilab API and api Scilab There are several functions which can be used to read write from the memory of Scilab These functions are described in dedicated pages Note Access to variables is done through api Scilab named variable Examples This example shows how to write a Scilab string in Scilab engine It is the equivalent to Amy Message in Scilab interpretor See modulescallscilabexamplesbasicExamplesreadwritestringc StartScilab int row 1 col 1 Size of the matrix Declare the string char myMatrixOfString charmallocsizeofchar row col myMatrixOfString0my Message char variableName A Write it into Scilabs memory createNamedMatrixOfStringpvApiCtx variableName row col myMatrixOfString Prior to Scilab 52 C2FcwritechainvariableName sizeOfMyString myString strlenvariableName sizeOfMyString printfDisplay from Scilab of A SendScilabJobdispA Display A Load the previously set variable A See modulescallscilabexamplesbasicExamplesreadwritestringc char variableToBeRetrievedA int iRows 0 int iCols 0 int ij int piAddr NULL int piLen NULL char pstData NULL fisrt call to retrieve dimensions readNamedMatrixOfStringpvApiCtxvariableToBeRetrievediRows iCols NULL NULL piLen intmallocsizeofint iRows iCols second call to retrieve length of each string readNamedMatrixOfStringpvApiCtxvariableToBeRetrieved iRows iCols piLen NULL String management 2208 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination third call to retrieve data readNamedMatrixOfStringpvApiCtx variableToBeRetrieved iRows iCols piLen pstData printf printfLoad and display of A forj 0 j iCols j fori 0 i iRows i Display the formated matrix with same scilab indice printfdd s j1i1pstDataj iRows i printf freepiLen fori 0 i iRows iCols i freepstDatai freepstData See Also CallScilabapi Scilab cwritechain creadchain SendScilabJob StartScilab CallScilab Boolean Management CallScilab Double Management APIScilab Boolean Reading APIScilab Boolean Writing APIScilab Double Reading APIScilab Double Writing Complex Management Authors Sylvestre Ledru 2209 Name TerminateScilab Stops and terminates Scilab engine in Call Scilab Synopsis BOOL TerminateScilabchar ScilabQuit Description This fonction stops the Scilab engine It is strongly recommanded to call this function at the end when using Call Scilab BOOL is just a simple typedef on int typedef int BOOL TRUE is defined on 1 define TRUE 1 and FALSE is defined on 0 define FALSE 0 Parameters ScilabQuit a standard C char containing the path to Scilab quit script scilabquit If ScilabStartup is NULL Scilab will use the default path detected from SCIpath returns 1 TRUE if the operation is successfull 0 FALSE if an error during initialization occured Examples A simple TerminateScilab example if TerminateScilabNULL FALSE fprintfstderrError while calling TerminateScilab return 2 See Also CallScilabapi Scilab Compile and run with callscilab StartScilab SendScilabJob Double Man agement Boolean Management Complex Management String Management Authors Sylvestre Ledru 2210 Name callscilab callscilab is an interface which provides the ability to call Scilab engine from CC code Description Scilab offers the possibility to be called from a native CC application Thanks to this module it is possible to call Scilab from CC in order to interface Scilabs features from an other codeapplication or to be able to interface Scilabs features from an other language Since Scilab 520 all Scilab datatype can be handle by callscilab This is done thanks to APIScilab This help describes the features of the callscilab API Note The javasci module is based on callscilab Note old APIs stackXh will not be available after Scilab 60 included Examples A simple callscilab example include stdioh stderr include stackch Provide functions to access to the memory of Scilab include callscilabh Provide functions to call Scilab engine Filename simplecallscilabc int mainvoid INITIALIZATION ifdef MSCVER if StartScilabNULLNULLNULL FALSE else if StartScilabgetenvSCINULLNULL FALSE endif fprintfstderrError while calling StartScilab return 1 ACTUAL Scilab TASKS SendScilabJobmyMatrixsamplefor the help SendScilabJobdispmyMatrix Will display sample for the help SendScilabJobdisp234439 Will display 42 42 TERMINATION if TerminateScilabNULL FALSE fprintfstderrError while calling TerminateScilab return 2 return 0 callscilab 2211 See Also api ScilabCompile and run with callscilab Matrix Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2212 Name Compile and run with Call Scilab How to compile a native application based on or using Scilab Compilation To compile a native code based on Call Scilab it is necessary to define some arguments variables and paths CFLAGS Call Scilab needs to have access to the headers of Scilab core and call Scilab module LinuxUnixMacOSX In the binary version of Scilab CFLAGS must be set to pathtoscilabincludescilabcore and pathtoscilabincludescilabcallscilab In the source tree of Scilab CFLAGS must be set to pathtoscilabmodulescoreincludes and pathtoscilabmodulescallscilabincludes Windows LDLIBRARYPATH Paths to libscilabso and libjavasciso or dll jnilib LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilablibscilab In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabmod ulescallscilablibs and pathtoscilablibs LDFLAGS The name of the library to link against LinuxUnixMacOSX It is only mandatory to link against scilab This should include the other libraries A sample Makefile building a C code using Call Scilab using Scilab built in it source tree PATHSCILAB pathtoscilabsources SCILABCFLAGS IPATHSCILABmodulescoreincludes IPATHSCILABmodulescallscilabincludes SCILABLDFLAGS lscilab PATHTOLIBSCILAB PATHSCILABmoduleslibs PATHTOLIBCALLSCILAB PATHSCILABmodulescallscilablibs all simplecallscilabc export LDLIBRARYPATHPATHTOLIBSCILABPATHTOLIBCALLSCILAB gcc o myExample SCILABLDFLAGS LPATHTOLIBSCILAB LPATHTOLIBCALLSCILAB SCILABCFLAGS simplecallscilabc Running To run an application based on Call Scilab there are a few other things to set up Some global variables must me set SCI Path to Scilab files LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilabsharescilab Compile and run with Call Scilab 2213 In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabsource tree Windows LDLIBRARYPATH Paths to libscilabso and libjavasciso or dll jnilib LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilablibscilab In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabmod ulesjavascilibs and pathtoscilablibs LDLIBRARYPATH Java Paths to Java native libraries libjavaso libjvmso libhpiso It is usually provided by the operating system or by Scilab distribution Please note that wont be necessary in Scilab 52 LinuxUnix JAVAHOMEjrelibarch JAVAHOMEjrelibarchserver JAVAHOMEjrelib archnativethreads arch can be i386 etc Mac OS X Windows Note that two environnement variables are taken in account for specific needs SCIDISABLETK1 Disables Tk Tcls GUI SCIJAVAENABLEHEADLESS1 Launch Java in headless mode no AWTSwing Examples Serie of declarations to execute my binary With a Scilab source tree SCIpath to Scilab source tree export LDLIBRARYPATHSCImoduleslibsSCImodulescallscilablibsSCImodulesapiscilablibs With a Scilab binary SCIpath to Scilab binary export LDLIBRARYPATHSCIlibscilab Dont forget to update i386 to whatever is necessary export LDLIBRARYPATHLDLIBRARYPATHusrlibjvmjava6openjdkjrelibi386usrlibjvmjava6openjdkjrelibi386server export LDLIBRARYPATHLDLIBRARYPATHusrlibjvmjava6openjdkjrelibi386nativethreads export SCIpathtoscilab myExample sample for the help 42 42 See Also api Scilabcallscilab StartScilab SendScilabJob SendScilabJobs Double Management Boolean Management Complex Management String Management Compile and run with Call Scilab 2214 Authors Allan Cornet Sylvestre Ledru 2215 Name creadbmat obsolete Read a single boolean or a matrix of boolean from Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab Boolean reading for remplacement Synopsis int C2Fcreadbmatchar name int m int n int scimat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns scimat The actual matrix of boolean array of int Note that it is going to be stored in Scilab columnwise namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function creadbmat Using this function will retrieve a variable called name from Scilab memory into a standard C int Examples Load the previously set variable B See modulescallscilabexamplesbasicExamplesreadwritebooleanc int rowB 0 colB 0 lp 0 int i 0 j 0 int matrixOfBooleanB NULL Int instead of double char variableToBeRetrievedB B First retrieve the size of the matrix C2FcmatbptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfBooleanBintmallocrowBcolBsizeofint Load the matrix C2FcreadbmatvariableToBeRetrievedBrowBcolBmatrixOfBooleanBstrlenvariableToBeRetrievedB printf printfDisplay from B formated size d d rowB colB creadbmat obsolete 2216 forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printfd matrixOfBooleanBi rowB j printf New row of the matrix See Also CallScilabapi ScilabAPIScilab Boolean reading APIScilab Boolean writing SendScilabJob StartScilab cwritebmat Boolean Management Authors Sylvestre Ledru 2217 Name creadchain obsolete Read a single string from Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab String reading for remplacement Synopsis int C2Fcreadchainchar name int itslen char myString unsigned long namelen unsigned long myStringlen Parameters name The name of the future Scilab variable itslen The length of the future buffer usually use bsiz it skips the need to detect the size of a char This variable will be altered to contain the actual size of myString myString The actual String char which is going to content the content of the Scilab variable name namelen The length of the variable name fortran compatibility myStringlen The length of the string fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function creadchain Using this function will retrieve a variable called name from Scilab memory into a standard C char Examples Load the previously set variable A See modulescallscilabexamplesbasicExamplesreadwritestringc int sizeA 0 char myStringFromScilabbsiz Static char int lengthmyStringFromScilab bsiz Max size it is going to be changed by creadchain char variableToBeRetrievedA We are loading a single string from Scilab C2FcreadchainvariableToBeRetrievedlengthmyStringFromScilabmyStringFromScilabstrlenvariableToBeRetrievedstrlenmyStringFromScilab printf printfDisplay of A size d s lengthmyStringFromScilab myStringFromScilab See Also CallScilabapi ScilabAPIScilab String reading APIScilab String writing SendScilabJob StartScilab cwritechain String Management creadchain obsolete 2218 Authors Sylvestre Ledru 2219 Name creadcmat obsolete Read a single complex or a matrix of complex from Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab Complex double read ing for remplacement Synopsis int C2Fcreadcmatchar name int m int n double scimat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns scimat The actual matrix of complex array of double Note that it is going to be stored in Scilab colum nwise and the second half of the array is used for complex values namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function creadcmat Using this function will retrieve a variable called name from Scilab memory into a standard C double Examples Load the previously set variable B See modulescallscilabexamplesbasicExamplesreadwritecomplexmatrixc int rowB 0 colB 0 lp 0 int i 0j 0 double matrixOfComplexB NULL char variableToBeRetrievedB B First retrieve the size of the matrix C2FcmatcptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfComplexB doublemallocrowBcolB2sizeofdouble Load the matrix C2FcreadcmatvariableToBeRetrievedBrowBcolBmatrixOfComplexBstrlenvariableToBeRetrievedB printf creadcmat obsolete 2220 printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printf52f 52fi matrixOfComplexBi rowB jmatrixOfComplexBrowBcolBi rowB j printf New row of the matrix See Also CallScilabapi ScilabAPIScilab Complex double reading APIScilab Double writing SendScil abJob StartScilab cwritecmat Complex Management Authors Sylvestre Ledru 2221 Name creadmat obsolete Read a single double or a matrix of double from Scilab memory using callscilab Note that it is the default datatype in Scilab Starting with Scilab 52 this function is ob solete See APIScilab Double reading for remplacement Synopsis int C2Fcreadmatchar name int m int n double scimat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns scimat The actual matrix of double array of double Note that it is going to be stored in Scilab colum nwise namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function creadmat Using this function will retrieve a variable called name from Scilab memory into a standard C double Examples Load the previously set variable B See modulescallscilabexamplesbasicExamplesreadwritematrixc int rowB 0 colB 0 lp 0 double matrixOfDoubleB NULL int i 0 j 0 char variableToBeRetrievedB B First retrieve the size of the matrix C2FcmatptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfDoubleB doublemallocrowBcolBsizeofdouble Load the matrix C2FcreadmatvariableToBeRetrievedBrowBcolBmatrixOfDoubleBstrlenvariableToBeRetrievedB printf creadmat obsolete 2222 printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printf52f matrixOfDoubleBi rowB j printf New row of the matrix See Also CallScilabapi ScilabAPIScilab Double readingAPIScilab Double writing SendScilabJob StartScilab cwritemat Double Management Authors Sylvestre Ledru 2223 Name cwritebmat obsolete Write a single boolean or a matrix of boolean into Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab Boolean writing for remplacement Synopsis int C2Fcwritebmatchar name int m int n int mat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns mat The actual matrix of boolean array of int Note that it is going to be stored in Scilab columnwise namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function cwritebmat Using this function will basically do the same as A T F F T but straight into Scilab memory with callscilab Examples This example shows how to write a Scilab matrix of boolean in Scilab engine It is the equivalent to BF F T F F F F T in Scilab interpretor See modulescallscilabexamplesbasicExamplesreadwritebooleanc StartScilab int B00001001 Declare the matrix int rowB2 colB4 Size of the matrix char variableNameB B C2FcwritebmatvariableNameB rowB colB B strlenvariableNameB Write it into Scilabs memory printf printfDisplay from Scilab of B SendScilabJobdispB Display B See Also CallScilabapi ScilabAPIScilab Boolean reading APIScilab Boolean writing SendScilabJob StartScilab creadbmat Boolean Management cwritebmat obsolete 2224 Authors Sylvestre Ledru 2225 Name cwritechain obsolete Write a single string into Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab String writing for remplacement Synopsis int C2Fcwritechainchar name int myStringSize char myString unsigned long namelen unsigned long myStringlen Parameters name The name of the future Scilab variable myStringSize The length of the string which is going to be write into Scilab memory myString The actual String char namelen The length of the variable name fortran compatibility myStringlen The length of the string fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function cwritechain Using this function will basically do the same as A my own String but straight into Scilab memory with callscilab Examples This example shows how to write a Scilab string in Scilab engine It is the equivalent to Amy Message in Scilab interpretor See modulescallscilabexamplesbasicExamplesreadwritestringc StartScilab char myString my Message Declare the string char variableName A The name of the future variable in Scilab int sizeOfMyStringstrlenmyString C2FcwritechainvariableName sizeOfMyString myString strlenvariableName sizeOfMyString Write it into Scilabs memory printfDisplay from Scilab of A SendScilabJobdispA Display A See Also CallScilabapi ScilabAPIScilab String reading APIScilab String writing SendScilabJob StartScilab creadchains String Management cwritechain obsolete 2226 Authors Sylvestre Ledru 2227 Name cwritecmat obsolete Write a single complex or a matrix of complex into Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab Complex double writing for remplacement Synopsis int C2Fcwritecmat char name int m int n double mat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns mat The actual matrix of complex array of double Note that it is going to be stored in Scilab colum nwise and the second half of the array is used for complex values namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function cwritecmat Using this function will basically do the same as A 1i 3i 4 22i but straight into Scilab memory with callscilab Examples This example shows how to write a Scilab matrix of complex in Scilab engine Write a matrix into Scilab B1i 4i 212i 3 3 9 842i 2 Note that it is done column by column double B134928321010054200 Declare the matrix int rowB2 colB4 Size of the matrix char variableNameB B C2FcwritecmatvariableNameB rowB colB B strlenvariableNameB Write it into Scilabs memory printf printfDisplay from Scilab of B SendScilabJobdispB Display B cwritecmat obsolete 2228 See Also CallScilabapi ScilabAPIScilab Complex double reading APIScilab Complex double writing SendScilabJob StartScilab Complex Management creadcmat Authors Sylvestre Ledru 2229 Name cwritemat obsolete Write a single double or a matrix of double into Scilab memory using callscilab Note that it is the default datatype in Scilab Starting with Scilab 52 this function is ob solete See APIScilab Double writing for remplacement Synopsis int C2Fcwritematchar name int m int n int mat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns mat The actual matrix of double array of double Note that it is going to be stored in Scilab colum nwise namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function cwritemat Using this function will basically do the same as A 1 3 4 2 but straight into Scilab memory with callscilab Examples This example shows how to write a Scilab matrix of double in Scilab engine Write a matrix into Scilab B1 4 2 3 3 9 8 2 Note that it is done column by column See modulescallscilabexamplesbasicExamplesreadwritematrixc StartScilab double B 13492832 Declare the matrix int rowB 2 colB 4 Size of the matrix char variableNameB B C2FcwritematvariableNameB rowB colB B strlenvariableNameB Write it into Scilabs memory printf printfDisplay from Scilab of B SendScilabJobdispB Display A cwritemat obsolete 2230 See Also CallScilabapi Scilab APIScilab Double readingAPIScilab Double writing SendScilabJob StartScilab Double Management creadmat Authors Sylvestre Ledru 2231 Name fromc Checks if current Scilab is called from an external C program by StartScilab rfromc Parameters r a boolean Description Returns tChecks if current Scilab is called from an external C program or f if not See Also CallScilabapi Scilabfromjava 2232 Name fromjava Checks if current Scilab is called from javasci r fromjava Parameters r a boolean Description Returns t if Scilab is called from javasci or f if not See Also CallScilabapi Scilabfromc Parte XLVIII FFTW 2234 Name fftw Fast fourier transform based on the fftw library yfftwx yfftwxsign yfftwxsigndimincr yfftwxsigndim1 dim2 dimNincr1 incr2 incrN Parameters yx matrixvector of realcomplex data Inputoutput data to be transformed sign Integer 1 or 1 Set direct or inverse transform dim integer Set the dimension the length of the transform incr integer Set the stride the span of the transform Description This function realizes directinverse Discrete Fourier Transform DFT with the help of the FFTW library One can compute vector 2D MD transform with this function For more details of fftw syntax see fft scilab function For more details about FFTW library see FFTW Web site httpwwwfftworg Remark fftw function automatically stores his last parameters in memory to reuse it in a second time This improves greatly the time computation when consecutives calls with same parameters are per formed Examples simple vector direct transform a rand501irand501 y fftwa y fftwa1 inverse transform b fftwy1 2D transform a rand512512irand512512 y fftwa MD transform old calling sequence a rand1201 y a dim5 6 4incr1 5 30 for i13 fftw 2235 y fftwy1dimiincri end MD transform new calling sequence More efficient than old y fftwa15 6 41 5 30 b fftwy15 6 41 5 30 See Also fftwflags getfftwwisdom setfftwwisdom fftwforgetwisdom Bibliography Matteo Frigo and Steven G Johnson FFTW Manual fo version 312 June 2006 Available http wwwfftworg 2236 Name fftwflags set computation method of fast fourier transform of the fftw function aSfftwflagsx1x2 Parameters x1x2 Matrix of string or integers Entry to switch the method of fft computation for fftw a Integer Give the current value of the flag of the fftw function S String matrix Give the string value of the fftw flag Description This function enables the change of the unsigned flags parameter of the fftwplangurusplitdft function that is used in fftw function Default value is FFTWESTIMATE Accepted entries are FFTWMEASURE or 0 FFTWDESTROYINPUT or 1 FFTWUNALIGNED or 2 FFTWCONSERVEMEMORY or 4 FFTWEXHAUSTIVE or 8 FFTWPRESERVEINPUT or 16 FFTWPATIENT or 32 FFTWESTIMATE or 64 FFTWESTIMATEPATIENT or 128 FFTWBELIEVEPCOST or 256 FFTWNODFTR2HC or 512 FFTWNONONTHREADED or 1024 FFTWNOBUFFERING or 2048 FFTWNOINDIRECTOP or 4096 FFTWALLOWLARGEGENERIC or 8192 FFTWNORANKSPLITS or 16384 FFTWNOVRANKSPLITS or 32768 FFTWNOVRECURSE or 65536 fftwflags 2237 FFTWNOSIMD or 131072 FFTWNOSLOW or 262144 FFTWNOFIXEDRADIXLARGEN or 524288 FFTWALLOWPRUNING or 1048576 Rmk when using FFTWMEASUREFFTWPATIENTFFTWEXHAUSTIVE you must call two times fftw first call for initialisation second and others calls for computation Examples return the integer value of the flag fftwflags change flags fftwflagsFFTWMEASUREFFTWCONSERVEMEMORY change flags and display current value of fftw flags both integer and strings aSfftwflagsFFTWPATIENT See Also fftw 2238 Name fftwforgetwisdom Reset fftw wisdom fftwforgetwisdom Description This function reset the current fftw wisdom Examples return fftw wisdom txtgetfftwwisdom set fftw wisdom setfftwwisdomtxt reset fftw wisdom fftwforgetwisdom See Also fftw getfftwwisdom setfftwwisdom 2239 Name getfftwwisdom return fftw wisdom txtgetfftwwisdom Parameters txt String matrix that contains fftw wisdom Description This function return the fftw wisdom in a string matrix Examples return fftw wisdom txtgetfftwwisdom set fftw wisdom setfftwwisdomtxt reset fftw wisdom fftwforgetwisdom See Also fftw setfftwwisdom fftwforgetwisdom 2240 Name setfftwwisdom set fftw wisdom setfftwwisdomtxt Parameters txt String matrix that contains fftw wisdom Description This function set the fftw wisdom with a string matrix Examples return fftw wisdom txtgetfftwwisdom set fftw wisdom setfftwwisdomtxt reset fftw wisdom fftwforgetwisdom See Also fftw getfftwwisdom fftwforgetwisdom Parte XLIX Interfaces com UMFPACK 2242 Name PlotSparse plot the pattern of non nul elements of a sparse matrix PlotSparseA style Parameters A a sparse matrix style optional a string given the color andor the marker type of the form colormark where color may be a number referring the color you want to use in the current colormap If you use the std colormap then color may be one of the following letters k for black b for blue r for red g for green c for cyan m for magenta y for yellow t for turquoise G a dark green mark must be one of the following point plus x cross circled plus D filled diamond d diamond upper triangle v down triangle o circle by default you have b in fact the 2d color and this is also forced in case of error Description plot the pattern of non nul elements of a sparse matrix each non nul element is drawn with a marker For big matrix use essentially the point as marker Examples Adescriptionrefmtype ReadHBSparseSCImodulesumfpackexamplesarc130rua set figurestyle old PlotSparseAy xtitleref mtype description See Also ReadHBSparse Authors Bruno Pincon BrunoPinconiecnunancyfr 2243 Name ReadHBSparse read a HarwellBoeing sparse format file A description ref mtype ReadHBSparsefilename Parameters filename optional a string given the filename eventually preceeding by the path if filename is not given then the function use uigetfile to get filename interactively A the sparse matrix description a string given some information about the matrix ref a string given the reference of the matrix mtype a string given the type of the matrix Description An utility to read the HarwellBoeing sparse matrix format Currently dont work for unassembled matrix Also the eventual rhs vectors of the file are not returned Generally the file name is of the form refmtype where mtype is a 3 letters word abc given some information already inside the file on the matrix a RCP for realcomplexpattern no values given b SHZU for symmetrichermitianskew symmetricasymmetric c AE for assembledunassembled matrix case E is not treated by this func References Users Guide for the HarwellBoeing Sparse Matrix Collection Iain S Duff Roger G Grimes John G Lewis You may found this guide and numerous sparse matrices in the HarwellBoeing format at the University of Florida Sparse Matrix Collection web site httpwwwciseufleduresearchsparsematrices maintained by Tim Davis httpwwwciseufledudavis Examples A ReadHBSparseSCImodulesumfpackexamplesarc130rua See Also PlotSparse ReadHBSparse 2244 Authors Bruno Pincon BrunoPinconiecnunancyfr 2245 Name cond2sp computes an approximation of the 2norm condition number of a spd sparse matrix K2 lm vm lM vM cond2spA Cptr rtol itermax verb Parameters A a real symmetric positive definite sparse matrix Cptr a pointer to a Cholesky factorization got with taucschfact rtol optional relative tolerance default 1e3 see details in DESCRIPTION itermax optional maximum number of iterations in the underlying algorithms default 30 verb optional boolean must be t for displaying the intermediary results and f default if you dont want K2 estimated 2norm condition number K2 A2 A12 lMlm lm real positive scalar minimum eigenvalue vm associated eigenvector lM real positive scalar maximum eigenvalue vM associated eigenvector Description This quick and dirty function computes lMvM using the iterative power method and lmvm with the inverse iterative power method then K2 lMlm For each method the iterations are stopped until the following condition is met lnew loldlnew rtol but 4 iterations are nevertheless required and also the iterations are stopped if itermax is reached and a warning message is issued As the matrix is symmetric this is the rayleigh quotient which gives the estimated eigenvalue at each step lambda vAv You may called this function with named parameter for instance if you want to see the intermediary result without setting yourself the rtol and itermax parameters you may called this function with the syntax K2 lm vm lM vM cond2spA Cptr verbt cond2sp 2246 Caution Currently there is no verification for the input parameters Remark This function is intended to get an approximation of the 2norm condition number K2 and with the methods used the precision on the obtained eigenvectors vM and vm are generally not very good If you look for a smaller residual Av lv you may apply some inverse power iterations from v0 with the matrix B A l0speyeA For instance applied 5 such iterations for lmvm is done with l0 lm v0 vm or l0 lM v0 vM to polish lMvM B A l0speyeA LUp umflufactB vr v0 nstep 5 for i1nstep vr umflusolveLUp vr Axb B vr vrnormvr end umfludelLUp if you dont use anymore this factorization lr vrAvr normr0 normAv0 l0v0 normrr normAvr lrvr BauerFike error bound mprintf first estimated eigenvalue l0 e l0 mprintf ll0 Av0l0v0 e ll0l0 e r normr0 normr0l0 mprintf raffined estimated eigenvalue lr e lr mprintf llr Avrlrvr e llrlr e r normrr normrrlr Examples A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa Cptr taucschfactA K2 lm vm lM vM cond2spA Cptr 1e5 50 t taucschdelCptr See Also condestsp taucschfact rcond Authors Bruno Pincon BrunoPinconiecnunancyfr 2247 Name condestsp estimate the condition number of a sparse matrix K1 condestspA LUp t K1 condestspA LUp K1 condestspA t K1 condestspA Parameters A a real or complex square sparse matrix LUp optional a pointer to umf LU factors of A obtained by a call to umflufact if you have already computed the LU PAQ factors it is recommanded to give this optional parameter as the factorization may be time consuming t optional a positive integer default value 2 by increasing this one you may hope to get a better even exact estimate K1 estimated 1norm condition number of A Description Give an estimate of the 1norm condition number of the sparse matrix A by Algorithm 24 appearing in A block algorithm for matrix 1norm estimation with an application to 1norm pseudospectra Nicholas J Higham and Francoise Tisseur Siam J Matrix Anal Appl vol 21 No 4 pp 11851201 Noting the exact condition number K1e A1 A11 we have allways K1 K1e and this estimate gives in most case something superior to 12 K1e Examples A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 K1 condestspA verif by direct computation K1e normA1norminvfullA1 another example A ReadHBSparseSCImodulesumfpackexamplesarc130rua K1 condestspA this example is not so big so that we can do the verif condestsp 2248 K1e normA1norminvfullA1 if you have already the lu factors condestspALup is faster because lu factors are then not computed inside condestsp Lup umflufactA K1 condestspALup umfludelLup clear memory See Also umflufact rcond Authors Bruno Pincon BrunoPinconiecnunancyfr 2249 Name rafiter obsolete iterative refinement for a spd linear system xn rn rafiterA Cptr b x0 nbiter verb Parameters A a real symmetric positive definite sparse matrix Cptr a pointer to a Cholesky factorization got with taucschfact b column vector rhs of the linear system but matrix multiple rhs are allowed x0 first solution obtained with taucschsolveCptr b nbiter optional number of raffinement iterations default 2 verb optional boolean must be t for displaying the intermediary results and f default if you dont want xn new refined solution rn residual Axn b Description This function is somewhat obsolete use x taucschsolveCptrbA see taucschsolve which do one iterative refinement step To use if you want to improve a little the solution got with taucschsolve Note that with verbt the displayed internal steps are essentially meaningful in the case where b is a column vector Caution Currently there is no verification for the input parameters Examples A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa Cptr taucschfactA b randsizeA11 x0 taucschsolveCptr b normAx0 b xn rn rafiterA Cptr b x0 verbt normAxn b taucschdelCptr rafiter 2250 See Also taucschsolve taucschfact Authors Bruno Pincon BrunoPinconiecnunancyfr 2251 Name reswithprec computes the residual r Axb with precision rnorm2r reswithprecA x b Parameters A real or complex sparse matrix m x n x column vector n x 1 or matrix n x p b column vector m x 1 or matrix m x p r column vector m x 1 or matrix m x p norm2r scalar or vector 1 x p when b is a m x p matrix Description This function computes the residual of a linear system r Ax b together with its 2norm with the additionnal precision provided on Intel like FPU 80 bits in place of 64 if the compiler translate long double to use it Else one must get the same than using Ax b at the scilab level In both cases using r nr reswithprecAxb is faster than r Ax b and faster than r Ax b nr normr When p 1 norm2ri is the 2norm of the vector ri Examples A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa Cptr taucschfactA b randsizeA11 x0 taucschsolveCptr b normAx0 b normreswithprecA x0 b See Also rafiter Authors Bruno Pincon BrunoPinconiecnunancyfr 2252 Name taucschdel utility function used with taucschfact taucschdelCptr or taucschdel Parameters Cptr a pointer to a Cholesky factorization Description This function is used in conjunction with taucschfact and taucschsolve It clears the internal memory space used to store the Cholesky factorization got with taucschfact Use without argument it frees the memory for all the current scilab taucs Cholesky factorizations Examples see the example section of taucschfact See Also taucschfact taucschsolve taucschinfo taucschget Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2253 Name taucschfact cholesky factorisation of a sparse spd matrix Cptr taucschfactA Parameters A a sparse real symmetric positive definite spd matrix Cptr a pointer to the Cholesky factors Cp AppCC Description This function computes a Cholesky factorization of the sparse symmetric positive definite spd matrix A and retrieves at the scilab level a pointer Cptr to an handle of the Cholesky factors Cp the memory used for them is outside scilab space If your matrix is spd this function must be used in place of umflufact or in place of the scilab function chfact for a gain in speed also as chfact uses the scilab memory for the factors the user must set the stacksize with a large value because of the fillin occuring in computing the factor C which then may take more memory than the initial matrix A When such a factorisation have been computed a linear system must be solved with taucschsolve To free the memory used by the Cholesky factors use taucschdelCptr to retrieve the Cholesky factors at the scilab level for example to display their sparse patterns use taucschget to get some information number of non zeros in C use taucschinfo To compute an approximation of the con dition number in norm 2 use cond2sp Remarks taucschfact works only with the upper triangle of A and the matrix A must be provided either in its complete form that is with the lower triangle also or only with its upper triangle currently taucschfact uses the genmmd generalized minimum degree algorithm of Liu to find in a first step the permutation p so as to minimize the fillin in the factorization future versions will let the user choose hisher own reordering by providing a supplementary argument p Examples Example 1 a small linear test system whom solution must be 12345 A sparse 2 1 0 0 0 1 2 1 0 0 0 1 2 1 0 0 0 1 2 1 0 0 0 1 2 b 0 0 0 0 6 Cp taucschfactA x taucschsolveCpb dont forget to clear memory with taucschdelCp Example 2 a real example taucschfact 2254 first load a sparse matrix A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa compute the factorisation Cp taucschfactA b randsizeA11 a random rhs use taucschsolve for solving Axb x taucschsolveCpb normAx b the same with one iterative refinement step x taucschsolveCpbA normAx b dont forget to clear memory taucschdelCp See Also taucschsolve taucschdel taucschinfo taucschget cond2sp Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2255 Name taucschget retrieve the Cholesky factorization at the scilab level Ctp taucschgetCptr Parameters Cptr a pointer to the Cholesky factorization Cp AppCC Ct a scilab sparse matrix you get the upper triangle ie Ct is equal to C p column vector storing the permutation Description This function may be used if you want to plot the sparse pattern of the Cholesky factorization or if you code something which use the factors Traditionnaly the factorization is written P A P C C with P the permutation matrix associated to the permutation p As we get the upper triangle Ct C in scilab syntax we can write App Ct Ct Examples Example 1 a small linear test system A sparse 2 1 0 0 0 1 2 1 0 0 0 1 2 1 0 0 0 1 2 1 0 0 0 1 2 Cp taucschfactA Ct p taucschgetCp fullApp CtCt this must be near the null matrix taucschdelCp Example 2 a real example stacksize3000000 the last PlotSparse need memory first load a sparse matrix A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa compute the factorisation Cptr taucschfactA retrieve the factor at scilab level Ct p taucschgetCptr plot the initial matrix xsetwindow0 clf taucschget 2256 PlotSparseA xtitleInitial matrix A bcsstk24rsa plot the permuted matrix B App xsetwindow1 clf PlotSparseB xtitlePermuted matrix B App plot the upper triangle Ct xsetwindow2 clf PlotSparseCt xtitleThe pattern of Ct App CCt retrieve cnz OK n cnz taucschinfoCptr cnz is superior to the realnumber of non zeros elements of C cnzexact nnzCt dont forget to clear memory taucschdelCptr See Also taucschfact taucschsolve taucschdel taucschinfo taucschget cond2sp Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2257 Name taucschinfo get information on Cholesky factors OK n cnz taucschinfoCptr Parameters Cptr a pointer to a Cholesky factorization OK a scalar boolean n a scalar integer cnz a scalar integer Description This function may be used to know basic information about the Cholesky factor created with taucschfact first OK is t if Cptr is a valid pointer to an Cholesky factorization and f else if OK is t then n and cnz are respectively the matrix order and the number of non zeros elements in the supernodal structure storing C if OK is f n and cnz are set to the void matrix Details Due to the supernodal structure used for C cnz is larger than the exact number of nonzeros elements in C and so this cnz is a mesure of the memory used internally To get the exact cnz you may retrieve the Cholesky factor with taucschget then apply the nnz scilab function see the 2d example in taucschget See Also taucschfact taucschsolve taucschdel taucschget Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2258 Name taucschsolve solve a linear sparse spd system given the Cholesky factors x taucschsolveCptr b A Parameters Cptr a pointer to a handle of the Cholesky factors Cp with AppCC b a real column vector or a matrix multiple rhs x a real column vector or a matrix in case of multiple rhs xi is solution of A xi bi A optional the real spd matrix A to use for iterative refinement step Description This function must be used in conjonction with taucschfact which computes the Cholesky factoriza tion of a sparse real spd matrix When the matrix A is provided one iterative refinement step is done the refined solution is accepted if it improves the 2norm of the residual Axb Like in taucschfact the matrix A may be provided either in its complete form that is with the lower triangle also or only with its upper triangle Examples see the example section of taucschfact See Also taucschfact taucschdel taucschinfo taucschget cond2sp Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2259 Name taucslicense display the taucs license Copyright TAUCS Version 10 November 29 2001 Copyright c 2001 by Sivan Toledo TelAviv Univesity stoledotauacil All Rights Reserved TAUCS License Your use or distribution of TAUCS or any derivative code implies that you agree to this License THIS MATERIAL IS PROVIDED AS IS WITH ABSOLUTELY NO WARRANTY EXPRESSED OR IMPLIED ANY USE IS AT YOUR OWN RISK Permission is hereby granted to use or copy this program provided that the Copyright this License and the Availability of the original version is retained on all copies User documentation of any code that uses this code or any derivative code must cite the Copyright this License the Availability note and Used by permission If this code or any derivative code is accessible from within MATLAB then typing help taucs must cite the Copyright and type taucs must also cite this License and the Availability note Permission to modify the code and to distribute modified code is granted provided the Copyright this License and the Availability note are retained and a notice that the code was modified is included This software is provided to you free of charge Availability httpwwwtauacilstoledotaucs 2260 Name umflicense display the umfpack license Copyright UMFPACK Copyright c 19952006 by Timothy A Davis All Rights Reserved UMFPACK is available under alternate licences contact T Davis for details UMFPACK License Your use or distribution of UMFPACK or any modified version of UMFPACK implies that you agree to this License This library is free software you can redistribute it andor modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation either version 21 of the License or at your option any later version This library is distributed in the hope that it will be useful but WITHOUT ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE See the GNU Lesser General Public License for more details You should have received a copy of the GNU Lesser General Public License along with this library if not write to the Free Software Foundation Inc 51 Franklin St Fifth Floor Boston MA 021101301 USA Permission is hereby granted to use or copy this program under the terms of the GNU LGPL provided that the Copyright this License and the Availability of the original version is retained on all copies User documentation of any code that uses this code or any modified version of this code must cite the Copyright this License the Availability note and Used by permission Permission to modify the code and to distribute modified code is granted provided the Copyright this License and the Availability note are retained and a notice that the code was modified is included Availability httpwwwciseufleduresearchsparse 2261 Name umfludel utility function used with umflufact umfludelLUptr or umfludel Parameters LUptr a pointer to an handle of umf lu factors LUpqR Description This function must be used in conjunction with umflufact and umflusolve It clears the internal memory space used to store the LU factors got with umflufact Use without argument it frees the memory for all the current scilab umfpack LU factors Examples see the example section of umflufact See Also umfpack umflufact umflusolve umfluget umfluinfo Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon 2262 Name umflufact lu factorisation of a sparse matrix LUptr umflufactA Parameters A a sparse real or complex square or rectangular matrix LUptr a pointer to umf lu factors LUpqR Description This function computes a LU factorisation of the sparse matrix A and return at the scilab level a pointer LUptr to an handle of the LU factors LUpqR the memory used for them is outside scilab stack This function must be used in place of umfpack if you have multiple linear systems with the same matrix to solve when the rhs are not known at the same time for instance A x1 b1 and A x2 b2 but b2 depends on x1 etc When such a factorisation have been computed a linear system must be solved with umflusolve in general x umflusolveLUptr b but others options are possible see umflusolve To free the memory used by the LU factors use umfludelLUptr umfludel to retrieve the LU factors at the scilab level for example to display their sparse patterns use umfluget to get some information number of non zeros in L and U use umfluinfo To compute an approximation of the condition number use condestsp Examples this is the small linear test system from UMFPACK whom solution must be 12345 A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 b 8 45 3 3 19 Lup umflufactA x umflusolveLupb solve now Axb x umflusolveLupbAxb normAx b dont forget to clear memory with umfludelLup a real but small example first load a sparse matrix A ReadHBSparseSCImodulesumfpackexamplesarc130rua compute the factorisation Lup umflufactA umflufact 2263 b randsizeA11 a random rhs use umflusolve for solving Axb x umflusolveLupb normAx b now the same thing with iterative refiment x umflusolveLupbAxbA normAx b solve now the system Axb x umflusolveLupbAxb without refinement normAx b x umflusolveLupbAxbA with refinement normAx b dont forget to clear memory umfludelLup See Also umfpack umfluget umflusolve umfludel umfluinfo condestsp Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon with contributions from Antonio Frasson 2264 Name umfluget retrieve lu factors at the scilab level LUpqRd umflugetLUptr Parameters LUptr a pointer to umf lu factors LUpqR LU scilab sparse matrix pq column vectors storing the permutations Rd vector storing the row scaling factors Description This function may be used if you want to plot the sparse pattern of the lu factors or if you code something which use the lu factors The factorization provided by umfpack is of the form P R1 A Q LU where P and Q are permutation matrices R is a diagonal matrix row scaling L a lower triangular matrix with a diagonal of 1 and U an upper triangular matrix The function provides the matrices L and U as Sparse scilab matrices but P and Q are given as permutation vectors p and q in fact p is the permutation associated to P and Rd is the vector corresponding to the diagonal of R Examples this is the test matrix from UMFPACK A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 Lup umflufactA LUpqR umflugetLup B A for i15 Bi BiRi end apply the row scaling Bpq LU must be a quasi nul matrix umfludelLup clear memory the same with a complex matrix A sparse 2i 32i 0 0 0 3i 0 4i 0 63i 0 1i 36i 2i 0 0 0 15i 0 0 0 4 2i 0 1 Lup umflufactA LUpqR umflugetLup umfluget 2265 B A for i15 Bi BiRi end apply the row scaling Bpq LU must be a quasi nul matrix umfludelLup clear memory See Also umfpack umflufact umflusolve umfludel umfluinfo Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon 2266 Name umfluinfo get information on LU factors OK nrow ncol lnz unz udiagnz it umfluinfoLUptr Parameters LUptr a pointer to umf lu factors LUpq R OK a scalar boolean nrow ncol lnz unz udiagnz it scalars integers Description This function may be used to know basic information about LU factors created with umflufact first OK is t if LUptr is a valid pointer to an umfpack LU numeric handle and f else if OK is t then nrow ncol are the matrix size L is nrow x n and U is n x ncol where n minnrowncol lnz unz are the number of non zeros elements in L and in U udiagnz are the number of non zeros elements on the diagonal of U if the matrix is square nrow ncol n then it is not inversible if udiagnz n more precisely it appears to be numericaly not inversible through the LU factorization it 0 if the factors are real and 1 if they are complex if OK is f then all the others outputs are set to the empty matrix Examples this is the test matrix from UMFPACK A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 Lup umflufactA OK nrow ncol lnz unz udiagnz it umfluinfoLup OK must be t nrowncol 5 LUpqR umflugetLup nnzL must be equal to lnz nnzU must be equal to unz umfludelLup clear memory umfluinfo 2267 See Also umfpack umflufact umflusolve umfludel umfluget Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon 2268 Name umflusolve solve a linear sparse system given the LU factors x umflusolveLUptr b st A Parameters LUptr a pointer to umf lu factors LUpqR b a real or complex column vector or a matrix multiple rhs st optional a string Axb default or Axb to be written Axb in scilab langage a quote in a string must be doubled A optional the sparse square matrix corresponding to the LU factors LUptr must be got with LUptr umflufactA x a column vector or a matrix in case of multiple rhs xi is solution of A xi bi or Axi bi Description This function must be used in conjonction with umflufact which computes the LU factors of a sparse matrix The optional st argument lets us choose between the solving of Axb general case or of Axb sometimes useful If you give the 4th argument then iterative refinement will be also proceceed as in umfpack to give a better numerical solution Examples see the example section of umflufact See Also umfpack umflufact umfluget umfludel umfluinfo Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon with contributions from Antonio Frasson 2269 Name umfpack solve sparse linear system x umfpackAb x umfpackbA Parameters A a sparse real or complex square matrix n x n b in the first case a column vector n x 1 or a n x m matrix in the second case a row vector 1 x n or a m x n matrix x in the first case a column vector n x 1 or a n x m matrix in the second case a row vector 1 x n or a m x n matrix 2d arg string specifier or Description This function is intended to work like the classic operators and x Ab and x bA ie it solves a linear system Ax b or xA b with a sparse square says n x n real or complex matrix and with a compatible rhs b n x m in the first case and m x n in the second Details First an LU factorisation of the matrix is computed P R1 A Q LU where P and Q are permutation matrices R is a diagonal matrix row scaling L a lower triangular matrix with a diago nal of 1 and U an upper triangular matrix then a first solution is computed with forwardbackward subtitutions finaly the solution is improved by iterative refinement Examples this is the small linear test system from UMFPACK whom solution must be 12345 A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 b 8 45 3 3 19 x umfpackAb test the other form x A b b 8 20 13 6 17 x umfpackbA solution must be 1 2 3 4 5 test multiple rhs b rand53 x umfpackAb normAx b umfpack 2270 test multiple rhs for x A b b rand35 x umfpackbA normxA b solve a complex system A sparse 2i 32i 0 0 0 3i 0 4i 0 63i 0 1i 36i 2i 0 0 0 15i 0 0 0 4 2i 0 1 b 313i 5832i 1913i 1812i 2216i x umfpackAb x must be 1i 22i 33i 4 4i 55i A benchmark of several linear solvers Adescrrefmtype ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa b 0onessizeA11 tic res umfpackAb printf time needed to solve the system with umfpack 3f toc tic res linsolveAb printf time needed to solve the system with linsolve 3f toc tic res Ab printf time needed to solve the system with the backslash operator 3f toc See Also umflufact umflusolve umfludel umfluinfo umfluget linsolve backslash Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon with contributions from Antonio Frasson Parte L Algoritmos Genéticos 2272 Name codinggabinary A function which performs conversion between binary and continuous repre sentation popout codinggabinarypopindirectionparam Parameters popin a list which contains all the individuals in the current population direction code or decode If direction code then we perform a continuous to binary encoding Else we convert from binary to continuous param a parameter list binarylength the number of bits by variables If binarylength 8 and the variable X is of dimension 2 then the binary code will be 16 bits length minboun a vector of minimum bounds for the variable X maxbound a vector of maximum bounds for the variable X popout the population coded to binary or decoded to continuous values Description This function allows to code or decode a population of individuals from resp to continuous vari ables to resp from binary See Also optimga mutationgabinary crossovergabinary Authors Yann COLLETTE ycolletfreesurffr 2273 Name codinggaidentity A nooperation conversion function popout codinggaidentitypopindirectionparam Parameters popin the population to be converted direction code or decode This value has no influence of the state of popin param a parameter list For this function there are no useful parameters set popout a population identical to popin Description This function is a donothing function It is essentially useful to implement an evolutionnary algo rithm In an evolutionnary algorithm we work directly on the variable and not on a binary code See Also mutationfuncdefault crossoverfuncdefault initfuncdefault optimga Authors Yann COLLETTE ycolletfreesurffr 2274 Name crossovergabinary A crossover function for binary code CrossedIndiv1CrossedIndiv2 crossovergabinaryIndiv1Indiv2param Parameters Indiv1 the first individual here a binary code to be crossedover Indiv2 the second individual to be crossedover param a list of parameters binarylength the length of the binary code multicross a boolean If T then we allow several cuts in the binary code multicrossnb the number of cuts in the binary code Only used when multicross is set to T CrossedIndiv1 The first individual obtained by the crossover function CrossedIndiv2 The second individual obtained by the crossover function Description This function implements a classical binary crossover See Also crossovergabinary crossovergadefault mutationgabinary optimga Authors Yann COLLETTE ycolletfreesurffr 2275 Name crossovergadefault A crossover function for continuous variable functions CrossedIndiv1CrossedIndiv2 crossovergadefaultIndiv1Indiv2param Parameters Indiv1 The first individual to be crossedover Indiv2 The second individual to be crossedover param a list of parameters beta the range of the random generator A random value will be sampled between beta and 1beta This sampled value will be used to perform a convex combination between Indiv1 and Indiv2 minbound a vector of minimum bounds for the variable X maxbound a vector of maximum bounds for the variable X CrossedIndiv1 The first individual resulting from the crossover CrossedIndiv2 The second individual resulting from the crossover Description crossovergadefault is a crossover function for functions with continuous variables This crossover function is an extension of a convexe combination The crossed individuals are computed with the following equations mix 1 2Betarand11 Beta CrossedIndiv1 mixIndiv1 1mixIndiv2 CrossedIndiv2 1mixIndiv1 mixIndiv2 The Beta parameter should be set to a positive value If Beta is set to 0 the resulting crossover is a simple convexe combination between the two parents That may lead to a too fast convergence of the genetic algorithm and may decrease the diversity of the individuals of the population If Beta is chosen strictly positive that may allow children to explore the domain beyond the domain explored by their parents See Also crossovergabinary mutationgadefault initgadefault optimga References Michalewicz Zbigniew Genetic Algorithms Data Structures Evolution Programs crossovergadefault 2276 Authors Yann COLLETTE ycolletfreesurffr 2277 Name initgadefault A function a initialize a population Popinit initgadefaultpopsizeparam Parameters popsize the number of individuals to generate param a list of parameters dimension the size of the vector X minbound a vector of minimum bounds for the variable X maxbound a vector of maximum bounds for the variable X Popinit a list which contains the initial population of individuals Description This function generate an initial population containing popsize individuals See Also crossovergadefault mutationgadefault mutationgabinary optimga Authors Yann COLLETTE ycolletfreesurffr 2278 Name mutationgabinary A function which performs binary mutation MutIndiv mutationgabinaryIndivparam Parameters Indiv the individual on which we will perform the mutation param a list of parameters binarylength the size of the binary code multimut a boolean If T several random bits will be flipped multimutnd the number of bits to be flipped Works only when multimut is set to T MutIndiv The mutated individual Description This function performs a classical multibits binary mutation See Also mutationgadefault crossovergabinary initfuncdefault optimga Authors Yann COLLETTE ycolletfreesurffr 2279 Name mutationgadefault A continuous variable mutation function MutIndiv mutationgadefaultIndivparam Parameters Indiv The individual to be mutated param a list of parameters delta a random perturbation will be sampled via an uniform distribution between delta and delta minbound a vector of minimum bound for the variable X maxbound a vector of maximum bound for the variable X MutIndiv The resulting mutated individual Description This function performs the classical continuous variable mutation function See Also mutationgabinary crossovergadefault initgadefault optimga Authors Yann COLLETTE ycolletfreesurffr 2280 Name optimga A flexible genetic algorithm popoptfobjpopoptpopinitfobjpopinit optimgagafpopsizenbgenerationpmutpcrossLogparam Parameters gaf the function to be optimized The prototype if y fx or y listfp1p2 popsize the size of the population of individuals default value 100 nbgeneration the number of generations equivalent to the number of iterations in classical optimization to be computed default value 10 pmut the mutation probability default value 01 pcross the crossover probability default value 07 Log if T we will display to information message during the run of the genetic algorithm param a list of parameters codagefunc the function which will perform the coding and decoding of individuals default function codageidentity initfunc the function which will perform the initialization of the population default function initgadefault crossoverfunc the function which will perform the crossover between two individuals de fault function crossovergadefault mutationfunc the function which will perform the mutation of one individual default func tion mutationgadefault selectionfunc the function whcih will perform the selection of individuals at the end of a generation default function selectiongaelitist nbcouples the number of couples which will be selected so as to perform the crossover and mutation default value 100 pressure the value the efficiency of the worst individual default value 005 popopt the population of optimal individuals fobjpopopt the set of objective function values associated to popopt optional popinit the initial population of individuals optional fobjpopinit the set of objective function values associated to popinit optional optimga 2281 Description This function implements the classical genetic algorithm Examples deffyfxy sumx2 PopSize 100 Probacross 07 Probamut 01 NbGen 10 NbCouples 110 Log T nbdisp 10 Nb point to display from the optimal population pressure 005 gaparams initparam Parameters to adapt to the shape of the optimization problem gaparams addparamgaparamsminbound2 2 gaparams addparamgaparamsmaxbound2 2 gaparams addparamgaparamsdimension2 gaparams addparamgaparamsbeta0 gaparams addparamgaparamsdelta01 Parameters to fine tune the Genetic algorithm All these parameters are optional for continuous optimization If you need to adapt the GA to a special problem you gaparams addparamgaparamsinitfuncinitgadefault gaparams addparamgaparamscrossoverfunccrossovergadefault gaparams addparamgaparamsmutationfuncmutationgadefault gaparams addparamgaparamscodagefunccodagegaidentity gaparams addparamgaparamsselectionfuncselectiongaelitist gaparams addparamgaparamsselectionfuncselectiongarandom gaparams addparamgaparamsnbcouplesNbCouples gaparams addparamgaparamspressurepressure Min getparamgaparamsminbound Max getparamgaparamsmaxbound x0 Max Min randsizeMin1sizeMin2 Min popopt fobjpopopt popinit fobjpopinit optimgaf PopSize NbGen Probamut Probacross Log gaparams See Also optimmoga optimnsga optimnsga2 References Michalewicz Zbigniew Genetic Algorithms Data Structures Evolution Programs Authors Yann COLLETTE ycolletfreesurffr 2282 Name optimmoga multiobjective genetic algorithm popoptfobjpopoptpopinitfobjpopinit optimmogagafpopsizenbgenerationpmutpcrossLogparam Parameters gaf the function to be optimized The header of the function is the following y fx or y listfp1p2 popsize the size of the population of individuals default value 100 nbgeneration the number of generations equivalent to the number of iterations in classical optimization to be computed default value 10 pmut the mutation probability default value 01 pcross the crossover probability default value 07 Log if T we will display to information message during the run of the genetic algorithm param a list of parameters codagefunc the function which will perform the coding and decoding of individuals default function codageidentity initfunc the function which will perform the initialization of the population default function initgadefault crossoverfunc the function which will perform the crossover between two individuals de fault function crossovergadefault mutationfunc the function which will perform the mutation of one individual default func tion mutationgadefault selectionfunc the function whcih will perform the selection of individuals at the end of a generation default function selectiongaelitist nbcouples the number of couples which will be selected so as to perform the crossover and mutation default value 100 pressure the value the efficiency of the worst individual default value 005 optimmoga 2283 popopt the population of optimal individuals fobjpopopt the set of multiobjective function values associated to popopt optional popinit the initial population of individuals optional fobjpopinit the set of multiobjective function values associated to popinit optional Description This function implements the classical MultiObjective Genetic Algorithm For a demonstration see SCImodulesgeneticalgorithmsexamplesMOGAdemosce See Also optimga optimnsga optimnsga2 Authors Yann COLLETTE ycolletfreesurffr 2284 Name optimnsga A multiobjective Niched Sharing Genetic Algorithm popoptfobjpopoptpopinitfobjpopinit optimnsgagafpopsizenbgenerationpmutpcrossLogparamsigmapow Parameters gaf the function to be optimized The prototype if y fx or y listfp1p2 popsize the size of the population of individuals default value 100 nbgeneration the number of generations equivalent to the number of iterations in classical optimization to be computed default value 10 pmut the mutation probability default value 01 pcross the crossover probability default value 07 Log if T we will display to information message during the run of the genetic algorithm param a list of parameters codagefunc the function which will perform the coding and decoding of individuals default function codageidentity initfunc the function which will perform the initialization of the population default function initgadefault crossoverfunc the function which will perform the crossover between two individuals de fault function crossovergadefault mutationfunc the function which will perform the mutation of one individual default func tion mutationgadefault selectionfunc the function whcih will perform the selection of individuals at the end of a generation default function selectiongaelitist nbcouples the number of couples which will be selected so as to perform the crossover and mutation default value 100 pressure the value the efficiency of the worst individual default value 005 sigma the radius of the sharing area pow the power coefficient of the penalty formula popopt the population of optimal individuals fobjpopopt the set of objective function values associated to popopt optional optimnsga 2285 popinit the initial population of individuals optional fobjpopinit the set of objective function values associated to popinit optional Description This function implements the classical Niched Sharing Genetic Algorithm For a demonstration see SCImodulesgeneticalgorithmsexamplesNSGAdemosce See Also optimmoga optimga optimnsga2 Authors Yann COLLETTE ycolletfreesurffr 2286 Name optimnsga2 A multiobjective Niched Sharing Genetic Algorithm version 2 popoptfobjpopoptpopinitfobjpopinit optimnsga2gafpopsizenbgenerationpmutpcrossLogparam Parameters gaf the function to be optimized The prototype if y fx or y listfp1p2 popsize the size of the population of individuals default value 100 nbgeneration the number of generations equivalent to the number of iterations in classical optimization to be computed default value 10 pmut the mutation probability default value 01 pcross the crossover probability default value 07 Log if T we will display to information message during the run of the genetic algorithm param a list of parameters codagefunc the function which will perform the coding and decoding of individuals default function codageidentity initfunc the function which will perform the initialization of the population default function initgadefault crossoverfunc the function which will perform the crossover between two individuals de fault function crossovergadefault mutationfunc the function which will perform the mutation of one individual default func tion mutationgadefault selectionfunc the function whcih will perform the selection of individuals at the end of a generation default function selectiongaelitist nbcouples the number of couples which will be selected so as to perform the crossover and mutation default value 100 pressure the value the efficiency of the worst individual default value 005 popopt the population of optimal individuals fobjpopopt the set of objective function values associated to popopt optional popinit the initial population of individuals optional fobjpopinit the set of objective function values associated to popinit optional optimnsga2 2287 Description This function implements the classical Niched Sharing Genetic Algorithm For a demonstration see SCImodulesgeneticalgorithmsexamplesNSGA2demosce See Also optimmoga optimga optimnsga Authors Yann COLLETTE ycolletfreesurffr 2288 Name paretofilter A function which extracts non dominated solution from a set FoutXoutIndout paretofilterFinXin Parameters Fin the set of multiobjective function values from which we want to extract the non dominated so lutions Xin the associated values in the parameters space Fout the set of non dominated multiobjective function values Xout the associated values in the parameters space Indout the set of indexes of the non dominated individuals selected from the set Xin Description This function applies a Pareto filter to extract non dominated solutions from a set of values See Also optimmoga optimnsga optimnsga2 Authors Yann COLLETTE ycolletfreesurfFr 2289 Name selectiongaelitist An elitist selection function PopoutFObjPopoutEfficiencyMOTotalFObjout selectiongaelitistPopinIndiv1Indiv2FObjPopinFObjIndiv1FObjIndiv2MOTotalFObjinMOFObjIndiv1MOFObjIndiv2param Parameters Popin The initial population of individuals Indiv1 a first set of childs generated via crossover mutation Indiv2 a second set of childs generated via crossover mutation FObjPopin a vector of objective function values associated to each individuals of Popin FObjIndiv1 a vector of objective function values associated to each individuals of Indiv1 FObjIndiv2 a vector of objective function values associated to each individuals of Indiv2 MOTotalFObjin a matrix of multiobjective function values associated to each individuals of Popin MOFObjIndiv1 a matrix of multiobjective function values associated to each individuals of Indiv1 MOFObjIndiv2 a matrix of multiobjective function values associated to each individuals of Indiv2 param a list of parameters pressure the selection pressure coefficient Each individuals with 0 effi ciency will have an efficiency value equal to pressure Popout all the selected individuals in a population of size popsize FObjPopout all the objective function values associated to each individuals of Popout Efficiency all the efficiency values associated to each individuals of Popout MOTotalFObjout all the multiobjective function values associated to each individuals of Popout Description This function performs the elitist selection function We select the best individuals in the set of parents and childs individuals See Also selectiongarandom mutationgadefault crossovergadefault initgadefault optimga selectiongaelitist 2290 Authors Yann COLLETTE ycolletfreesurffr 2291 Name selectiongarandom A function which performs a random selection of individuals PopoutFObjPopoutEfficiencyMOTotalFObjout selectiongarandomPopinIndiv1Indiv2FObjPopinFObjIndiv1FObjIndiv2MOTotalFObjinMOFObjIndiv1MOFObjIndiv2param Parameters Popin The initial population of individuals Indiv1 a first set of childs generated via crossover mutation Indiv2 a second set of childs generated via crossover mutation FObjPopin a vector of objective function values associated to each individuals of Popin FObjIndiv1 a vector of objective function values associated to each individuals of Indiv1 FObjIndiv2 a vector of objective function values associated to each individuals of Indiv2 MOTotalFObjin a matrix of multiobjective function values associated to each individuals of Popin MOFObjIndiv1 a matrix of multiobjective function values associated to each individuals of Indiv1 MOFObjIndiv2 a matrix of multiobjective function values associated to each individuals of Indiv2 param a list of parameters pressure the selection pressure coefficient Each individuals with 0 efficiency will have an efficiency value equal to pressure Popout all the selected individuals in a population of size popsize FObjPopout all the objective function values associated to each individuals of Popout Efficiency all the efficiency values associated to each individuals of Popout MOTotalFObjout all the multiobjective function values associated to each individuals of Popout Description This function performs the random selection function We select popsize individuals in the set of parents and childs individuals at random See Also selectiongaelitist mutationgadefault crossovergadefault initgadefault optimga selectiongarandom 2292 Authors Yann COLLETTE ycolletfreesurffr Parte LI Arrefecimento Simulado 2294 Name computeinitialtemp A SA function which allows to compute the initial temperature of the sim ulated annealing Tinit computeinitialtempx0fprobainitItMXneighfuncparamneighfunc Parameters x0 the starting point f the objective function which will be send to the simulated annealing for optimization probainit the initial probability of accepting a bad solution usually around 07 ItMX the number of iterations of random walk usually around 100 neighfunc a function which returns a neighbor of a given point see the help page of neighfunc to see the prototype of this function paramneighfunc some parameters can be a list which will be sent as parameters to neighfunc Tinit The initial temperature corresponding to the given probability of accepting a bad solution Description This function computes an initial temperature given an initial probability of accepting a bad solution This computation is based on some iterations of random walk Examples deffyfxysumx2 x0 2 2 Probastart 07 ItPre 100 xtest neighfuncdefaultx0 comptparams initparam comptparams addparamcomptparamsneighfunc neighfuncdefault T0 computeinitialtempx0 rastrigin Probastart ItPre comptsa See Also optimsa neighfuncdefault templawdefault Authors collette Yann COLLETTE ycolletfreesurffr 2295 Name neighfunccsa The classical neighborhood relationship for the simulated annealing xneigh neighfunccsaxcurrentTparam Parameters xcurrent the point for which we want to compute a neighbor T the current temperature param a vector with the same size than xcurrent A normalisation vector which allows to distort the shape of the neighborhood This parameter allows to take into account the differences of interval of variation between variables By default this parameter is set to a vector of ones xneigh the computed neighbor Description This function implements the classical neighborhood relationship for the simulated annealing The neighbors distribution is a gaussian distribution which is more and more peaked as the temperature decrease See Also neighfuncdefault templawhuang optimsa Authors collette Yann COLLETTE ycolletfreesurffr 2296 Name neighfuncdefault A SA function which computes a neighbor of a given point xneigh neighfuncdefaultxcurrentTparam Parameters xcurrent the point for which we want to compute a neighbor T the current temperature param a two columns vector The first column correspond to the negative amplitude of variation and the second column corresponds to the positive amplitude of variation of the neighborhood By default the first column is a column of 01 and the second column is a column of 01 xneigh the computed neighbor Description This function computes a neighbor of a given point For example for a continuous vector a neighbor will be produced by adding some noise to each component of the vector For a binary string a neighbor will be produced by changing one bit from 0 to 1 or from 1 to 0 Examples We produce a neighbor by adding some noise to each component of a given vector function xneigh neighfuncdefaultxcurrent T samindelta 01onessizexcurrent1sizexcurrent2 samaxdelta 01onessizexcurrent1sizexcurrent2 xneigh xcurrent samaxdelta samindeltarandsizexcurrent1sizexcurrent2 samindelta endfunction See Also optimsa computeinitialtemp templawdefault Authors collette Yann COLLETTE ycolletfreesurffr 2297 Name neighfuncfsa The Fast Simulated Annealing neghborhood relationship xneigh neighfuncfsaxcurrentTparam Parameters xcurrent the point for which we want to compute a neighbor T the current temperature param a vector with the same size than xcurrent A normalisation vector which allows to distort the shape of the neighborhood This parameter allows to take into account the differences of interval of variation between variables By default this parameter is set to a vector of ones xneigh the computed neighbor Description This function computes the FSA neighborhood of a given point The corresponding distribution is a Cauchy distribution which is more and more peaked as the temperature decrease See Also optimsa templawfsa neighfuncdefault Authors collette Yann COLLETTE ycolletfreesurffr 2298 Name neighfuncvfsa The Very Fast Simulated Annealing neighborhood relationship xneigh neighfuncvfsaxcurrentTparam Parameters xcurrent the point for which we want to compute a neighbor T the current temperature param a ones column vector The column correspond to the amplitude of variation of the neighborhood By default the column is a column of 01 xneigh the computed neighbor Description This function implements the Very Fast Simulated Annealing relationship This distribution is more and more peaked as the temperature decrease See Also optimsa neighfuncvfsa templawhuang Authors collette Yann COLLETTE ycolletfreesurffr 2299 Name optimsa A Simulated Annealing optimization method xbestfbestmeanlistvarlistfhistorytemplistxhistory optimsax0fItExtItIntT0Logtemplawparamtemplawneighfuncparamneighfunc Parameters x0 the initial solution f the objective function to be optimized the prototype if fx ItExt the number of temperature decrease ItInt the number of iterations during one temperature stage T0 the initial temperature see computeinitialtemp to compute easily this temperature Log if T some information will be displayed during the run of the simulated annealing templaw the temperature decrease law see templawdefault for an example of such a function paramtemplaw a structure of any kind it depends on the temperature law used which is transmitted as a pa rameter to templaw neighfunc a function which computes a neighbor of a given point see neighfuncdefault for an example of such a function paramneighfunc a structure of any kind like vector list it depends on the neighborhood function used which is transmitted as a parameter to neighfunc xbest the best solution found so far fbest the objective function value corresponding to xbest meanlist the mean of the objective function value for each temperature stage A vector of float optional varlist the variance of the objective function values for each temperature stage A vector of float op tional fhistory the computed objective function values for each iteration Each input of the list corresponds to a temperature stage Each input of the list is a vector of float which gathers all the objective function values computed during the corresponding temperature stage optional templist the list of temperature computed for each temperature stage A vector of float optional optimsa 2300 xhistory the parameter values computed for each iteration Each input of the list corresponds to a temper ature stage Each input of the list is a vector of input variables which corresponds to all the vari ables computed during the corresponding temperature stage optional can slow down a lot the execution of optimsa Description A Simulated Annealing optimization method Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 2 2 Probastart 07 ItPre 100 Itextern 100 Itintern 1000 xtest neighfuncdefaultx0 comptparams initparam comptparams addparamcomptparamsneighfunc neighfuncdefault T0 computeinitialtempx0 rastrigin Probastart ItPre comptsa xopt fopt sameanlist savarlist optimsax0 rastrigin Itextern Itintern T0 Log T printfoptimal solution dispxopt printfvalue of the objective function f fopt t 1lengthsameanlist plottsameanlistrtsavarlistg See Also computeinitialtemp neighfuncdefault templawdefault Authors collette Yann COLLETTE ycolletfreesurffr 2301 Name templawcsa The classical temperature decrease law Tout templawcsaTinstepmeanstepvartempstagenparam Parameters Tin the temperature at the current stage stepmean the mean value of the objective function computed during the current stage stepvar the variance value of the objective function computed during the current stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param not used for this temperature law Tout the temperature for the temperature stage to come Description This function implements the classical annealing temperature schedule the one for which the con vergence of the simulated annealing has been proven Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 1 1 Probastart 08 Itintern 1000 Itextern 30 ItPre 100 printfSA the CSA algorithm T0 computeinitialtempx0 rastrigin Probastart ItPre neighfuncdefault printfInitial temperatore T0 f T0 xopt fopt sameanlist savarlist templist optimsax0 rastrigin Itextern Itintern T0 Log T templawcsa neighfunccsa printfoptimal solution dispxopt printfvalue of the objective function f fopt scf templawcsa 2302 subplot211 xtitleClassical simulated annealingIterationMean Variance t 1lengthsameanlist plottsameanlistrtsavarlistg legendMeanVariance subplot212 xtitleTemperature evolutionIterationTemperature plotttemplistk See Also optimsa templawhuang neighfuncdefault Authors collette Yann COLLETTE ycolletfreesurffr 2303 Name templawdefault A SA function which computed the temperature of the next temperature stage Tnext templawdefaultTstepmeanstepvartempstagenparam Parameters T the temperature applied during the last temperature stage stepmean the mean of the objective function values computed during the last temperature stage stepvar the variance of the obejective function values computed during the last temperature stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param a float between 0 and 1 Corresponds to the decrease in temperature of the geometric law 09 by default Tnext the new temperature to be applied for the next temperature stage Description A SA function which computed the temperature of the next temperature stage Examples This function implements the simple geometric temperature law function T templawdefaultT stepmean stepvar alpha 09 T alphaT endfunction See Also optimsa computeinitialtemp neighfuncdefault Authors collette Yann COLLETTE ycolletfreesurffr 2304 Name templawfsa The Szu and Hartley Fast simulated annealing Tout templawfsaTinstepmeanstepvartempstagenparam Parameters Tin the temperature at the current stage stepmean the mean value of the objective function computed during the current stage stepvar the variance value of the objective function computed during the current stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param not used for this temperature law Tout the temperature for the temperature stage to come Description This function implements the Fast simulated annealing of Szu and Hartley Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 1 1 Probastart 08 Itintern 1000 Itextern 30 ItPre 100 printfSA the FSA algorithm T0 computeinitialtempx0 rastrigin Probastart ItPre neighfuncdefault printfInitial temperatore T0 f T0 xopt fopt sameanlist savarlist templist optimsax0 rastrigin Itextern Itintern T0 Log T templawfsa neighfuncfsa printfoptimal solution dispxopt printfvalue of the objective function f fopt scf subplot211 templawfsa 2305 xtitleFast simulated annealingIterationMean Variance t 1lengthsameanlist plottsameanlistrtsavarlistg legendMeanVariance subplot212 xtitleTemperature evolutionIterationTemperature plotttemplistk See Also optimsa templawhuang neighfuncdefault Authors collette Yann COLLETTE ycolletfreesurffr 2306 Name templawhuang The Huang temperature decrease law for the simulated annealing Tout templawhuangTinstepmeanstepvartempstagenparam Parameters Tin the temperature at the current stage stepmean the mean value of the objective function computed during the current stage stepvar the variance value of the objective function computed during the current stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param a float corresponding to the lambda parameter of the Huang temperature decrease law 001 by default Tout the temperature for the temperature stage to come Description This function implements the Huang temperature decrease law for the simulated annealing Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 1 1 Probastart 08 Itintern 1000 Itextern 30 ItPre 100 printfSA the Huang temperature decrease law T0 computeinitialtempx0 rastrigin Probastart ItPre neighfuncdefault printfInitial temperatore T0 f T0 xopt fopt sameanlist savarlist templist optimsax0 rastrigin Itextern Itintern T0 Log T templawhuang neighfuncdefault printfoptimal solution dispxopt printfvalue of the objective function f fopt scf templawhuang 2307 subplot211 xtitleHuang simulated annealingIterationMean Variance t 1lengthsameanlist plottsameanlistrtsavarlistg legendMeanVariance subplot212 xtitleTemperature evolutionIterationTemperature plotttemplistk See Also optimsa templawcsa neighfunccsa Authors collette Yann COLLETTE ycolletfreesurffr 2308 Name templawvfsa This function implements the Very Fast Simulated Annealing from L Ingber Tout templawvfsaTinstepmeanstepvartempstagen param Parameters Tin the temperature at the current stage stepmean the mean value of the objective function computed during the current stage stepvar the variance value of the objective function computed during the current stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param a float the c parameter of the VFSA method 001 by default Tout the temperature for the temperature stage to come Description This function implements the Very Fast Simulated Annealing from L Ingber Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 1 1 Probastart 08 Itintern 1000 Itextern 30 ItPre 100 printfSA the VFSA algorithm T0 computeinitialtempx0 rastrigin Probastart ItPre neighfuncdefault printfInitial temperatore T0 f T0 xopt fopt sameanlist savarlist templist optimsax0 rastrigin Itextern Itintern T0 Log T templawvfsa neighfuncvfsa printfoptimal solution dispxopt printfvalue of the objective function f fopt scf subplot211 templawvfsa 2309 xtitleVFSA simulated annealingIterationMean Variance t 1lengthsameanlist plottsameanlistrtsavarlistg legendMeanVariance subplot212 xtitleTemperature evolutionIterationTemperature plotttemplistk See Also optimsa neighfuncvfsa templawhuang Authors collette Yann COLLETTE ycolletfreesurffr Parte LII Parâmetros 2311 Name addparam Add a parameter to a list of parameters paramlisterr addparamlistnameparamnameparamvalue Parameters listname the list of parameters This list must have been initialize by a call to initparam paramname a string The name of the parameter to be added in the list of parameters paramvalue the value associated to the parameter paramname This parameter is optional You can set the value of this parameter via a call to setparam paramlist the updated list of parameters err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function creates a new parameter in a list of parameters You can set the value of the parameter using this function or you can set it via a call to setparam Examples mylist initparam mylist addparammylistminbound0 0 0 See Also initparam setparam getparam removeparam isparam Authors collette ycolletfreesurffr 2312 Name getparam Get the value of a parameter in a parameter list reserr getparamlistnameparamnamedefaultvalue Parameters listname the list of parameters This list must have been initialized by a call to initparam paramname a string The name of the parameter to be add in the list of parameters defaultvalue the default value to be stored in the parameter if paramname has not been found res the value of the parameter If the parameter doesnt exist res err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function returns the value of the parameter paramname in a parameter list If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 dispgetparammylistminbound1 1 1 dispgetparammylistmaxbound 1 1 1 See Also initparam setparam addparam removeparam isparam Authors collette ycolletfreesurffr 2313 Name initparam Initialize the structure which will handles the parameters list paramlist initparam Parameters paramlist an initialized list of parameters this list is empty and is of type plist Description This function initialize an empty list of parameters You must initialize the list of parameters before using it Examples mylist initparam mylist addparammylistminbound0 0 0 See Also addparam setparam getparam removeparam isparam Authors collette ycolletfreesurffr 2314 Name isparam Check if a parameter is present in a parameter list reserr isparamlistnameparamname Parameters listname the list of parameters This list must have been initialize by a call to initparam paramname a string The name of the parameter to be add in the list of parameters res the result T is the parameter is present F otherwise err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function checks if a parameter is present in a parameter list If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 dispisparammylistminbound dispisparammylistmaxbound See Also initparam setparam getparam removeparam addparam Authors collette ycolletfreesurffr 2315 Name listparam List all the parameters name in a list of parameters stringlisterr listparamlistname Parameters listname the list of parameters This list must have been initialize by a call to initparam stringlist the list of parameters name err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description List all the parameters name in a list of parameters If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 mylist addparammylistmaxbound1 1 1 displistparammylist See Also initparam setparam getparam removeparam isparam Authors collette ycolletfreesurffr 2316 Name removeparam Remove a parameter and its associated value from a list of parameters paramlisterr removeparamlistnameparamname Parameters listname the list of parameters This list must have been initialize by a call to initparam paramname a string The name of the parameter to be removed from the list of parameters If the parameter doesnt exist nothing happens paramlist the updated list of parameters err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function allows to remove a parameter and its associated value from a list of parameters If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 mylist addparammylistmaxbound0 0 0 mylist removeparammylistminbound See Also initparam setparam getparam addparam isparam Authors collette ycolletfreesurffr 2317 Name setparam Set the value of a parameter in a parameter list paramlisterr setparamlistnameparamnameparamvalue Parameters listname the list of parameters This list must have been initialize by a call to initparam paramname a string The name of the parameter to be added in the list of parameters paramvalue the value to be associated to the parameter paramname paramlist the updated list of parameters err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function sets the value of an already existing parameter If the parameter doesnt exist err is set to T If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 mylisterr setparammylistminbound1 1 1 disperr mylisterr setparammylistmaxbound1 1 1 disperr See Also initparam addparam getparam removeparam isparam Authors collette ycolletfreesurffr Parte LIII Atoms 2319 Name Getting started Introduction This page teaches how to get started with ATOMS module manager on the scilab platform towards a session example It describes how one can install a module and load it in Scilab environment Atoms Configure ATOMS to display extrainformations atomsSetConfigVerboseTrue List available modules atomsList ampltoolbox An interface to load nl files created by AMPL ANNToolbox ANN Toolbox conmin A Scilab interface to the conmin optimization method CUTEr Testing environment for optimization and linear algebra solvers dacescilab This is a conversion of the well known DACE kriging toolbox for Matlab ddetoolbox Dynamic Data Exchange client for Scilab HYDROGRv50 Models and function for operational hydrology lolimot A fast neural network LOcal LInear MOdel Tree modulelycee Scilab pour les lycées NISP Non Intrusive Spectral Projection plotlib Matlablike Plotting library for Scilab scilab2c Translate Scilab code into C code scipad Scipad 720 simplex This package contains the simplex optimization method sndfiletoolbox Read write sound files stixbox Statistics toolbox for Scilab 52 Install a module Installing a module download and extract it atomsInstallNISP NISP 21 will be installed in the allusers section Installing NISP 21 success Load a module The module is installed but its not loaded in the scilab environment and its func tionnalities are not available yet Getting started 2320 By default a module is added to the list of modules to load at Scilab start when its installed More information on the autoload system atomsAutoloadList atomsAutoloadAdd atom sAutoloadDel atomsLoadNISP Start NISP Toolbox Load gateways Load help Load demos Remove a module atomsRemove NISP NISP 21 will be removed from the allusers section the package NISP 21 is currently loaded It will removed at next Scilab restart Authors Pierre MARECHAL DIGITEO 2321 Name Functions Summary InstallRemoveUpdate modules atomsInstall Install one or several modules atomsUpdate Update one or several modules atomsRemove Remove one or several modules atomsGetInstalled Get the list of installed external modules atomsIsInstalled Determines whether the module is installed or not Load modules atomsLoad Load one or several modules atomsGetLoaded Get the list of loaded modules atomsIsLoaded Determines whether the module is loaded or not atomsAutoloadList Get the list of modules registered to autoload at Scilab start atomsAutoloadAdd Add one or several modules to autoload system atomsAutoloadDel Remove one or several modules from autoload system Get information atomsList List available modules atomsSearch Searches for modules atomsShow Show the caracteristics of a module atomsDepTreeShow Show the dependency tree of a module Manage repositories atomsRepositoryList Get the list of managed repositories atomsRepositoryAdd Add one or several URLs to the list of managed repositories atomsRepositoryDel Remove one or several URLs from the list of man aged repositories Manage ATOMS system atomsSystemUpdate Update the list of available modules atomsSetConfig Manage ATOMS parameters Authors Pierre MARECHAL DIGITEO 2322 Name atomsAutoloadAdd Add one or several modules to autoload nbAdd atomsAutoloadAddmodulessection Parameters modules mx1 mx2 or mx3 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present the most recent version is used 3rd Col Installed section Optionnal If this field is emp ty or is not present and module is in stalled in both user and allusers sections the section of autoload list is used section This argument controls which autoload list is changed section is a singlestring and its value should be allusers modules are added to the allusers autoload list and all users of scilab are affected user modules are added to the user autoload list and only the current user is affected If SCIcontrib is write accessible allusers is the default value Otherwise the default value is user nbAdd An integer the number of modules successfully added Description Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsSetConfigautoloadAddAfterInstallFalse atomsInstalltoolbox5user atomsAutoloadList atomsAutoloadAddtoolbox5user atomsAutoloadList atomsAutoloadAdd 2323 atomsAutoloadDeltoolbox5 atomsAutoloadAddtoolbox5 10user atomsAutoloadList atomsAutoloadDeltoolbox5 atomsAutoloadAddtoolbox5 10 useruser atomsAutoloadList atomsRemovetoolbox5user atomsSetConfigautoloadAddAfterInstallTrue atomsRepositoryDelhttpscene1testatomsscilaborg atomsAutoloadList See Also atomsAutoloadDel atomsAutoloadList Authors Pierre MARECHAL DIGITEO 2324 Name atomsAutoloadDel Remove one or several modules from the autoload system nbDel atomsAutoloadDelmodulessection Parameters modules mx1 mx2 or mx3 character string matrix 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present all ver sions of the module are removed from the au toload system 3rd Col Installed section Optionnal If this field is empty or is not present modules installed in both user and allusers sections are searched section This argument controls the list of sections where search moduless to remove from autoload system section is a singlestring and its value should be all modules to remove from autotoload list are searched in both user and allusers sections allusers modules to remove from autotoload system are only searched in the allusers autoload list user modules to remove from autotoload system are only searched in the user autoload list If SCI is write accessible all is the default value Otherwise the default value is user nbDel An integer the number of modules successfully removed from the autoload system Description atomsAutoloadDel remove one or several modules from the autoload system Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox5user atomsAutoloadList atomsAutoloadDel 2325 atomsAutoloadDeltoolbox5 atomsAutoloadList atomsAutoloadAddtoolbox5 10 useruser atomsAutoloadList atomsAutoloadDeltoolbox5 10 atomsAutoloadList atomsAutoloadAddtoolbox5 10 useruser atomsAutoloadList atomsAutoloadDeltoolbox5 10 user atomsAutoloadList atomsAutoloadAddtoolbox5 10 useruser atomsAutoloadList atomsAutoloadDeltoolbox5 10 useruser atomsAutoloadList atomsRemovetoolbox5user atomsRepositoryDelhttpscene1testatomsscilaborg See Also atomsAutoloadAdd atomsAutoloadList Authors Pierre MARECHAL DIGITEO 2326 Name atomsAutoloadList Get the list of modules registered to autoload modules atomsAutoloadListsection Parameters section This argument controls the list of section where search URLs section is a singlestring and its value should be all modules present on both user and allusers autoload lists are returned allusers only modules present on the allusers autoload lists are returned user only modules present on the user autoload lists are returned The default value is all modules 4xn character string matrix 1st Col Modules technical name 2nd Col Modules version 3rd Col Modules installed section 4th Col Autoload list section Description atomsAutoloadList returns the list of modules registered to autoload Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox1 atomsAutoloadListuser atomsAutoloadListallusers atomsAutoloadListall atomsRemovetoolbox1 atomsRepositoryDelhttpscene1testatomsscilaborg See Also atomsAutoloadAdd atomsAutoloadDel Authors Pierre MARECHAL DIGITEO 2327 Name atomsDepTreeShow Show the dependency tree of a module atomsDepTreeShowmodule Parameters module 1x1 or 1x2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present the most recent version is used Description atomsDepTreeShow shows the dependency tree of an external module Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsDepTreeShowtoolbox6 See Also atomsShow atomsList Authors Pierre MARECHAL DIGITEO 2328 Name atomsGetInstalled Get the list of installed external modules installed atomsGetInstalledsection Parameters installed 5xn String matrix 1st column External modules technical name 2nd column External modules version 3rd column allusersuser this parameter tell if the external module has been installed for all users or only for the current user 4th column External modules installation path 5th column IA this parameter tell if the external module has been automatically or in tentionnaly installed section This argument filter the output list section is a singlestring and its value should be all atomsGetInstalled lists external modules installed in both user and allusers sec tions allusers atomsGetInstalled only lists external modules installed in the allusers sec tion user atomsGetInstalled only lists external modules installed in the user section The default value is all Description atomsGetInstalled returns the list of installed external modules Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox5 atomsGetInstalled atomsRemovetoolbox5 See Also atomsInstall atomsIsInstalled atomsGetInstalled 2329 Authors Pierre MARECHAL DIGITEO 2330 Name atomsGetLoaded Get the list of loaded external modules loaded atomsGetLoaded Parameters loaded 5xn String matrix 1st column External modules technical name 2nd column External modules version 3rd column allusersuser this parameter tell if the external module has been installed for all users or only for the current user 4th column External modules installation path 5th column IA this parameter tell if the external module has been automatically or in tentionnaly installed Description atomsGetLoaded returns the list of loaded external modules Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox5 atomsLoadtoolbox5 atomsGetLoadedtoolbox5 atomsRemovetoolbox5 See Also atomsLoad atomsIsLoaded Authors Pierre MARECHAL DIGITEO 2331 Name atomsInstall Install one or several external modules result atomsInstallmodulessection result atomsInstallfile Parameters modules mx1 mx2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present the most recent version is used file mx1 Matrix of strings 1st Col Filesystem path Mandatory section This argument controls where the external module is installed section is a singlestring and its value should be allusers the external module is installed for all users of the computer and is located in SCIcontrib allusers zone user the external module is only installed for the current user and is located in SCI HOMEatoms user zone If SCIcontrib is write accessible allusers is the default value Otherwise the default value is user result 5xn character string matrix 1st Col Technical name 2nd Col Version 3rd Col Installation section this parameter determines whether the module has been installed for all users or only for the current user 4th Col Installation path 5th Col Status I stands for Intentionnaly A stands for Automatically Description atomsInstall install one or more external modules atomsInstall 2332 Examples Example 1 Installing a module from a repository Display some additionnal informations atomsSetConfigVerboseTrue Load the test repository atomsRepositoryAddhttpscene1testatomsscilaborg Install a module atomsInstalltoolbox1 Install a specific version atomsInstalltoolbox2 20 Install several modules atomsInstalltoolbox4 10 toolbox2 10 Install a module in the user section atomsInstalltoolbox5user Install a module in the allusers section write access on SCI directory is needed atomsInstalltoolbox6 10toolbox3 10 allusers Get the list of installed modules disp atomsGetInstalled Cleaning atomsRemovetoolbox1 toolbox2 toolbox3 toolbox4 toolbox5 toolbox6 Example 2 Installing a local module As well as installing modules from the central repository you can also install modules directly from your own machine Display some additionnal informations atomsSetConfigVerboseTrue Install a module atomsInstallSCImodulesatomstestsunitteststoolbox7101binzip Get the list of installed modules disp atomsGetInstalled Cleaning atomsRemovetoolbox7 atomsInstall 2333 See Also atomsIsInstalled atomsGetInstalled atomsRemove Authors Pierre MARECHAL DIGITEO 2334 Name atomsIsInstalled Determines whether the module is installed Returns true if the module is installed false otherwise res atomsIsInstalledmodulessection Parameters modules mx1 mx2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present modules version is ignored 3rd Col Section Optionnal If this field is empty or is not present modules section is ignored section This argument controls the list of searched modules section is a singlestring and its value should be all atomsIsInstalled searchs external modules installed in both user and allusers sections allusers atomsIsInstalled searchs external modules installed in the allusers section user atomsIsInstalled searchs external modules installed in the user section The default value is all res Description Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg Install the needed module for the purpose of the example atomsInstalltoolbox5user simplest way atomsIsInstalledtoolbox5 Check several modules atomsIsInstalledtoolbox5 toolbox4 atomsIsInstalled 2335 with a specific version atomsIsInstalledtoolbox5 10 toolbox4 10 toolbox5 11 installed in a specific section atomsIsInstalledtoolbox5 10 toolbox4 10 toolbox5 11user atomsIsInstalledtoolbox5 10 toolbox4 10 toolbox5 11allusers Some cleaning atomsRepositoryDelhttpscene2testatomsscilaborg atomsRemovetoolbox2 See Also atomsInstall atomsGetInstalled Authors Pierre MARECHAL DIGITEO 2336 Name atomsIsLoaded determines whether a module is loaded or not result atomsIsLoadedmodules Parameters modules mx1 mx2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present modules version is ignored 3rd Col Section Optionnal If this field is empty or is not present modules section is ignored result mx1 boolean matrix Description atomsIsLoaded determines whether a module is loaded or not Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene2testatomsscilaborg Install toolbox4 both 10 and 11 version atomsInstalltoolbox4 10user Load the version 10 atomsLoadtoolbox4 10 Ignore the modules version atomsIsLoadedtoolbox4 With a specific version atomsIsLoadedtoolbox4 10 Check several modules atomsIsLoaded toolbox4 10 toolbox4 11 toolbox1 10 Some cleaning atomsRepositoryDelhttpscene2testatomsscilaborg atomsRemovetoolbox2 atomsIsLoaded 2337 See Also atomsLoad atomsGetLoaded Authors Pierre MARECHAL DIGITEO 2338 Name atomsList List available external modules atomsList Description List available external modules Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsList See Also atomsShow atomsDepTreeShow Authors Pierre MARECHAL DIGITEO 2339 Name atomsLoad Install one or several external modules result atomsLoadnameversion Parameters name Matrix of strings External module name version Matrix of strings External module version This is an optional parameter If its not defined the most recent version of the module is used result Description atomsLoad install one or more external modules Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox2 10 atomsInstalltoolbox2 20 atomsLoadtoolbox2 10 t2version t2function1 atomsRemovetoolbox2 See Also atomsIsLoaded atomsGetLoaded Authors Pierre MARECHAL DIGITEO 2340 Name atomsRemove Remove one or several modules result atomsRemovemodulessection Parameters modules mx1 or mx2 character string matrix 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present all ver sions of the module are removed section This argument controls the list of sections where search modules to remove section is a singlestring and its value should be all Modules to remove are searched in both user and allusers sections allusers Modules to remove are only searched in the allusers section user Modules to remove are only searched in the user section If SCI is write accessible all is the default value Otherwise the default value is user result 5xn character string matrix 1st Col Technical name 2nd Col Version 3rd Col Installation section this parameter determines whether the module has been installed for all users or only for the current user 4th Col Installation path 5th Col Status I stands for Intentionnaly A stands for Automatically Description atomsRemove remove one or more modules Examples Display some additionnal informations atomsSetConfigVerboseTrue atomsRemove 2341 Load the test repository atomsRepositoryAddhttpscene2testatomsscilaborg install toolbox4 both 10 and 11 versions Remove all versions of a module atomsInstalltoolbox4 10toolbox4 11user atomsRemovetoolbox4 Remove a specific version atomsInstalltoolbox4 10toolbox4 11user atomsRemovetoolbox4 10 atomsRemovetoolbox4 11 Remove several modules atomsInstalltoolbox4toolbox3user atomsRemovetoolbox4toolbox3 Remove a module from a specific section This example needs write access on SCI directory atomsInstalltoolbox4user atomsInstalltoolbox4allusers dispatomsGetInstalled atomsRemovetoolbox4user dispatomsGetInstalled atomsRemovetoolbox4allusers dispatomsGetInstalled Unload the test repository atomsRepositoryDelhttpscene2testatomsscilaborg See Also atomsRemove atomsIsInstalled atomsGetInstalled Authors Pierre MARECHAL DIGITEO 2342 Name atomsRepositoryAdd Add one or several URLs to the list of managed repositories nbAdd atomsRepositoryAddurlsection Parameters url Matrix of strings list of the URLs to add section This argument controls where the repository is added section is a singlestring and its value should be allusers the repository is added to the allusers list and all user of scilab are affected user the repository is added to the user list and only the current user is affected If SCIcontrib is write accessible allusers is the default value Otherwise the default value is user nbAdd An integer the number of repositories successfully added Description Examples atomsRepositoryList atomsRepositoryAddhttpscene1testatomsscilaborg atomsRepositoryList See Also atomsRepositoryDel atomsRepositoryList Authors Pierre MARECHAL DIGITEO 2343 Name atomsRepositoryDel Remove one or several URLs from the list of managed repositories nbDel atomsRepositoryDelurlsection Parameters url character string matrix list of the URLs to remove section This argument controls the list of sections where search URLs to remove section is a singlestring and its value should be all URLs to remove are searched in both user and allusers sections allusers URLs to remove are only searched in the allusers section user URLs to remove are only searched in the user section If SCI is write accessible all is the default value Otherwise the default value is user nbDel An integer the number of repositories successfully removed Description Examples atomsRepositoryList atomsRepositoryAddhttpscene1testatomsscilaborg atomsRepositoryList atomsRepositoryDelhttpscene1testatomsscilaborg atomsRepositoryList See Also atomsRepositoryAdd atomsRepositoryList Authors Pierre MARECHAL DIGITEO 2344 Name atomsRepositoryList Get the list of managed repositories repositories atomsRepositoryListsection Parameters section This argument controls the list of section where search URLs section is a singlestring and its value should be all URLs present in the user allusers and official section are listed allusers only URLs present in the allusers section are listed user only URLs present in the user section are listed official only URLs present in the official section are listed The default value is all repositories Matrix of strings the first column give the list of repositories managed by ATOMS and the second column indicate if the repository is a official repository if the repository has been added for all users or only for the current user Description atomsRepositoryList return a matrix that give the list of available repositories Examples atomsRepositoryAddhttpscene1atomsscilaborg atomsRepositoryList atomsRepositoryListall atomsRepositoryListofficial atomsRepositoryListallusers atomsRepositoryListuser atomsRepositoryDelhttpscene1atomsscilaborg See Also atomsRepositoryAdd atomsRepositoryDel Authors Pierre MARECHAL DIGITEO 2345 Name atomsSearch Searches for external modules result atomsSearchpattern Parameters pattern String The pattern to search for result Description atomsSearch searches for packages matching one of the patterns supplied as input argument Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg atomsSearchtoolbox See Also atomsList Authors Pierre MARECHAL DIGITEO 2346 Name atomsSetConfig Manage ATOMS system parameters result atomsSetConfigparametervalue Parameters parameter singlestring matrix value singlestring matrix result Number of changed parameters Proxy Parameter Description Values useProxy UseDont use proxies TrueFalse proxyHost the hostname IP or DNS name proxyPort the port proxyUser Specify the username for authen tication on a proxy server proxyPassword Specify the password for authen tication on a proxy server Network Parameter Description Values offLine If set to True the system on ly works with local repositories The offline mode permits the us er to install modules from a lo cal repository or a local package hard disk USB keys even if the network is unreachable TrueFalse Autoload System Parameter Description Values autoload EnableDisable autoload system TrueFalse autoloadAddAfterInstall Automatically add a module to the list of module to autoload at Scilab start TrueFalse Miscellenous Parameter Description Values atomsSetConfig 2347 verbose Display or not extrainforma tions TrueFalse Description atomsSetConfig returns the list of modules registered to autoload Examples Display extrainformations atomsSetConfigVerboseTrue Disable autoload system atomsSetConfigautoloadFalse Authors Pierre MARECHAL DIGITEO 2348 Name atomsShow Show the caracteristics of a module atomsShowmodule Parameters module 1x1 or 1x2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present the most recent version is used Description Show the caracteristics of a module Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsShowtoolbox5 See Also atomsList atomsDepTreeShow Authors Pierre MARECHAL DIGITEO 2349 Name atomsSystemUpdate Update the list of available modules atomsSystemUpdate Description atomsSystemUpdate update the list of available modules Examples atomsSystemUpdate Authors Pierre MARECHAL DIGITEO 2350 Name atomsUpdate Update one or several external modules result atomsUpdate result atomsUpdatenamesection Parameters name 1xn character string matrix modules technical name section This argument controls the list of sections where search modules to update section is a singlestring and its value should be all Modules to remove are searched in both user and allusers sections allusers Modules to remove are only searched in the allusers section user Modules to remove are only searched in the user section If SCI is write accessible all is the default value Otherwise the default value is user result Description atomsUpdate update one or more external modules Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg Install toolbox5 atomsInstalltoolbox5 dispatomsGetInstalled Load the 2nd scenario in which toolbox4 has been updated toolbox4 version 11 has been added toolbox4 is a dependency of toolbox5 atomsRepositoryDelhttpscene1testatomsscilaborg atomsRepositoryAddhttpscene2testatomsscilaborg Update toolbox5 atomsUpdatetoolbox5 dispatomsGetInstalled Some cleaning atomsUpdate 2351 atomsRepositoryDelhttpscene2testatomsscilaborg atomsRemovetoolbox5 See Also atomsInstall atomsRemove atomsGetInstalled Authors Pierre MARECHAL DIGITEO Parte LIV EntradaSaída de Arquivos Matlab Binários 2353 Name loadmatfile loads a Matlab V6 MATfile binary or ASCII into Scilab loadmatfileformatfilenamevar1var2 loadmatfilefilenameformatvar1var2 loadmatfilefilenamevar1var2format Parameters filename character string containing the path of the file needed format file format if not given and file has extension mat file is considered to be binary mat binary file ascii option to force Scilab to read file as an ASCII file var1 var2 character strings containing the name of the variables to load only for binary files Description loads a Matlab MATfile into Scilab The Matlab data types are converted into the Scilab equivalents Examples A rand1010 B sprand10010001 savematfiletestmatfilematABv6 clear loadmatfiletestmatfilemat dispA dispB See Also load savematfile save mfile2sci matfile2sci Authors Serge Steer INRIA VC Bibliography This function has been developped following the MATFile Format description MatFile Format httpwwwmathworkscomaccesshelpdeskhelppdfdocmat labmatfileformatpdf 2354 Name matfileclose Closes a Matlab V5 binary MATfile status matfileclosefd Parameters fd Real file descriptor returned by matfileopen status Boolean T if closure succeeds F otherwise Description Closes a Matlab binary MATfile opened by matfileopen See Also matfileopen matfilevarreadnext matfilevarwrite matfilelistvar Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2355 Name matfilelistvar Lists variables of a Matlab V5 binary MATfile names classes types matfilelistvarfd Parameters fd Real file descriptor returned by matfileopen names String vector names of the variables classes Real vector classes of the variables types Real vector data types of the variables Description Lists variables of a Matlab binary MATfile opened by matfileopen See Also matfileopen matfileclose matfilevarwrite matfilevarreadnext Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2356 Name matfileopen Opens a Matlab V5 binary MATfile fd matfileopenfilename mode Parameters filename String the path of the file Must contain only ANSI character mode String file access type r by default r opens the file for reading w opens the file for writing fd Real file descriptor 1 if opening failed Description Opens a Matlab binary MATfile for reading or writing data See Also matfileclose matfilevarreadnext matfilevarwrite matfilelistvar Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2357 Name matfilevarreadnext Reads next variable in a Matlab V5 binary MATfile name value vartype matfilevarreadnextfd Parameters fd Real file descriptor returned by matfileopen name String name of the variable read or if reading failed value Any Scilab type value of the variable read or an empty matrix if reading failed vartype Real type of the variable if reading succeeds or 0 if the variable type is unknown 1 if end of file has been reached Description Reads next variable in a Matlab binary MATfile opened by matfileopen See Also matfileopen matfileclose matfilevarwrite matfilelistvar Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2358 Name matfilevarwrite Write a variable in a Matlab V5 binary MATfile status matfilevarreadnextfd name value compressionflag Parameters fd Real file descriptor returned by matfileopen name String name of the variable to write in the file value Any Scilab type value of the variable to write in the file compressionflag Boolean indicate if data compression has to be used flag equaled to T or not status Boolean T if writing succeeds F otherwise Description Writes a variable in a Matlab binary MATfile opened by matfileopen See Also matfileopen matfileclose matfilevarreadnext matfilelistvar Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2359 Name savematfile write a Matlab MATfile binary or ASCII savematfilefilename savematfilefilename var1 var2 savematfilefilename struct s savematfilefilename struct s f1 f2 savematfile v4 savematfile v6 savematfile v7 savematfile v73 savematfile filename var1 var2 Parameters filename character string containing the path of the file needed format data format to use mat binary MATfile default ascii 8bit ASCII format ascii double 16bit ASCII format ascii tabs delimits with tabs ascii double tabs 16digit ASCII format tab delimited v4 A format that MATLAB Version 4 can open v6 A format that MATLAB Version 6 and earlier can open v7 A format that MATLAB Version 7 and earlier can open default v73 A format that MATLAB Version 73 and earlier can open var1 var2 character strings containing the name of the variables to load only for binary files struct s saves all fields of the scalar structure s as individual variables within the file filename struct s f1 f2 saves as individual variables only those structure fields specified sf1 sf2 savematfile 2360 Description saves variables in a Matlab MATfile from Scilab The Scilab data types are converted into the Matlab equivalents Examples A rand1010 B sprand10010001 savematfiletestmatfilematABv6 clear loadmatfiletestmatfilemat dispA dispB See Also load save loadmatfile mfile2sci Authors Serge Steer INRIA VC Bibliography This function has been developped following the MATFile Format description MatFile Format httpwwwmathworkscomaccesshelpdeskhelppdfdocmat labmatfileformatpdf Parte LV xcos 2362 Índice 6 Batch functions 2363 lincos 2364 scicos 2365 scicossimulate 2366 scicosim 2368 steadycos 2370 7 palettes 2372 1 Annotations palette 2372 2 Commonly used blocks palette 2375 3 Continuous time systems palette 2383 4 Demonstrations blocks palette 2408 5 Discontinuities palette 2425 6 Discrete time systems palette 2438 7 Electrical palette 2455 8 Event handling palette 2513 9 Implicit palette 2559 10 Integer palette 2564 11 Lookup tables palette 2595 12 Math operations palette 2602 13 Matrix operation palette 2649 14 Port Subsystem palette 2712 15 Signal processing palette 2719 16 Signal routing palette 2724 17 Sinks palette 2760 18 Sources palette 2815 19 Thermohydraulics palette 2868 20 User defined functions palette 2882 21 Zero crossing detection palette 2908 8 Programming xcos Blocks 2918 1 C Computational Functions 2918 2 Scilab Computational Functions 2932 3 Utilities Functions 2936 9 Scilab Data Structures 2947 1 Blocks 2947 2 CompilationSimulation 2958 3 Diagram 2966 4 Links 2971 10 Scilab Utilities Functions 2974 buildouttb 2975 createpalette 2976 getscicosversion 2977 scicosdebug 2978 var2vec 2979 vec2var 2980 Capítulo 6 Batch functions Batch functions 2364 Nome lincos Constructs by linearization a linear statespace model from a general dynamical system described by a xcos diagram sys lincosscsm x0u0 param Module xcos Description Construct a linear statespace system by linearizing a model given as a xcos diagram The output is a Scilab data structure of type continuoustime statespace linear system sys lincosscsm x0u0 param Parameters scsm a xcos data structure x0 column vector Continuous state around which linearization to be done default 0 u0 column vector Input around which linearization to be done default 0 param param list with two elements default list1d60 param1 scalar Perturbation level for linearization the following variation is used delxui param1param11d4absxui param2 scalar Time t sys statespace system File content SCImodulesscicosmacrosscicosautolincossci See Also steadycos Finds an equilibrium state of a general dynamical system described by a xcos diagram Scilab Function scicossimulate Function for running xcos simulation in batch mode Scilab Function Authors Ramine Nikoukhah INRIA Batch functions 2365 Nome scicos OBSOLETE see xcos scsm scicostoto Module xcos See Also xcos Batch functions 2366 Nome scicossimulate Function for running xcos simulation in batch mode InfoscicossimulatescsmInfoscicoscontextflag Module xcos Description This function is used to simulate xcos diagrams in batch mode It requires the scsm structure which can be obtained by loading in Scilab the cos file eg load mydiagramcos Contrary to the function the diagram need not be compiled before being saved InfoscicossimulatescsmInfoscicoscontextflag Parameters scsm xcos diagram obtained by load filecos Note that the version of filecos must be the current version If not load into xcos and save Info a list It must be list at the first call then use output Info as input Info for the next calls Info contains compilation and simulation information and is used to avoid recompilation when not needed scicoscontext a Scilab struct containing values of symbolic variables used in the context and xcos blocks This is often used to change a parameter in the diagram context In that case make sure that in the diagram context the variable is defined such that it can be modified Say a variable a is to be defined in the context having value 1 and later in batch mode we want to change the value of a In that case in the context of the diagram place if existsa then a1end If you want then to run the simulation in batch mode using the value a2 set scicoscontexta2 flag string If it equals nw no window then blocks using graphical windows are not executed Note that the list of such blocks must be updated as new blocks are added Info contains compilation and simulation information and is used to avoid recompilation when not needed Normally it should not be modified File content SCImodulesscicosmacrosscicosautoscicossimulatesci See Also scicosim Scicos batch simulation function Scilab Function xcos Block diagram editor and GUI for the hybrid simulator Scilab Function steadycos Finds an equilibrium state of a general dynamical system described by a xcos diagram Scilab Function Batch functions 2367 lincos Constructs by linearization a linear statespace model from a general dynamical system described by a xcos diagram Scilab Function Authors Ramine Nikoukhah INRIA Batch functions 2368 Nome scicosim xcos batch simulation function statet scicosimstatetcurtfsimstrtol Module xcos Description Simulator for xcos compiled diagram Usually scicosim is called by xcos to perform simulation of a diagram But scicosim may also be called outside xcos Typical usage in such a case may be For advanced user it is possible to manually change some parameters or state values statet scicosimstatetcurtfsimstrtol Parameters state Scilab tlist containing initial state Usually generated by xcos Compile After loading a com piled cos file it can be found in cprstate tcur starting time of simulation At the beginning it must be zero tf final simulation time sim Scilab tlist containing compilation results Usually generated by xcos Compile After loading a compiled cos file it can be found in cprsim str start run or finish Function must be first called with start then with run one or more times and finally with finish tol vector atolrtolttoldeltatrealtimescalesolverhmax where atol rtol are respectively the ab solute and relative tolerances for ode or dae solver ttol is the precision on event dates must be very small deltat is maximum integration interval for each call to ode solver sometimes needed to force restaring the call to solver realtimescale is the correspondance between simulation time and real time 0 means no slowing down solver is the choice of solver 0 lsodar 100 daskr hmax max step size used by solver Default 000011000E061000E1010000100 state state after simulation t final reached time Usually tf but not always See Also scicossimulate Function for running xcos simulation in batch mode Scilab Function xcos Block diagram editor and GUI for the hybrid simulator Scilab Function Batch functions 2369 Authors Ramine Nikoukhah INRIA Alan Layec INRIA Batch functions 2370 Nome steadycos Finds an equilibrium state of a general dynamical system described by a xcos diagram XUYXPsteadycosscsmXUYIndxInduIndy Indxp param Module xcos Description This function finds the steady state for a given system described by a xcos diagram The diagram consists in general of a Super block with input and output port blocks The steady state concern only the continuoustime dynamics XUYXPsteadycosscsmXUYIndxInduIndy Indxp param Parameters scsm a xcos data structure X column vector Continuous state Can be set to if zero U column vector Input Can be set to if zero Y column vector Output Can be set to if zero Indx index of entries of X that are not fixed If all can vary set to 1 Indu index of entries of U that are not fixed If all can vary set to 1 Indy index of entries of Y that are not fixed If all can vary set to 1 Indxp index of entries of XP derivative of x that need not be zero If all can vary set to 1 Default param list with two elements default list1d60 param1 scalar Perturbation level for line arization the following variation is used delxui param1param11d4absxui pa ram2 scalar Time t X steady state X U stationary input U Y output corresponding to steady state found XP derivative of the state corresponding to steady state found File content SCImodulesscicosmacrosscicosautosteadycossci See Also lincos Constructs by linearization a linear statespace model from a general dynamical system described by a xcos diagram Scilab Function Batch functions 2371 scicossimulate Function for running xcos simulation in batch mode Scilab Function xcos Block diagram editor and GUI for the hybrid simulator Scilab Function Authors Ramine Nikoukhah INRIA 2372 Capítulo 7 palettes 1 Annotations palette palettes 2373 Nome Annotationspal Annotations palette Block Screenshot Module xcos Description This palette includes blocks used for annotations Blocks TEXTf Text palettes 2374 Nome TEXTf Text Block Screenshot Contents Text Palette Description Dialog box Default properties Interfacing function Authors Palette Annotations palette Description This special block is only use to add text at any point of the diagram window It has no effect on the simulation Dialog box Text a character string Text to be displayed Properties Type str of size 1 Font number a positive integer less than 6 number of selected font seexset palettes 2375 Properties Type vec of size 1 Font size a positive integer selected font size seexset Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function text Interfacing function SCImodulesscicosblocksmacrosMiscTEXTfsci Authors Ramine Nikoukhah INRIA 2 Commonly used blocks palette palettes 2376 Nome Commonlyusedblockspal Commonly used blocks palette Block Screenshot Module xcos Description In the Commonly used blocks palette you can find blocks from other palettes that most models use Blocks ANDBLK Activation and BIGSOMf Sum CMSCOPE Multi display scope CONSTm Constant CONVERT CONVERT Data Type Conversion CSCOPXY yfx permanent viewer DEMUX Demultiplexer DOLLARf Delay operator INTEGRALf Integration palettes 2377 INf Input Port LOGICALOP Logical operation MUX Multiplexer NRMSOMf Merge data OUTf Output Port PRODUCT Product RELATIONALOP Relational operation SATURATION Saturation SWITCH2m Switch2 TEXTf Text palettes 2378 Nome LOGICALOP Logical operation Block Screenshot Contents Logical operation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Commonly used blocks palette Description The Logical Operator block performs the specified logical operation on its inputs An input value is TRUE 1 if it is nonzero and FALSE 0 if it is zero Dialog box number of inputs The number of block inputs The value must be appropriate for the selected operator Properties Type vec of size 1 Operator AND palettes 2379 The logical operator to be applied to the block inputs Valid choices are the operators from the list Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function logicalop Interfacing function SCImodulesscicosblocksmacrosMiscLOGICALOPsci Computational function SCImodulesscicosblockssrcclogicalopc SCImodulesscicosblockssrcclogicalopi32c SCImodulesscicosblockssrcclogicalopi16c SCImodulesscicosblockssrcclogicalopi8c SCImodulesscicosblockssrcclogicalopui32c SCImodulesscicosblockssrcclogicalopui16c SCImodulesscicosblockssrcclogicalopui8c Authors Fady NASSIF INRIA palettes 2380 Ramine Nikoukhah INRIA palettes 2381 Nome RELATIONALOP Relational operation Block Screenshot Contents Relational operation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Commonly used blocks palette Description It performs logical comparison of its two inputs Dialog box Operator Designate the relational operator used to compare the two inputs Properties Type vec of size 1 Use zero crossing palettes 2382 Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function relationalop Interfacing function SCImodulesscicosblocksmacrosMiscRELATIONALOPsci Computational function SCImodulesscicosblockssrccrelationalopc SCImodulesscicosblockssrccrelationalopi32c SCImodulesscicosblockssrccrelationalopi16c SCImodulesscicosblockssrccrelationalopi8c SCImodulesscicosblockssrccrelationalopui32c SCImodulesscicosblockssrccrelationalopui16c SCImodulesscicosblockssrccrelationalopui8c Authors Fady NASSIF INRIA palettes 2383 Ramine Nikoukhah INRIA 3 Continuous time systems palette palettes 2384 Nome Continuouspal Continuous time systems palette Block Screenshot Module xcos Description The Continuous time systems palette includes basic linear blocks Blocks CLINDUMMYf Dummy CLR Continuous transfer function CLSS Continuous statespace system DERIV Derivative INTEGRALf Integration INTEGRALm Integration PID PID regulator TCLSS Continuous linear system with jump TIMEDELAY Time delay VARIABLEDELAY Variable delay palettes 2385 Nome CLINDUMMYf Dummy Block Screenshot Contents Dummy Palette Description Default properties Interfacing function Authors Palette Continuous time systems palette Description This block should be placed in any block diagram that contains a zerocrossing block but no continuous system with state The reason for that is that it is the ode solver that find zero crossing surfaces Default properties always active yes directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function cdummy Interfacing function SCImodulesscicosblocksmacrosLinearCLINDUMMYfsci palettes 2386 Authors Ramine Nikoukhah INRIA palettes 2387 Nome CLR Continuous transfer function Block Screenshot Contents Continuous transfer function Palette Description Dialog box Default properties Interfacing function Computational function Palette Continuous time systems palette Description This block realizes a SISO linear system represented by its rational transfer function NumeratorDe nominator The rational function must be proper Dialog box Numerator This parameter sets the numerator of the transfer function This must be a polynomial in s Properties Type pol of size 1 Denominator palettes 2388 This parameter sets the denominator of the transfer function This must be a polynomial in s Properties Type pol of size 1 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function csslti4 Interfacing function SCImodulesscicosblocksmacrosLinearCLRsci Computational function SCImodulesscicosblockssrcccsslti4c Type 4 palettes 2389 Nome CLSS Continuous statespace system Block Screenshot Contents Continuous statespace system Palette Description Dialog box Default properties Interfacing function Computational function Palette Continuous time systems palette Description This block realizes a continuoustime linear statespace system The system is defined by the matrices and the initial state The dimen sions must be compatible palettes 2390 Dialog box matrix A square matrix Properties Type mat of size 11 B matrix The matrix if system has no input Properties Type mat of size size121 C matrix The matrix if system has no output Properties Type mat of size 1size12 D matrix The matrix if system has no D term Properties Type mat of size 11 Initial state A vectorscalar initial state of the system Properties Type vec of size size12 Default properties always active yes directfeedthrough no zerocrossing no mode no palettes 2391 regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function csslti4 Interfacing function SCImodulesscicosblocksmacrosLinearCLSSsci Computational function SCImodulesscicosblockssrcccsslti4c Type 4 palettes 2392 Nome DERIV Derivative Block Screenshot Contents Derivative Palette Description Default properties Interfacing function Computational function Authors Palette Continuous time systems palette Description The Derivative block approximates the derivative of its input by computing Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 palettes 2393 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function deriv Interfacing function SCImodulesscicosblocksmacrosLinearDERIVsci Computational function SCImodulesscicosblockssrccderivc Type 4 Authors Ramine Nikoukhah INRIA palettes 2394 Nome INTEGRALf Integration Block Screenshot Contents Integration Palette Description Dialog box Default properties Interfacing function Computational function Palette Continuous time systems palette Description This block is an integrator The output is the integral of the input Dialog box Initial Condition A scalar that gives the initial condition Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing no palettes 2395 mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function integr Interfacing function SCImodulesscicosblocksmacrosLinearINTEGRALfsci Computational function SCImodulesscicosblockssrcfortranintegrf Type 0 palettes 2396 Nome INTEGRALm Integration Block Screenshot Contents Integration Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Continuous time systems palette Description This block is an integrator The output is the integral of the input Dialog box Initial Condition A vectorscalar initial conditions palettes 2397 With that parameter one can define the datatype of the inputoutput It can be a real or a complex type Properties Type mat of size 11 With reinitialization To reset its state to the specified initial condition based on an external signal select1 Properties Type vec of size 1 With saturation If selected limits the states to a value between the Lower saturation limit and Upper saturation limit parameters Properties Type vec of size 1 Upper limit The upper limit for the integral Properties Type mat of size 11 Lower limit The lower limit for the integral Properties Type mat of size 11 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function integralfunc Interfacing function SCImodulesscicosblocksmacrosLinearINTEGRALmsci palettes 2398 Computational function SCImodulesscicosblockssrccintegralfuncc SCImodulesscicosblockssrccintegralzfuncc Authors Fady NASSIF INRIA Alan Layec INRIA Ramine Nikoukhah INRIA palettes 2399 Nome PID PID regulator Block Screenshot Contents PID regulator Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Authors Palette Continuous time systems palette Description This block implements a PID controller The PID controller calculation algorithm involves three se parate parameters the Proportional the Integral and Derivative values The Proportional value deter mines the reaction to the current error the Integral determines the reaction based on the sum of recent errors and the Derivative determines the reaction to the rate at which the error has been changing The weighted sum of these three actions is used to adjust the process via a control element such as the position of a control valve or the power supply of a heating element Dialog box palettes 2400 Proportional The value of the gain that multiply the error Properties Type vec of size 1 Integral The value of the integral time of the error1Integral Properties Type vec of size 1 Derivation The value of the derivative time of the error Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosLinearPIDsci palettes 2401 Compiled Super Block content Authors Fady NASSIF INRIA palettes 2402 Nome TCLSS Continuous linear system with jump Block Screenshot Contents Continuous linear system with jump Palette Description Dialog box Default properties Interfacing function Computational function Palette Continuous time systems palette Description This block realizes a continuoustime linear statespace system with the possibility of jumps in the state The number of inputs to this block is two The first input is the regular input of the linear system the second carries the new value of the state which is copied into the state when an event arrives at the unique event input port of this block That means the state of the system jumps to the value present on the second input of size equal to that of the state The system is defined by the matrices and the initial state The dimensions must be compatible The sizes of inputs and outputs are adjusted automatically Dialog box palettes 2403 matrix A square matrix Properties Type mat of size 11 B matrix The matrix if system has no input Properties Type mat of size size121 C matrix The matrix if system has no output Properties Type mat of size 1size12 D matrix The matrix if system has no D term Properties Type mat of size 11 Initial state A vectorscalar initial state of the system Properties Type vec of size size12 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no palettes 2404 name of computational function tcslti4 Interfacing function SCImodulesscicosblocksmacrosLinearTCLSSsci Computational function SCImodulesscicosblockssrcctcslti4c Type 4 palettes 2405 Nome TIMEDELAY Time delay Block Screenshot Contents Time delay Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Continuous time systems palette Description The Transport Delay block delays the input by a specified amount of time It can be used to simulate a time delay At the start of the simulation the block outputs the Initial input parameter until the simulation time exceeds the Time delay parameter when the block begins generating the delayed input The Time delay parameter must be nonnegative Dialog box Delay The amount of simulation time that the input signal is delayed before being propagated to the output The value must be nonnegative palettes 2406 Properties Type vec of size 1 initial input The output generated by the block between the start of the simulation and the Time delay Properties Type vec of size 1 Buffer size The initial memory allocation for the number of points to store Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function timedelay Interfacing function SCImodulesscicosblocksmacrosLinearTIMEDELAYsci Computational function SCImodulesscicosblockssrcctimedelayc Type 4 Authors Ramine Nikoukhah INRIA palettes 2407 Nome VARIABLEDELAY Variable delay Block Screenshot Contents Variable delay Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Continuous time systems palette Description The Variable Transport Delay block can be used to simulate a variable time delay The block might be used to model a system with a pipe where the speed of a motor pumping fluid in the pipe is variable The block accepts two inputs the first input is the signal that passes through the block the second input is the time delay Dialog box Max delay It defines the largest value the time delay input can haveThe value cannot be negative palettes 2408 Properties Type vec of size 1 initial input The output generated by the block until the simulation time first exceeds the time delay input Properties Type vec of size 1 Buffer size The number of points the block can store Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function variabledelay Interfacing function SCImodulesscicosblocksmacrosLinearVARIABLEDELAYsci Computational function SCImodulesscicosblockssrccvariabledelayc Type 4 Authors Ramine Nikoukhah INRIA 4 Demonstrations blocks palette palettes 2409 Nome Demonstrationsblockspal Demonstrations blocks palette Block Screenshot Module xcos Description The Demonstrations blocks palette contains blocks used in some Xcos demonstration diagrams Blocks AUTOMAT hybrid automata BOUNCE Balls coordinates generator BOUNCEXY Balls viewer BPLATFORM Balls under a platform viewer PDE 1D PDE block palettes 2410 Nome AUTOMAT automata finite state machine Block Screenshot Contents automata finite state machine Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Demonstrations blocks palette Description This block gives the possibility to construct hybrid automata ie a hybrid system whose discrete part is defined via modes and transitions between modes and the continuous part is defined via DAE differential algebraic equations The automaton block provides a switching mechanism between subsystems corresponding to control modes of an automaton Subsystems are constructed in such a way that they have the state vector as input coming from the automaton block and compute the flow and jump functions zerocrossing and pass them back to the automaton block The state variables are defined in the automaton block and the subsystems are static functions Suppose that a hybrid automaton consists of control modes The continuoustime dynamics in mode is defined with DAE where and the dimension of is for any Suppose that in control mode there are jump conditions indicating jumps toward other modes The jump conditions are defined by functions where When a jump function changes sign and becomes positive a mode transition will happen When tran sition function becomes positive a transition to mode happens and state vector is reset to for In order to develop an automaton containing a mode with multiple reset functions the value of the current and previous active modes should be used These values are available at the first output port of the block The automaton block has the following inputoutput ports palettes 2411 Output 1 The first output port is a vector of size two con sisting of the current and the previous active control modes ie Output 2 The second output port is a vector of size providing the state vector and its first time derivative Inputs The automaton block has vector input ports corresponding to modes or subsys tems of the automaton Each input defines the dynamic behavior in the control each mode as well as the reset functions and the transition functions The input port which is the output of the subsystem is a vector of size Each input is composed of the following vector The first elements of the are the continuoustime dynamics The dy namics of the system in the control mode is described by a smooth index1 DAE The next elements of are the values used to reset the continuoustime state when a transition to control mode is activated The next elements of are the jump or zerocrossing functions If the zerocrossing function of mode crosses zero with negative to positive direction a transition to destination mode happens Event Output This is an event output port which is activated whenever a mode transition happens This event is useful when an event is needed to activate or initialize a part of the subsystem not included in the internal dynamics of the automaton block In the interface window the number of control modes the initial control mode and the initial value of continuoustime state at the beginning of the simulation should be given Find more documentation and demos about the Automaton block oat wwwscicosorg Interested users are referred to the paper Modeling Hybrid Automata in Scicos Masoud Najafi Ramine Nikoukhah 2007 IEEE Multiconference on Systems and Control Singapore palettes 2412 Dialog box Number of finitestate Modes Number of modes in the automation Properties Type vec of size 11 Initial Mode Initial active mode at the beginning of the simulation Properties Type vec of size 11 Number of continuoustime states Number of continuoustime states at modes Note that the num ber of continuoustime states is the same in all modes Properties Type vec of size 11 Continuoustime states initial values Initial value of continuoustime states at the beginning of the simulation Properties Type vec of size 11 Xproperties of continuoustime states in each Mode In this field the state types in mode are given A state in an index 1 DAE can be either differential state or algebraic state vector is coded in an MN matrix where M is the number of modes and N is the number of states This matrices indicates whether a continuoustime state is algebraic or differential in each control mode If in the mode state is differential the ijth element of the Xproperty matrix should set to 1 otherwise it should set to 1 Xproperty can be given as a 1N vector if type of states remain the same in all modes Properties Type mat of size 11 Jump from Mode 1MfinalGuardIn1i palettes 2413 The fields express the mode transition information Suppose that all control modes are labeled from 1 to M Then in the field corresponding to control modei destination modes of modei are defined in a vectorjth element of this vector gives the destination mode whenjth jump function becomes positive For example if in the field of the mode2 the user defines 134 it means that in mode2 there are three active jump functions When for example the third jump function becomes positive a mode transition to mode4 will be activated Properties Type vec of size 11 Default properties always active yes directfeedthrough no zerocrossing yes mode no regular inputs port 1 size 31 type 1 port 2 size 31 type 1 regular outputs port 1 size 21 type 1 port 2 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state yes discretetime state no object discretetime state no name of computational function automat Interfacing function SCImodulesscicosblocksmacrosMiscAUTOMATsci Computational function SCImodulesscicosblockssrccautomatc Type 10004 Authors Masoud Najafi INRIA palettes 2414 Nome BOUNCE Balls coordinates generator Block Screenshot Contents Balls coordinates generator Palette Dialog box Default properties Interfacing function Computational function Palette Demonstrations blocks palette Dialog box palettes 2415 Mass The parameter description 1 Properties Type vec of size 1 Radius The parameter description 2 Properties Type vec of size 1 xminxmaxyminymax The parameter description 3 Properties Type vec of size 1 xpos The parameter description 4 Properties Type vec of size 1 xdpos The parameter description 5 Properties Type vec of size 1 ypos The parameter description 6 Properties Type vec of size 1 ydpos The parameter description 7 Properties Type vec of size 1 g gravity The parameter description 8 Properties Type vec of size 1 C aerodynamic coeff The parameter description 9 Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing yes mode no palettes 2416 regular outputs port 1 size 21 type 1 port 2 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function bounceball Interfacing function SCImodulesscicosblocksmacrosMiscBOUNCEsci Computational function SCImodulesscicosblockssrccbounceballc Type 4 palettes 2417 Nome BOUNCEXY Balls viewer Block Screenshot Contents Balls viewer Palette Dialog box Default properties Interfacing function Computational function Authors Palette Demonstrations blocks palette Dialog box colors palettes 2418 The parameter description 1 Properties Type vec of size 1 radii The parameter description 2 Properties Type vec of size 1 window number 1 for automatic The parameter description 3 Properties Type vec of size 1 animation mode 01 The parameter description 4 Properties Type vec of size 1 Xmin The parameter description 5 Properties Type vec of size 1 Xmax The parameter description 6 Properties Type vec of size 1 Ymin The parameter description 7 Properties Type vec of size 1 Ymax The parameter description 8 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 palettes 2419 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function bouncexy Interfacing function SCImodulesscicosblocksmacrosMiscBOUNCEXYsci Computational function SCImodulesscicosblockssrccbouncexyc Type 4 Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2420 Nome BPLATFORM Balls under a platform viewer Block Screenshot Contents Balls under a platform viewer Palette Dialog box Default properties Interfacing function Authors Palette Demonstrations blocks palette Dialog box Default properties always active no directfeedthrough no zerocrossing no mode no palettes 2421 regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function bplatform2 Interfacing function SCImodulesscicosblocksmacrosMiscBPLATFORMsci Authors M Najafi INRIA palettes 2422 Nome PDE 1D PDE block Block Screenshot Contents 1D PDE block Palette Description Dialog box Default properties Interfacing function Authors Palette Demonstrations blocks palette Description This block is an implementation of several numerical schemes Finite Elements 1st and 2nd order Finite Differences 1st and 2nd order Finite Volumes 1st order to solve mono dimensional PDE Partial Differential Equation within SCICOS The mathematical framwork was restricts in PDEs linear scalars with maximum order 2 in time and space The goal is to provide engineers and physicists with an easy to use toolbox in SCICOS that will let them graphically describe the PDE to be solved A decision system selects the most efficient numerical scheme depending on the type of the PDE and runs the solvers palettes 2423 Dialog box a et b double The two edges of the discretization field specification de lEDP check box to select the PDE operators aix bit i17 are the operator coefficients type of PDE discriminant constant or variable in the later case the sign should be given Discretization methode choix check box is the choice for the manual or the automatic mode type in the manual mode we can give the method type Finite differences finite elements or finite volumes degré method degre 1 or 2 for the FD and FE methods 1 for the FV method Nombre de noeuds to give the number of the nodal points palettes 2424 Conditions initiales uxt0 dudt at t0 to give the initial conditions Conditions aux limites type two type of the boundray conditions are possible Dirichlet or Neumann expressions to give then boundray conditions expressions Points de mesures To give the list of mesurment points Name A getvalue box to give the block names Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 0 port 3 size 11 type 0 port 4 size 11 type 0 port 5 size 11 type 1 regular outputs port 1 size 101 type 1 port 2 size 01 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function PDE Interfacing function SCImodulesscicosblocksmacrosPDEPDEsci Authors EADS 20050116 palettes 2425 EADS 20050116 5 Discontinuities palette palettes 2426 Nome discontinuitiespal discontinuities palette Block Screenshot Module xcos Description discontinuities palette includes blocks whose outputs are discontinuities functions of their inputs Blocks BACKLASH Backlash DEADBAND Deadband DELAYVf Variable time delay HYSTHERESIS Hystheresis RATELIMITER Rate limiter QUANTf Quatization SATURATION Saturation palettes 2427 Nome BACKLASH Backlash Block Screenshot Contents Backlash Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description The Backlash block implements a system in which a change in input causes an equal change in output However when the input changes direction an initial change in input has no effect on the output The amount of sidetoside play in the system is referred to as the Dialog box initial output The initial output value Properties Type vec of size 1 palettes 2428 gap The width of the deadband Properties Type vec of size 1 use zerocrossing Select to enable use of zero crossing detection to detect engagement with lower and upper th resholds Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function backlash Interfacing function SCImodulesscicosblocksmacrosMiscBACKLASHsci Computational function SCImodulesscicosblockssrccbacklashc Type 4 Authors Ramine Nikoukhah INRIA palettes 2429 Nome DEADBAND Deadband Block Screenshot Contents Deadband Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description Provide a region of zero output Dialog box End of dead band The upper limit of the dead band Properties Type vec of size 1 Start of dead band palettes 2430 The lower limit of the dead band Properties Type vec of size 1 zero crossing Select to enable zero crossing detection to detect when the limits are reached Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function deadband Interfacing function SCImodulesscicosblocksmacrosMiscDEADBANDsci Computational function SCImodulesscicosblockssrccdeadbandc Type 4 Authors Ramine Nikoukhah INRIA palettes 2431 Nome HYSTHERESIS Hystheresis Block Screenshot Contents Hystheresis Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description Switch output between two constantsThe Relay block allows its output to switch between two speci fied values When the relay is on it remains on until the input drops below the value of the Switch off point parameter When the relay is off it remains off until the input exceeds the value of the Switch on point parameter The block accepts one input and generates one output Dialog box palettes 2432 switch on at The Switch on point parameter is converted to the input data type offline using roundtonearest and saturation Properties Type vec of size 1 switch off at The Switch off point parameter is converted to the input data type offline using roundtonearest and saturation Properties Type vec of size 1 output when on The output when the relay is on Properties Type vec of size 1 output when off The output when the relay is off Properties Type vec of size 1 use zero crossing yes Select to enable zero crossing detection to detect switchon and switchoff points Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function hystheresis palettes 2433 Interfacing function SCImodulesscicosblocksmacrosMiscHYSTHERESISsci Computational function SCImodulesscicosblockssrcchystheresisc Type 4 Authors Ramine Nikoukhah INRIA palettes 2434 Nome RATELIMITER Rate limiter Block Screenshot Contents Rate limiter Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description The Rate Limiter block limits the first derivative of the signal passing through it The output changes no faster than the specified limit Dialog box max slope The limit of the derivative of an increasing input signal Properties Type vec of size 1 min slope palettes 2435 The limit of the derivative of a decreasing input signal Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function ratelimiter Interfacing function SCImodulesscicosblocksmacrosMiscRATELIMITERsci Computational function SCImodulesscicosblockssrccratelimiterc Type 4 Authors Ramine Nikoukhah INRIA palettes 2436 Nome SATURATION Saturation Block Screenshot Contents Saturation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description The Saturation block imposes upper and lower bounds on a signal When the input signal is within the range specified by the Lower limit and Upper limit parameters the input signal passes through unchanged When the input signal is outside these bounds the signal is clipped to the upper or lower bound When the Lower limit and Upper limit parameters are set to the same value the block outputs that value Dialog box Upper limit palettes 2437 Specify the upper bound on the input signal When the input signal to the Saturation block is above this value the output of the block is clipped to this value Properties Type vec of size 1 Lower limit Specify the lower bound on the input signal When the input signal to the Saturation block is below this value the output of the block is clipped to this value Properties Type vec of size 1 zero crossing Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function satur Interfacing function SCImodulesscicosblocksmacrosNonLinearSATURATIONsci Computational function SCImodulesscicosblockssrccsaturc Type 4 Authors Ramine Nikoukhah INRIA palettes 2438 6 Discrete time systems palette palettes 2439 Nome Discretepal Discrete time systems palette Block Screenshot Module xcos Description The Discrete time systems palette contains blocks for medeling discrete time systems Blocks DELAYf Discrete time delay DELAYVf Variable delay DLR Discrete transfer function DLRADAPTf Discrete ZeroPole function DLSS Discrete statespace system DOLLARf Delay operator REGISTER Shift Register SAMPHOLDm Sample and hold TCLSS Continuous linear system with jump palettes 2440 Nome DELAYVf Variable delay Block Screenshot Contents Variable delay Palette Description Dialog box Default properties Interfacing function Computational function Palette Discrete time systems palette Description Add here a paragraph of the function description Dialog box Number of inputs Set the vector size of the first regular input and the vector size of the regular output port Properties Type vec of size 1 palettes 2441 Register initial condition Set the length and the initial conditions of the register Properties Type vec of size 1 Max delay It defines the largest value the time delay input can haveThe value cannot be negative Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 2 continuoustime state no discretetime state yes object discretetime state no name of computational function delayv Interfacing function SCImodulesscicosblocksmacrosLinearDELAYVfsci Computational function SCImodulesscicosblockssrcfortrandelayvf Type 1 palettes 2442 Nome DELAYf Discrete time delay Block Screenshot Contents Discrete time delay Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Palette Discrete time systems palette Description This compiled superblock implements a discretized delay It is build with a shift register and a clock The value of the delay is given by the discretization time step multiplied by the number1 of state of the register Dialog box Discretization time step Set the time period of the integrated clock palettes 2443 Properties Type vec of size 1 Register initial state Set the length and the initial conditions of the register Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosLinearDELAYfsci Compiled Super Block content palettes 2444 Nome DLR Discrete transfer function Block Screenshot Contents Discrete transfer function Palette Description Dialog box Default properties Interfacing function Computational function Palette Discrete time systems palette Description This block realizes a SISO linear system represented by its rational transfer function in the symbolic variable z The rational function must be proper Dialog box Numerator z This parameter sets the numerator of the transfer function This must be a polynomial inz Properties Type pol of size 1 Denominator z palettes 2445 This parameter sets the denominator of the transfer function This must be a polynomial inz Properties Type pol of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function dsslti4 Interfacing function SCImodulesscicosblocksmacrosLinearDLRsci Computational function SCImodulesscicosblockssrccdsslti4c Type 4 palettes 2446 Nome DLRADAPTf Discrete ZeroPole Block Screenshot Contents Discrete ZeroPole Palette Description Dialog box Default properties Interfacing function Computational function Palette Discrete time systems palette Description This block models system represented by zeros and poles of discrete transfer function Dialog box Vector of p mesh points The parameter description 1 palettes 2447 Properties Type vec of size 1 Numerator roots one line for each mesh The parameter description 2 Properties Type mat of size 11 Denominator roots one line for each mesh The parameter description 3 Properties Type mat of size size11 Vector of gain at mesh points The parameter description 4 Properties Type vec of size size1 past inputs Num degree values The parameter description 5 Properties Type vec of size size22 past outputs Den degree values The parameter description 6 Properties Type vec of size size32 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no palettes 2448 name of computational function dlradp Interfacing function SCImodulesscicosblocksmacrosNonLinearDLRADAPTfsci Computational function SCImodulesscicosblockssrcfortrandlradpf Type 0 palettes 2449 Nome DLSS Discrete statespace system Block Screenshot Contents Discrete statespace system Palette Description Dialog box Default properties Interfacing function Computational function Palette Discrete time systems palette Description This block realizes a discretetime linear statespace system The system is defined by the matrices and the initial state The dimensions must be compatible At the arrival of an input event on the unique input event port the state is updated Dialog box matrix palettes 2450 A square matrix Properties Type mat of size 11 B matrix The matrix if system has no input Properties Type mat of size size121 C matrix The matrix if system has no output Properties Type mat of size 1size12 D matrix The matrix if system has no D term Properties Type mat of size 11 Initial state A vectorscalar initial state of the system Properties Type vec of size size12 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function dsslti4 Interfacing function SCImodulesscicosblocksmacrosLinearDLSSsci palettes 2451 Computational function SCImodulesscicosblockssrccdsslti4c Type 4 palettes 2452 Nome DOLLARf Delay operator Block Screenshot Contents Delay operator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Discrete time systems palette Description The Unit Delay block delays its input by the specified sample period This block is equivalent to the z1 discretetime operator The block accepts one input and generates one output which can be either both scalar or both vector If the input is a vector all elements of the vector are delayed by the same sample period Dialog box initial condition The output of the simulation for the first sampling period during which the output of the Unit Delay block is otherwise undefined Properties Type vec of size 1 palettes 2453 Inherit no0 yes1 When Inherit is yes the block inherit its event input Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function dollar Interfacing function SCImodulesscicosblocksmacrosLinearDOLLARfsci Computational function SCImodulesscicosblockssrcfortrandollarf Type 0 Authors Ramine Nikoukhah INRIA palettes 2454 Nome REGISTER Shift Register Block Screenshot Contents Shift Register Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Discrete time systems palette Description This block realizes a shift register At every input event the register is shifted one step Dialog box Register initial condition A column vector It contains the initial state of the register Properties Type vec of size 1 Datatype This block support all datatypes besides complex palettes 2455 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function delay4 Interfacing function SCImodulesscicosblocksmacrosLinearREGISTERsci Computational function SCImodulesscicosblockssrccdelay4i32c SCImodulesscicosblockssrccdelay4i16c SCImodulesscicosblockssrccdelay4i8c SCImodulesscicosblockssrccdelay4ui32c SCImodulesscicosblockssrccdelay4ui16c SCImodulesscicosblockssrccdelay4ui8c Authors Fady NASSIF INRIA 7 Electrical palette palettes 2456 Nome Electricalpal Electrical palette Block Screenshot Module xcos Description Electrical toolbox contains very basic electrical components such as voltage source diode capacitor etc Blocks Capacitor Electrical capacitor CCS Controllable Modelica current source ConstantVoltage Electrical DC voltage source CurrentSensor Electrical current sensor CVS Controllable Modelica voltage source Diode Electrical diode Ground Ground zero potential reference Gyrator Modelica Gyrator IdealTransformer Ideal Transformer palettes 2457 Inductor Electrical inductor NMOS Simple NMOS Transistor NPN NPN transistor OpAmp Ideal opamp noratornullator pair PMOS Simple PMOS Transistor PNP PNP transistor PotentialSensor Potential sensor Resistor Electrical resistor SineVoltage Sine voltage source Switch Nonideal electrical switch VariableResistor Electrical variable resistor VoltageSensor Electrical voltage sensor VsourceAC Electrical AC voltage source VVsourceAC Variable AC voltage source palettes 2458 Nome CCS Controllable Modelica current source Block Screenshot Contents Controllable Modelica current source Palette Description Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description This block is an ideal current source The current value is controlled through the explicit input of the block connected to standard Xcos blocks The voltage across the block is independent of the current value Default properties Inputs Modelica variable name Iin Explicit variable Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable File name of the model CCS palettes 2459 Interfacing function SCImodulesscicosblocksmacrosElectricalCCSsci Modelica model SCImodulesscicosblocksmacrosElectricalCCSmo See also CVS Controllable Modelica voltage source Authors Masoud Najafi INRIA palettes 2460 Nome CVS Controllable Modelica voltage source Block Screenshot Contents Controllable Modelica voltage source Palette Description Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description This block is an ideal voltage source The voltage value is controlled through the explicit input of the block connected to standard Xcos blocks The current passing through the block is independent of the voltage across the block terminals Default properties Inputs Modelica variable name vin Explicit variable Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable File name of the model CVS palettes 2461 Interfacing function SCImodulesscicosblocksmacrosElectricalCVSsci Modelica model SCImodulesscicosblocksmacrosElectricalCVSmo See also CCS Controllable Modelica current source Authors Masoud Najafi INRIA palettes 2462 Nome Capacitor Electrical capacitor Block Screenshot Contents Electrical capacitor Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description A capacitor is an electrical component that can store energy in electrical circuits The relationship between the voltage across a capacitor with capacitance and the current passing through it is given by the Capacitors can also be used to differentiate between highfrequency and lowfrequency signals and this makes them useful in electronic filters A capacitor has a high impedance when a signal is low frequency signals Dialog box palettes 2463 C F Capacitance Properties Type vec of size 1 Initial Voltage Initial Voltage Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name C Default value 001 Is a state variable no Modelica parameter name v Default value 0 Is a state variable yes File name of the model Capacitor Interfacing function SCImodulesscicosblocksmacrosElectricalCapacitorsci Modelica model SCImodulesscicosblocksmacrosElectricalCapacitormo palettes 2464 Nome ConstantVoltage Electrical DC voltage source Block Screenshot Contents Electrical DC voltage source Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component is a model for any device or system that produces a constant electromotive force between its port The output voltage of this DC voltage source is defined by the user The black port indicates the positive voltage The ohmic resistance of this DC voltage source is zero Dialog box V volt Output voltage Properties Type vec of size 1 Default properties Inputs palettes 2465 Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name V Default value 001 Is a state variable no File name of the model ConstantVoltage Interfacing function SCImodulesscicosblocksmacrosElectricalConstantVoltagesci Modelica model SCImodulesscicosblocksmacrosElectricalConstantVoltagemo palettes 2466 Nome CurrentSensor Electrical current sensor Block Screenshot Contents Electrical current sensor Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This block is inserted in series in an electrical circuit to measure the current passing through the com ponent The measure is given to the explicit part of the model via an explicit pout Conventionally current flowing into the black port is considered positive The ohmic resistance of this block is zero Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Modelica variable name i Explicit variable File name of the model CurrentSensor Interfacing function SCImodulesscicosblocksmacrosElectricalCurrentSensorsci Modelica model SCImodulesscicosblocksmacrosElectricalCurrentSensormo palettes 2467 Nome Diode Electrical diode Block Screenshot Contents Electrical diode Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component consists of a simple diode parallel with an ohmic resistance The current passing through this component is defined as a function of the voltage across the ports where and are the saturation current and the voltage equivalent of temperature respectively If the exponent reaches a certain limit the diode characteristic becomes linear to avoid overflow Dialog box palettes 2468 Saturation current A Saturation current Properties Type vec of size 1 Voltage equivalent to temperature Volt Voltage equivalent of temperature Properties Type vec of size 1 Max exponent for linear continuation Max exponent for linear continuation Properties Type vec of size 1 R ohm Parallel ohmic resistance Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name Ids Default value 0000001 Is a state variable no Modelica parameter name Vt Default value 004 Is a state variable no Modelica parameter name Maxexp Default value 15 Is a state variable no Modelica parameter name R Default value 1000E08 palettes 2469 Is a state variable no File name of the model Diode Interfacing function SCImodulesscicosblocksmacrosElectricalDiodesci Modelica model SCImodulesscicosblocksmacrosElectricalDiodemo palettes 2470 Nome Ground Ground zero potential reference Block Screenshot Contents Ground zero potential reference Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description The Ground element is a single port component providing a reference voltage in electrical circuits The potential at the ground node is zero Every electrical circuit has to contain at least one ground element Default properties Inputs Modelica variable name p Implicit variable File name of the model Ground Interfacing function SCImodulesscicosblocksmacrosElectricalGroundsci Modelica model SCImodulesscicosblocksmacrosElectricalGroundmo palettes 2471 Nome Gyrator Modelica Gyrator Block Screenshot Contents Modelica Gyrator Palette Description Dialog box Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description A gyrator is a twoport element defined by the following equations i1 G2 v2 i2 G1 v1 where the constants G1 G2 are called the gyration conductance Dialog box G1 Gyration conductance i2v1 palettes 2472 Properties Type vec of size 1 G2 Gyration conductance i1v2 Properties Type vec of size 1 Default properties Inputs Modelica variable name p1 Implicit variable Modelica variable name n1 Implicit variable Modelica variable name p2 Implicit variable Modelica variable name n2 Implicit variable Parameters Modelica parameter name G1 Default value 1 Is a state variable no Modelica parameter name G2 Default value 1 Is a state variable no File name of the model Gyrator Interfacing function SCImodulesscicosblocksmacrosElectricalGyratorsci Modelica model SCImodulesscicosblocksmacrosElectricalGyratormo Authors Masoud Najafi INRIA palettes 2473 Nome IdealTransformer Ideal Transformer Block Screenshot Contents Ideal Transformer Palette Description Dialog box Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description The ideal transformer is an ideal twoport resistive circuit element which is characterized by the fol lowing two equations v1 n v2 i2 n i1 where n is a real number called the turns ratio Dialog box N Turns ratio N1N2 Properties Type vec of size 1 palettes 2474 Default properties Inputs Modelica variable name p1 Implicit variable Modelica variable name n1 Implicit variable Modelica variable name p2 Implicit variable Modelica variable name n2 Implicit variable Parameters Modelica parameter name N Default value 1 Is a state variable no File name of the model IdealTransformer Interfacing function SCImodulesscicosblocksmacrosElectricalIdealTransformersci Modelica model SCImodulesscicosblocksmacrosElectricalIdealTransformermo Authors Masoud Najafi INRIA palettes 2475 Nome Inductor Electrical inductor Block Screenshot Contents Electrical inductor Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description Inductor is an electrical component that can store energy in electrical circuits The relationship between the voltage across the ports of an inductor of inductance and the current passing through it is given by Inductors can also be used to differentiate between highfrequency and lowfrequency signals and this makes them useful in electronic filters An inductor shows a high impedance for high frequency signals Dialog box palettes 2476 L H Inductance Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name L Default value 000001 Is a state variable no File name of the model Inductor Interfacing function SCImodulesscicosblocksmacrosElectricalInductorsci Modelica model SCImodulesscicosblocksmacrosElectricalInductormo palettes 2477 Nome NMOS Simple NMOS Transistor Block Screenshot Contents Simple NMOS Transistor Palette Description Dialog box Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description Description The NMos model is a simple model of a nchannel metaloxide semiconductor FET It differs slightly from the device used in the SPICE simulator For more details please care for H Spiro The model does not consider capacitances A small fixed drainsource resistance is included to avoid numerical difficulties W m L m Beta 1 V² Vt V K2 K5 DW m DLm 12e6 4e6 062 45 24 61 12e6 9e6 depletion 60e6 3e6 048 1 08 68 12e6 9e6 enhance ment 12e6 4e6 0625 8 21 78 12e6 9e6 zero 50e6 8e6 0299 24 1144 7311 54e6 4e6 20e6 6e6 041 8 1144 7311 25e6 15e6 30e6 9e6 025 4 861 878 34e6 174e6 30e6 5e6 031 6 15 72 0 39e6 palettes 2478 50e6 6e6 0414 38 34 8 16e6 2e6 depletion 50e6 5e6 03 37 23 86 16e6 2e6 enhance ment 50e6 6e6 038 9 23 707 16e6 2e6 zero 20e6 4e6 06776 5409 065 71 8e6 2e6 20e6 4e6 06505 6209 065 71 8e6 2e6 20e6 4e6 05365 6909 03 8 3e6 2e6 20e6 4e6 05365 4909 03 8 3e6 2e6 12e6 4e6 023 45 29 6 0 0 depletion 60e6 3e6 022 1 11 65 0 0 enhance ment 12e6 4e6 038 8 33 6 0 0 zero 20e6 6e6 022 8 1 66 0 0 Dialog box Width m W Properties Type vec of size 1 Length m L Properties Type vec of size 1 Transconductance parameter AVV Beta palettes 2479 Properties Type vec of size 1 Zero bias threshold voltage V Vt Properties Type vec of size 1 Bulk threshold parameter K2 Properties Type vec of size 1 Reduction of pinchoff region K5 Properties Type vec of size 1 Narrowing of channel m dW Properties Type vec of size 1 Shortening of channel m dL Properties Type vec of size 1 DrainSourceResistance Ohm RDS Properties Type vec of size 1 Default properties Inputs Modelica variable name G Implicit variable Outputs Modelica variable name D Implicit variable Modelica variable name B Implicit variable Modelica variable name S Implicit variable Parameters Modelica parameter name W palettes 2480 Default value 000002 Is a state variable no Modelica parameter name L Default value 0000006 Is a state variable no Modelica parameter name Beta Default value 0000041 Is a state variable no Modelica parameter name Vt Default value 08 Is a state variable no Modelica parameter name K2 Default value 1144 Is a state variable no Modelica parameter name K5 Default value 07311 Is a state variable no Modelica parameter name dW Default value 00000025 Is a state variable no Modelica parameter name dL Default value 00000015 Is a state variable no Modelica parameter name RDS Default value 10000000 Is a state variable no File name of the model NMOS Interfacing function SCImodulesscicosblocksmacrosElectricalNMOSsci Modelica model SCImodulesscicosblocksmacrosElectricalNMOSmo palettes 2481 See also PMOS Simple PMOS Transistor Authors wwwmodelicaorg palettes 2482 Nome NPN NPN transistor Block Screenshot Contents NPN transistor Palette Description Dialog box Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description This model is a simple model of a bipolar NPN junction transistor according to EbersMoll palettes 2483 Dialog box Parameter Default value Description Bf 50 Forward beta Br 01 Reverse beta Is 1e16 Transport saturation current A Vak 002 Early voltage inverse 1Volt 1V Tauf 012e9 Ideal forward transit time s Taur 5e9 Ideal reverse transit time s Ccs 1e12 Collectorsubstratground cap F Cje 04e12 Baseemitter zero bias depletion cap F Cjc 05e12 Basecoll zero bias depletion cap F palettes 2484 Phie 08 Baseemitter diffusion voltage V Me 04 Baseemitter gradation exponent Phic 08 Basecollector diffusion voltage V Mc 0333 Basecollector gradation expo nent Gbc 1e15 Basecollector conductance S Gbe 1e15 Baseemitter conductance S Vt 002585 Voltage equivalent of tempera ture V EMin 100 if x EMin the expx function is linearized EMax 40 if x EMax the expx function is linearized Default properties Inputs Modelica variable name B Implicit variable Outputs Modelica variable name C Implicit variable Modelica variable name E Implicit variable Parameters Modelica parameter name Bf Default value 50 Is a state variable no Modelica parameter name Br Default value 01 Is a state variable no Modelica parameter name Is Default value 0 Is a state variable no Modelica parameter name Vak Default value 002 palettes 2485 Is a state variable no Modelica parameter name Tauf Default value 1200E10 Is a state variable no Modelica parameter name Taur Default value 5000E09 Is a state variable no Modelica parameter name Ccs Default value 1000E12 Is a state variable no Modelica parameter name Cje Default value 4000E13 Is a state variable no Modelica parameter name Cjc Default value 5000E13 Is a state variable no Modelica parameter name Phie Default value 08 Is a state variable no Modelica parameter name Me Default value 04 Is a state variable no Modelica parameter name Phic Default value 08 Is a state variable no Modelica parameter name Mc Default value 0333 Is a state variable no Modelica parameter name Gbc Default value 1000E15 Is a state variable no palettes 2486 Modelica parameter name Gbe Default value 1000E15 Is a state variable no Modelica parameter name Vt Default value 002585 Is a state variable no Modelica parameter name EMinMax Default value 40 Is a state variable no File name of the model NPN Interfacing function SCImodulesscicosblocksmacrosElectricalNPNsci Modelica model SCImodulesscicosblocksmacrosElectricalNPNmo See also PNP PNP transistor Authors wwwmodelicaorg palettes 2487 Nome OpAmp Ideal opamp noratornullator pair Block Screenshot Contents Ideal opamp noratornullator pair Palette Description Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description The ideal OpAmp is a twoport The left port is fixed to v10 and i10 nullator At the right port both any voltage v2 and any current i2 are possible norator Default properties Inputs Modelica variable name inp Implicit variable Modelica variable name inn Implicit variable Outputs Modelica variable name out Implicit variable File name of the model OpAmp Interfacing function SCImodulesscicosblocksmacrosElectricalOpAmpsci palettes 2488 Modelica model SCImodulesscicosblocksmacrosElectricalOpAmpmo Authors wwwmodelicaorg palettes 2489 Nome PMOS Simple PMOS Transistor Block Screenshot Contents Simple PMOS Transistor Palette Description Dialog box Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description The PMOS model is a simple model of a pchannel metaloxide semiconductor FET It differs slightly from the device used in the SPICE simulator For more details please care for H Spiro The model does not consider capacitances A small fixed drainsource resistance is included to avoid numerical difficulties Some typical parameter sets are W m Lm Beta 1V² Vt V K2 K5 DW m DL m 50e6 8e6 0085 15 41 839 38e6 40e6 20e6 6e6 0105 10 41 839 25e6 21e6 30e6 5e6 0059 3 98 101 0 39e6 30e6 5e6 0152 69 104 11 8e6 4e6 30e6 5e6 0163 69 104 11 8e6 4e6 30e6 5e6 0182 69 086 106 1e6 6e6 20e6 6e6 0074 1 4 59 0 0 palettes 2490 Dialog box Width m W Properties Type vec of size 1 Length m L Properties Type vec of size 1 Transconductance parameter AVV Beta Properties Type vec of size 1 Zero bias threshold voltage V Vt Properties Type vec of size 1 Bulk threshold parameter K2 Properties Type vec of size 1 Reduction of pinchoff region K5 Properties Type vec of size 1 palettes 2491 Narrowing of channel m dW Properties Type vec of size 1 Shortening of channel m dL Properties Type vec of size 1 DrainSourceResistance Ohm RDS Properties Type vec of size 1 Default properties Inputs Modelica variable name G Implicit variable Outputs Modelica variable name D Implicit variable Modelica variable name B Implicit variable Modelica variable name S Implicit variable Parameters Modelica parameter name W Default value 000005 Is a state variable no Modelica parameter name L Default value 0000006 Is a state variable no Modelica parameter name Beta Default value 00000105 Is a state variable no Modelica parameter name Vt Default value 1 palettes 2492 Is a state variable no Modelica parameter name K2 Default value 041 Is a state variable no Modelica parameter name K5 Default value 0839 Is a state variable no Modelica parameter name dW Default value 00000025 Is a state variable no Modelica parameter name dL Default value 00000021 Is a state variable no Modelica parameter name RDS Default value 10000000 Is a state variable no File name of the model PMOS Interfacing function SCImodulesscicosblocksmacrosElectricalPMOSsci Modelica model SCImodulesscicosblocksmacrosElectricalPMOSmo See also NMOS Simple NMOS Transistor Authors wwwmodelicaorg palettes 2493 Nome PNP PNP transistor Block Screenshot Contents PNP transistor Palette Description Dialog box Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description This model is a simple model of a bipolar PNP junction transistor according to EbersMoll palettes 2494 Dialog box Parameter Default value Description Bf 50 Forward beta Br 01 Reverse beta Is 1e16 Transport saturation current A Vak 002 Early voltage inverse 1Volt 1V Tauf 012e9 Ideal forward transit time s Taur 5e9 Ideal reverse transit time s Ccs 1e12 Collectorsubstratground cap F Cje 04e12 Baseemitter zero bias depletion cap F Cjc 05e12 Basecoll zero bias depletion cap F Phie 08 Baseemitter diffusion voltage V Me 04 Baseemitter gradation exponent palettes 2495 Phic 08 Basecollector diffusion voltage V Mc 0333 Basecollector gradation expo nent Gbc 1e15 Basecollector conductance S Gbe 1e15 Baseemitter conductance S Vt 002585 Voltage equivalent of tempera ture V EMin 100 if x EMin the expx function is linearized EMax 40 if x EMax the expx function is linearized Default properties Inputs Modelica variable name B Implicit variable Outputs Modelica variable name C Implicit variable Modelica variable name E Implicit variable Parameters Modelica parameter name Bf Default value 50 Is a state variable no Modelica parameter name Br Default value 01 Is a state variable no Modelica parameter name Is Default value 0 Is a state variable no Modelica parameter name Vak Default value 002 Is a state variable no Modelica parameter name Tauf palettes 2496 Default value 1200E10 Is a state variable no Modelica parameter name Taur Default value 5000E09 Is a state variable no Modelica parameter name Ccs Default value 1000E12 Is a state variable no Modelica parameter name Cje Default value 4000E13 Is a state variable no Modelica parameter name Cjc Default value 5000E13 Is a state variable no Modelica parameter name Phie Default value 08 Is a state variable no Modelica parameter name Me Default value 04 Is a state variable no Modelica parameter name Phic Default value 08 Is a state variable no Modelica parameter name Mc Default value 0333 Is a state variable no Modelica parameter name Gbc Default value 1000E15 Is a state variable no Modelica parameter name Gbe Default value 1000E15 palettes 2497 Is a state variable no Modelica parameter name Vt Default value 002585 Is a state variable no Modelica parameter name EMinMax Default value 40 Is a state variable no File name of the model PNP Interfacing function SCImodulesscicosblocksmacrosElectricalPNPsci Modelica model SCImodulesscicosblocksmacrosElectricalPNPmo See also NPN NPN transistor Authors wwwmodelicaorg palettes 2498 Nome PotentialSensor Potential sensor Block Screenshot Contents Potential sensor Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This block is used to measure the voltage with respect to the reference voltage Ground block in an electrical circuit The voltage is given to the explicit part of the model via an explicit output port Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name v Explicit variable File name of the model PotentialSensor Interfacing function SCImodulesscicosblocksmacrosElectricalPotentialSensorsci Modelica model SCImodulesscicosblocksmacrosElectricalPotentialSensormo palettes 2499 Nome Resistor Electrical resistor Block Screenshot Contents Electrical resistor Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description A resistor is a twoport electrical component that resists an electric current by producing a voltage drop between its terminals according to the Ohms law The electrical resistance is equal to the voltage drop across the resistor divided by the current through the resistor Dialog box R ohm palettes 2500 Resistance Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name R Default value 001 Is a state variable no File name of the model Resistor Interfacing function SCImodulesscicosblocksmacrosElectricalResistorsci Modelica model SCImodulesscicosblocksmacrosElectricalResistormo palettes 2501 Nome SineVoltage Sine voltage source Block Screenshot Contents Sine voltage source Palette Description Dialog box Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description This Modelica block a general sine voltage source The internal ohmic resistance is zero Dialog box palettes 2502 Amplitude Volt Sine voltage amplitude Properties Type vec of size 1 phase rad phase shift of the sine voltage Properties Type vec of size 1 Frequency Hz Sine voltage frequency Properties Type vec of size 1 Voltageoffset V Offset Voltage of the sine voltage Properties Type vec of size 1 Timeoffset s Start time During the start time the signal value is equal to the voltage offset Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name V Default value 1 Is a state variable no Modelica parameter name phase Default value 0 Is a state variable no Modelica parameter name freqHz Default value 1 Is a state variable no palettes 2503 Modelica parameter name offset Default value 0 Is a state variable no Modelica parameter name startTime Default value 0 Is a state variable no File name of the model SineVoltage Interfacing function SCImodulesscicosblocksmacrosElectricalSineVoltagesci Modelica model SCImodulesscicosblocksmacrosElectricalSineVoltagemo Authors wwwmodelicaorg palettes 2504 Nome Switch Nonideal electrical switch Block Screenshot Contents Nonideal electrical switch Palette Description Dialog box Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description This is a nonideal twopole switch If the explicit input become positive two pins are connected via a resistor of resistance RON Otherwise two pins are connected via ROFF resistance Note that using this block may result in a stiff model so try to choose proper error tolerances Dialog box Resistance in On state Ohm Switch resistance when the Switch is closed Properties Type vec of size 1 palettes 2505 Resistance in Off state Ohm Switch resistance when the switch is open Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Modelica variable name inp Explicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name Ron Default value 001 Is a state variable no Modelica parameter name Roff Default value 100000 Is a state variable no File name of the model Switch Interfacing function SCImodulesscicosblocksmacrosElectricalSwitchsci Modelica model SCImodulesscicosblocksmacrosElectricalSwitchmo Authors Masoud Najafi INRIA palettes 2506 Nome VVsourceAC Variable AC voltage source Block Screenshot Contents Variable AC voltage source Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description The variable voltage source block is a model for a controlled AC voltage source This component provides a sinusoid voltage across its ports The amplitude of the output voltage is governed by the explicit input and the frequency is defined by the user The ohmic resistance of the block is zero Dialog box Frequency Hz Frequency of the output sinosoid voltage Properties Type vec of size 1 Default properties Inputs Modelica variable name p palettes 2507 Implicit variable Modelica variable name VA Explicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name f Default value 50 Is a state variable no File name of the model VVsourceAC Interfacing function SCImodulesscicosblocksmacrosElectricalVVsourceACsci Modelica model SCImodulesscicosblocksmacrosElectricalVVsourceACmo palettes 2508 Nome VariableResistor Electrical variable resistor Block Screenshot Contents Electrical variable resistor Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component represents a variable ohmic resistor The resistance is controlled via an explicit input port Default properties Inputs Modelica variable name p Implicit variable Modelica variable name R Explicit variable Outputs Modelica variable name n Implicit variable File name of the model VariableResistor palettes 2509 Interfacing function SCImodulesscicosblocksmacrosElectricalVariableResistorsci Modelica model SCImodulesscicosblocksmacrosElectricalVariableResistormo palettes 2510 Nome VoltageSensor Electrical voltage sensor Block Screenshot Contents Electrical voltage sensor Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component is used to measure the voltage difference between two nodes in an electrical circuit The output signal is the difference between the voltages of the black port and the white port The ohmic conductance of this block is zero Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Modelica variable name v Explicit variable File name of the model VoltageSensor palettes 2511 Interfacing function SCImodulesscicosblocksmacrosElectricalVoltageSensorsci Modelica model SCImodulesscicosblocksmacrosElectricalVoltageSensormo palettes 2512 Nome VsourceAC Electrical AC voltage source Block Screenshot Contents Electrical AC voltage source Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component is an AC voltage source with sinusoid output voltage The amplitude and the fre quency of the output voltage is set by the user The ohmic resistance of this block is zero Dialog box Amplitude Volt Amplitude of the output sinusoid voltage Properties Type vec of size 1 Frequency Hz Frequency of the output sinusoid voltage palettes 2513 Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name VA Default value 220 Is a state variable no Modelica parameter name f Default value 50 Is a state variable no File name of the model VsourceAC Interfacing function SCImodulesscicosblocksmacrosElectricalVsourceACsci Modelica model SCImodulesscicosblocksmacrosElectricalVsourceACmo 8 Event handling palette palettes 2514 Nome Eventspal Event handling palette Block Screenshot Module xcos Description The Event handling palette is used to handle events in the diagram It contains several activation clocks synchronous blocks and blocks to gather events in a single link Blocks ANDBLK Activation and ANDLOGf Logical and CEVENTSCOPE Activation scope CLKFROM Receives data from a corresponding CLKGOTO CLKGOTO Pass block input to CLKFROM block palettes 2515 CLKGotoTagVisibility Define Scope of CLKGOTO tag visibility CLKOUTVf Output activation port CLKSOMVf Activation union CLOCKc Activation clock EDGETRIGGER EDGETRIGGER block ENDBLK END block ENDc ENDc block ESELECTf Synchronous block EventSelect EVTDLYc Event delay EVTGENf Event generator EVTVARDLY Event variable delay ExtractActivation ExtractActivation block HALTf Stop simulation IFTHELf Synchronous block IfThenElse Mfreq Multiple Frequencies MCLOCKf Clock Frequency division MFCLCKf Clock Multiple Frequencies REGISTER Shift Register SampleCLK Sample Time Clock freqdiv Frequency division palettes 2516 Nome ANDBLK Activation and Block Screenshot Contents Activation and Palette Description Default properties Interfacing function Compiled Super Block content Authors Palette Event handling palette Description The Bus Creator block combines a set of signals ie a group of signals represented by a single line in a block diagram It allows you to reduce the number of lines required to route signals from one part of a diagram to another This makes your easier to understand Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 2 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper palettes 2517 Interfacing function SCImodulesscicosblocksmacrosEventsANDBLKsci Compiled Super Block content Authors Ramine Nikoukhah INRIA palettes 2518 Nome ANDLOGf Logical and Block Screenshot Contents Logical and Palette Description Default properties Interfacing function Authors Palette Event handling palette Description This block with two event inputs and a regular output outputs 1 or 1 on its regular output depending on input events 1 When events are synchronously present on both event input ports 1 When only one event is present Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 2 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2519 object discretetime state no name of computational function andlog Interfacing function SCImodulesscicosblocksmacrosEventsANDLOGfsci Authors Ramine Nikoukhah INRIA palettes 2520 Nome CEVENTSCOPE Activation scope Block Screenshot Contents Activation scope Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Event handling palette Description This block realizes the visualization of the input event signals Dialog box Number of event inputs palettes 2521 an integer giving the number of event input ports colors a vector of integers The ith element is the color number or dash type used to draw the evolution of the ith input port signal Seexset for color dash type definitions Properties Type vec of size 1 colors c an integer It is the color number or dash type used to draw the evolution of the input port signal Seeplot2d for color dash type definitions Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Refresh period Maximum value on the Xaxis time The plot is redrawn when time reaches a multiple of this value Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2522 object discretetime state no name of computational function cevscpe Interfacing function SCImodulesscicosblocksmacrosSinksCEVENTSCOPEsci Computational function SCImodulesscicosblockssrcccevscpec Type 4 Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2523 Nome CLKFROM Receives data from a corresponding CLKGOTO Block Screenshot Contents Receives data from a corresponding CLKGOTO Palette Description Dialog box Default properties Interfacing function See also Authors Palette Event handling palette Description This block is used to connect events ports For more information on how it works please refer to the documentation of the FROM block by clicking on the link in the See also field Dialog box Tag The tag of the CLKGOTO block passing the signal to this CLKFROM block Properties Type str of size 1 Default properties always active no palettes 2524 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function clkfrom Interfacing function SCImodulesscicosblocksmacrosBranchingCLKFROMsci See also FROM FROM Receives data from a corresponding GOTO Authors Fady NASSIF INRIA palettes 2525 Nome CLKGOTO Pass block input to CLKFROM block Block Screenshot Contents Pass block input to CLKFROM block Palette Description Dialog box Default properties Interfacing function See also Authors Palette Event handling palette Description This block is used to connect events ports For more information on how it works please refer to the documentation of the GOTO block by clicking on the link in the See also field Dialog box Tag This parameter identifies the Goto block whose scope is defined in this block Properties Type str of size 1 Tag Visibility 1Local 2Scoped 3Global palettes 2526 This parameter idetifies the visibility of the block It can be local1 scoped2 or global3 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function clkgoto Interfacing function SCImodulesscicosblocksmacrosBranchingCLKGOTOsci See also GOTO GOTO Pass block input to From block Authors Fady NASSIF INRIA palettes 2527 Nome CLKGotoTagVisibility Define Scope of CLKGOTO tag visibility Block Screenshot Contents Define Scope of CLKGOTO tag visibility Palette Description Dialog box Default properties Interfacing function See also Authors Palette Event handling palette Description This block is used in the event case For more information on how it works please refer to the docu mentation of the GotoTagVisibility block by clicking on the link in the See also field Dialog box GotoTag The Goto block tag whose visibility is defined by the location of this block Properties Type str of size 1 Default properties always active no palettes 2528 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function clkgototagvisibility Interfacing function SCImodulesscicosblocksmacrosBranchingCLKGotoTagVisibilitysci See also GotoTagVisibility Define Scope of GOTO tag visibility Authors Fady NASSIF INRIA palettes 2529 Nome CLKOUTVf Output activation port Block Screenshot Contents Output activation port Palette Description Dialog box Default properties Interfacing function Authors Palette Event handling palette Description This block must only be used inside Xcos Super Blocks to represent an event output port In a Super Block the event output ports must be numbered from 1 to the number of event output ports Dialog box Port number an integer defining the port number Properties Type vec of size 1 Default properties always active no directfeedthrough no palettes 2530 zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function output Interfacing function SCImodulesscicosblocksmacrosSinksCLKOUTVfsci Authors Ramine Nikoukhah INRIA palettes 2531 Nome CLKSOMVf Activation union Block Screenshot Contents Activation union Palette Description Default properties Interfacing function Computational function Authors Palette Event handling palette Description This block is an event addition block with up to three inputs The output reproduces the events on all the input ports Strictly speaking CLKSOMV is not a Xcos block because it is discarded at the compilation phase The inputs and output of CLKSOMV are synchronized Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 3 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function sum palettes 2532 Interfacing function SCImodulesscicosblocksmacrosEventsCLKSOMVfsci Computational function SCImodulesscicosblockssrccsumc Type 0 Authors Ramine Nikoukhah INRIA palettes 2533 Nome EDGETRIGGER EDGETRIGGER block Block Screenshot Contents EDGETRIGGER block Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Palette Event handling palette Description This block generates an event on rising falling or both edges of the input signal depending on block parameter A rising edge is a change in value from strictly negative to positive or zero or a change in value from zero to strictly positive A falling edge is the opposite Note that this block only generates an event if the input jumps due to an event The generated event is synchronous with the event causing the jump This block does not detect continuoustime zerocrossings Dialog box rising 1 falling 1 both 0 Properties Type vec of size 1 Default properties always active no palettes 2534 directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosMiscEDGETRIGGERsci Compiled Super Block content palettes 2535 Nome ESELECTf Synchronous block EventSelect Block Screenshot Contents Synchronous block EventSelect Palette Description Dialog box Default properties Interfacing function Authors Palette Event handling palette Description Special block similar to IfThenElse Input and output are synchronized The incoming event is di rected to one of the output event ports depending on the value of the regular input For example when the input value is between 0 and 1 the control input is redirected to the first command output when the input value is between 1 and 2 the control input is redirected to the second command output et cætera Dialog box number of output event ports palettes 2536 A scalar Number of output event ports Properties Type vec of size 1 Inherit If no then it inherits the event from event input port elseif yes then event is activated by regular input port Properties Type vec of size 1 zerocrossing Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 2 continuoustime state no discretetime state no object discretetime state no name of computational function eselect Interfacing function SCImodulesscicosblocksmacrosBranchingESELECTfsci Authors Ramine Nikoukhah INRIA palettes 2537 Nome EVTDLYc Event delay Block Screenshot Contents Event delay Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Event handling palette Description One event is generated Delay after an event enters the unique input event port Block may also generate an initial output event The event date of that block is computed by the formula where the date of initial output event the delay and and internal integer discrete counter palettes 2538 Dialog box Delay scalar Time delay between input and output event Properties Type vec of size 1 Date of initial output event scalar IfAutoexec0 block initially generates an output event at dateAutoexec Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function evtdly4 Interfacing function SCImodulesscicosblocksmacrosEventsEVTDLYcsci palettes 2539 Computational function SCImodulesscicosblockssrccevtdly4c Type 4 See also CLOCKc Activation clock Authors Alan Layec INRIA palettes 2540 Nome EVTGENf Event generator Block Screenshot Contents Event generator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Event handling palette Description One event is generated on the unique output event port if Event time is larger than equal to zero if not no event is generated Dialog box Event Time scalar date of the initial event Properties Type vec of size 1 Default properties always active no palettes 2541 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function trash Interfacing function SCImodulesscicosblocksmacrosEventsEVTGENfsci Computational function SCImodulesscicosblockssrcfortrantrashf Type 0 Authors Ramine Nikoukhah INRIA palettes 2542 Nome EVTVARDLY Event variable delay Block Screenshot Contents Event variable delay Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Event handling palette Description One event is generated Delay after an event enters the unique input event port The value of the delay is read from the regular input port Block may also generate an initial output event Dialog box Initial event firing time One event is generated on the unique output event port if Event time is larger than equal to zero if not no event is generated Properties Type vec of size 1 Default properties always active no palettes 2543 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function evtvardly Interfacing function SCImodulesscicosblocksmacrosEventsEVTVARDLYsci Computational function SCImodulesscicosblockssrccevtvardlyc Type 4 Authors Ramine Nikoukhah INRIA palettes 2544 Nome ExtractActivation ExtractActivation block Block Screenshot Contents ExtractActivation block Palette Default properties Interfacing function Compiled Super Block content Palette Event handling palette Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosMiscExtractActivationsci palettes 2545 Compiled Super Block content palettes 2546 Nome HALTf Halt Block Screenshot Contents Halt Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Event handling palette Description This block has a unique input event port Upon the arrival of an event the simulation is stopped and the main Xcos window is activated Simulation can be restarted or continued Run button Dialog box State on halt A scalar value to be placed in the state of the block For debugging purposes this allows to distinguish between different halts Properties Type vec of size 1 Default properties always active no palettes 2547 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function hltblk Interfacing function SCImodulesscicosblocksmacrosEventsHALTfsci Computational function SCImodulesscicosblockssrcfortranhltblkf Type 0 Authors Ramine Nikoukhah INRIA palettes 2548 Nome IFTHELf Synchronous block IfThenElse Block Screenshot Contents Synchronous block IfThenElse Palette Description Dialog box Default properties Interfacing function Authors Palette Event handling palette Description One event is generated on one of the output event ports when an input event arrives Depending on the sign of the regular input the event is generated on the first or second output This is a Synchro block input and output event are synchronized Dialog box Inherit If no then it inherits the event from event input port elseif yes then event is activated by regular input port Properties Type vec of size 1 zerocrossing palettes 2549 Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 2 continuoustime state no discretetime state no object discretetime state no name of computational function ifthel Interfacing function SCImodulesscicosblocksmacrosEventsIFTHELfsci Authors Ramine Nikoukhah INRIA palettes 2550 Nome MCLOCKf MCLOCKf title Block Screenshot Contents Multiple Frequencies fn Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Palette Event handling palette Description Add here a paragraph of the function description Dialog box basic period 1f The parameter description 1 Properties Type vec of size 1 multiply by n The parameter description 2 Properties Type vec of size 1 palettes 2551 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 2 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosEventsMCLOCKfsci Compiled Super Block content palettes 2552 Nome MFCLCKf MFCLCKf title Block Screenshot Contents Clock Frequency division Palette Description Dialog box Default properties Interfacing function Computational function Palette Event handling palette Description Add here a paragraph of the function description Dialog box basic period 1f The parameter description 1 Properties Type vec of size 1 multiply by n The parameter description 2 Properties Type vec of size 1 palettes 2553 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 2 continuoustime state no discretetime state yes object discretetime state no name of computational function mfclck Interfacing function SCImodulesscicosblocksmacrosEventsMFCLCKfsci Computational function SCImodulesscicosblockssrcfortranmfclckf Type 0 palettes 2554 Nome Mfreq Multiple Frequencies Block Screenshot Contents Multiple Frequencies Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Event handling palette Description This blocks generates events at specific sample time of the simulation time The sample time is given in the Sample Time field and the offset is given in the Offset field This block has one event input the number of event outputs depends on the number of different sample time For example if the vector of sample time is 1 1 2 and the vector of offset is 0 5 0 then the block has 7 outputs The first output is activated when the simulation time is equal to a multiple of the first sample time plus the first offset The second output is activated when the simulation time is equal to a multiple of the second sample time plus the second offset The third output is activated when we have both cases first case and second case The fourth output is activated when the simulation time is equal to a multiple of the third sample time plus the third offset The fifth output is activated when we have both cases first case and forth case The sixth output is activated when we have both cases second case and fourth case The seventh output is activated when we have both cases third case and forth case palettes 2555 etc So the number of outputs is equal to 2number of different time values Each of these time values is represented by a binary number associated to the outputs number in decimal Dialog box Sample time Vector of sample time values Properties Type vec of size 1 Offset Vector of offset values Must have the same size as the Sample time and each offset value must be less than its corresponding sample time Properties Type vec of size 1 Example Let us take the example where the sample time is equal to 1 1 2 and the offset is equal to 0 5 0 Consider tsimulation time When t0 the fifth output is activated 001 100 When t05 the second output is activated 010 When t1 the first output is activated 001 When t15 the second output is activated 010 When t2 we loop back to 0 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 3 continuoustime state no discretetime state no palettes 2556 object discretetime state no name of computational function mfrequ Interfacing function SCImodulesscicosblocksmacrosEventsMfreqsci Computational function SCImodulesscicosblockssrccmfrequc Type 4 See also MFCLCKf MFCLCKf title Authors Fady NASSIF INRIA palettes 2557 Nome freqdiv Frequency division Block Screenshot Contents Frequency division Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Authors Palette Event handling palette Description This block is a Super Block The input event is directed once every n times to output The input is driven by an event clock Dialog box Phase positive scalar Properties Type vec of size 1 Division factor palettes 2558 an integer greater than 1 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosEventsfreqdivsci Compiled Super Block content palettes 2559 Authors Ramine Nikoukhah INRIA 9 Implicit palette palettes 2560 Nome Implicitpal Implicit palette Block Screenshot Module xcos Description In the Implicit palette you can find blocks used to model implicit systems Blocks CONSTRAINTf Constraint DIFFf Sum palettes 2561 Nome CONSTRAINTf Constraint Block Screenshot Contents Constraint Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Implicit palette Description Defines implicit algebraic relations Dialog box Set number of constraints no of algebraic relations to be defined Properties Type vec of size 1 Default properties always active yes directfeedthrough no palettes 2562 zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function constraint Interfacing function SCImodulesscicosblocksmacrosMiscCONSTRAINTfsci Computational function SCImodulesscicosblockssrcfortranconstraintf Type 10001 Authors Ramine Nikoukhah INRIA palettes 2563 Nome DIFFf Derivative Block Screenshot Contents Derivative Palette Description Dialog box Default properties Interfacing function Computational function Palette Implicit palette Description This block computes the derivative of the input Dialog box Initial state The initial continuous state Properties Type vec of size 1 Initial Derivative The initial derivative state palettes 2564 Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function diffblk Interfacing function SCImodulesscicosblocksmacrosMiscDIFFfsci Computational function SCImodulesscicosblockssrcfortrandiffblkf Type 10001 10 Integer palette palettes 2565 Nome Integerpal Integer palette Block Screenshot Module xcos Description That palette is dedicated to handle integer numbers Various basic operators for the management of bit fields and for logic are implemented as well as common gates encountered in digital circuits Blocks BITCLEAR BITCLEAR Clear a Bit BITSET BITSET Set a Bit CONVERT CONVERT Data Type Conversion DFLIPFLOP D flipflop DLATCH D latch flipflop EXTRACTBITS EXTRACTBITS INTMUL INTMUL integer matrix multiplication JKFLIPFLOP JK flipflop LOGIC Combinational Logic SHIFT SHIFT Shift Bits SRFLIPFLOP SR flipflop palettes 2566 Nome BITCLEAR Clear a Bit Block Screenshot Contents Clear a Bit Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This blocks set the specified bit of the integer input to 0 The user can specify the bit in the fieldindex of bit Bit 0 is the least significant bit Dialog box Datatype3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 palettes 2567 index of bit 0 is least significant It indicate the index of the bit to clear When the type is int32 or uint32 the number must be positive and less than 32 When the type is int16 or uint16 the number must be positive and less than 16 When the type is int8 or uint8 the number must be positive and less than 8 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 3 regular outputs port 1 size 11 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function bitclear32 Interfacing function SCImodulesscicosblocksmacrosIntegerOpBITCLEARsci Computational function SCImodulesscicosblockssrccbitclear32c SCImodulesscicosblockssrccbitclear16c SCImodulesscicosblockssrccbitclear8c See also BITSET BITSET Set a Bit Authors Fady NASSIF INRIA palettes 2568 Nome BITSET Set a Bit Block Screenshot Contents Set a Bit Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This blocks set the specified bit of the integer input to 1 The user can specify the bit in the fieldindex of bit Bit 0 is the least significant bit Dialog box Datatype3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 palettes 2569 index of bit 0 is leat significant It indicate the index of the bit to clear When the type is int32 or uint32 the number must be positive and less than 32 When the type is int16 or uint16 the number must be positive and less than 16 When the type is int8 or uint8 the number must be positive and less than 8 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 3 regular outputs port 1 size 11 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function bitset32 Interfacing function SCImodulesscicosblocksmacrosIntegerOpBITSETsci Computational function SCImodulesscicosblockssrccbitset32c SCImodulesscicosblockssrccbitset16c SCImodulesscicosblockssrccbitset8c See also BITCLEAR BITCLEAR Clear a Bit Authors Fady NASSIF INRIA palettes 2570 Nome CONVERT Data Type Conversion Block Screenshot Contents CONVERT Data Type Conversion Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Integer palette Description This block converts an input signal of any data type to a specified data type The input can be real complex or integer When the output is an integer and when overflow occurs the block three different forms of results 1 A normal non saturated result 2 A saturated result 3 An error message warning the user about the overflow The user can select one of these three forms by setting the DO ON OVERFLOW field to 01 or 2 Dialog box palettes 2571 input type 1 double 3int32 4int16 5int8 It indicates the input data type it can be a double or an integer Properties Type vec of size 1 output type 1 double 3int32 4int16 5int8 It indicates the output data type it can be a double or an integer Properties Type vec of size 1 Do on Overflow0Nothing 1Saturate 2Error When this parameter is set to zero the result is similar to a normal multiplication of two integer matrix When it is set to 1 on overflow the block saturate the result When it is set to 2 on overflow an error message box appears Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function convert Interfacing function SCImodulesscicosblocksmacrosIntegerOpCONVERTsci Computational function SCImodulesscicosblockssrccconvertc Authors Fady NASSIF INRIA palettes 2572 Nome DFLIPFLOP D flipflop Block Screenshot Contents D flipflop Palette Description Default properties Interfacing function Compiled Super Block content See also Authors Palette Integer palette Description The DFLIPFLOP block outputs the input state when the enable is set and on the rising edge of the clock The input is D the enable is en and the clock is clk Q and Q are the outputs of this block This block is almostly used with digital number the input data type is int8 The truth table of this block is en D Q Q 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs palettes 2573 port 1 size 11 type 5 port 2 size 11 type 1 port 3 size 11 type 1 regular outputs port 1 size 11 type 5 port 2 size 11 type 5 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosIntegerOpDFLIPFLOPsci Compiled Super Block content See also DLATCH D latch flipflop SRFLIPFLOP SR flipflop JKFLIPFLOP JK flipflop palettes 2574 Authors Fady NASSIF INRIA palettes 2575 Nome DLATCH D latch flipflop Block Screenshot Contents D latch flipflop Palette Description Default properties Interfacing function Compiled Super Block content See also Authors Palette Integer palette Description This block outputs the input state when the input gate is high The input is D the enable is C Q and Q are the outputs of this block This block is almost used with digital number the input data type is int8 The truth table of this block is C D Q Q 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs palettes 2576 port 1 size 11 type 5 port 2 size 11 type 1 regular outputs port 1 size 11 type 5 port 2 size 11 type 5 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosIntegerOpDLATCHsci Compiled Super Block content See also DFLIPFLOP D flipflop SRFLIPFLOP SR flipflop JKFLIPFLOP JK flipflop Authors Fady NASSIF INRIA palettes 2577 Nome EXTRACTBITS EXTRACTBITS Block Screenshot Contents EXTRACTBITS Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This block outputs a contiguous selection of bits from the input integer numberThe Bits to extract defines the method by which the user select the output bits 1 When Upper Half is selected the block outputs the half of the input that contain the most significant bit In this case the third parameter number of bits or index of bit is ignored 2 When Lower Half is selected the block outputs the half of the input that contain the least significant bit In this case the third parameter number of bits or index of bit is ignored 3 When Range starting with most significant bit is selected the block outputs certain number of bits of the input that contain the most significant bit In this case the third parameter number of bits or index of bit defines the number of bits to extract 4 When Range ending with least significant bit is selected the block outputs certain number of bits of the input that contain the least significant bit In this case the third parameter number of bits or index of bit defines the number of bits to extract 5 When Range of bits is selected the block outputs a range of bits of the input In this case the third parameter number of bits or index of bit defines the range of bits to extract it must be a vector with the format startend The extracted value depends on the forth parameter Treat bit field as an integer When it is set to 0 the input scaling is used to determine the output scaling When it is set to 1 only the extracted bits forms the output number palettes 2578 Dialog box Datatype3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 Bits to extract1Upper Half 2Lower Half 3Range starting with most significant bit 4Ran ge ending with least significant bit 5Range of bits It indicates the mode used to extract bits from the input data Properties Type vec of size 1 number of bits or index of bit case range of bitsstartend0 is least significant bit When the Bits to extract field is set to 3 or 4 this parameter is used to determine the number of bits to extract and it must be a number When the Bits to extract field is set to 5 this parameter is used to determine range of bits to extract and it must have the startend form vector When the Bits to extract field is set to 1 or 2 this parameter is ignored Properties Type vec of size 1 Treat bit field as an integer0no 1yes It indicates the scaling mode to use on the output bits selection Properties Type vec of size 1 palettes 2579 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 3 regular outputs port 1 size 11 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function extractbit32UH0 Interfacing function SCImodulesscicosblocksmacrosIntegerOpEXTRACTBITSsci Computational function SCImodulesscicosblockssrccextractbit32UH0c SCImodulesscicosblockssrccextractbit32UH1c SCImodulesscicosblockssrccextractbitu32UH1c SCImodulesscicosblockssrccextractbit32LHc SCImodulesscicosblockssrccextractbit32MSB0c SCImodulesscicosblockssrccextractbit32MSB1c SCImodulesscicosblockssrccextractbitu32MSB1c SCImodulesscicosblockssrccextractbit32LSBc SCImodulesscicosblockssrccextractbit32RB0c SCImodulesscicosblockssrccextractbit32RB1c SCImodulesscicosblockssrccextractbitu32RB1c SCImodulesscicosblockssrccextractbit16UH0c SCImodulesscicosblockssrccextractbit16UH1c palettes 2580 SCImodulesscicosblockssrccextractbitu16UH1c SCImodulesscicosblockssrccextractbit16LHc SCImodulesscicosblockssrccextractbit16MSB0c SCImodulesscicosblockssrccextractbit16MSB1c SCImodulesscicosblockssrccextractbitu16MSB1c SCImodulesscicosblockssrccextractbit16LSBc SCImodulesscicosblockssrccextractbit16RB0c SCImodulesscicosblockssrccextractbit16RB1c SCImodulesscicosblockssrccextractbitu16RB1c SCImodulesscicosblockssrccextractbit8UH0c SCImodulesscicosblockssrccextractbit8UH1c SCImodulesscicosblockssrccextractbitu8UH1c SCImodulesscicosblockssrccextractbit8LHc SCImodulesscicosblockssrccextractbit8MSB0c SCImodulesscicosblockssrccextractbit8MSB1c SCImodulesscicosblockssrccextractbitu8MSB1c SCImodulesscicosblockssrccextractbit8LSBc SCImodulesscicosblockssrccextractbit8RB0c SCImodulesscicosblockssrccextractbit8RB1c SCImodulesscicosblockssrccextractbitu8RB1c See also BITSET BITSET Set a Bit BITCLEAR BITCLEAR Clear a Bit Authors Fady NASSIF INRIA palettes 2581 Nome INTMUL Integer matrix multiplication Block Screenshot Contents Integer matrix multiplication Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description The INTMUL block computes the matrix multiplication of two integers inputs matricesThe number of rows of the second matrix must be equal to the number of columns of the first matrix The output is a matrix where the number of rows is equal to the number of rows of the first input matrix and the number of columns is equal to the number of columns of the second input matrix This block support all the integer data type On overflow the result can take different forms 1 A normal non saturated result 2 A saturated result 3 An error message warning the user about the overflow The user can select one of these three forms by setting the DO ON OVERFLOW field to 01 or 2 palettes 2582 Dialog box Datatype 3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 Do on Overflow0Nothing 1Saturate 2Error When this parameter is set to zero the result is similar to a normal multiplication of two integer matrix When it is set to 1 on overflow the block saturate the result When it is set to 2 on overflow an error message box appears Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 3 port 2 size 23 type 3 regular outputs port 1 size 13 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matmuli32 palettes 2583 Interfacing function SCImodulesscicosblocksmacrosIntegerOpINTMULsci Computational function SCImodulesscicosblockssrccmatmuli32nc SCImodulesscicosblockssrccmatmuli16nc SCImodulesscicosblockssrccmatmuli8nc SCImodulesscicosblockssrccmatmului32nc SCImodulesscicosblockssrccmatmului16nc SCImodulesscicosblockssrccmatmului8nc SCImodulesscicosblockssrccmatmuli32sc SCImodulesscicosblockssrccmatmuli16sc SCImodulesscicosblockssrccmatmuli8sc SCImodulesscicosblockssrccmatmului32sc SCImodulesscicosblockssrccmatmului16sc SCImodulesscicosblockssrccmatmului8sc SCImodulesscicosblockssrccmatmuli32ec SCImodulesscicosblockssrccmatmuli16ec SCImodulesscicosblockssrccmatmuli8ec SCImodulesscicosblockssrccmatmului32ec SCImodulesscicosblockssrccmatmului16ec SCImodulesscicosblockssrccmatmului8ec See also MATMUL MATMUL Matrix Multiplication Authors Fady NASSIF INRIA palettes 2584 Nome JKFLIPFLOP JK flipflop Block Screenshot Contents JK flipflop Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Integer palette Description The JK flip flop is the most versatile of the basic flipflops It has two inputs traditionally labeled J and K When J and K are different the output takes the value of J at the next falling edge When J and K are both low no change occurs in the output state when they are both high the output will toggle from one state to other It can perform the functions of the setreset flipflop and has the advantage that there are no ambiguous states It can also act as a T flipflop to accomplish toggling action if J and K are tied together This toggle application finds extensive use in binary counters This block is almost used with digital number the input data type is int8 The truth table of this block is J K Qt Qt 0 0 Qt1 Qt1 0 1 0 1 1 0 1 0 1 1 Qt1 Qt1 palettes 2585 Dialog box Initial Value Initial Value of the state Q Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 5 port 2 size 11 type 1 port 3 size 11 type 5 regular outputs port 1 size 11 type 5 port 2 size 11 type 5 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosIntegerOpJKFLIPFLOPsci palettes 2586 Compiled Super Block content See also DLATCH D latch flipflop DFLIPFLOP D flipflop SRFLIPFLOP SR flipflop Authors Fady NASSIF INRIA palettes 2587 Nome LOGIC Combinational Logic Block Screenshot Contents Combinational Logic Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This block implements a standard truth table for modeling programming array digital circuit and any other boolean expressions The user can specify a matrix that defines all the possible block output in the Truth table field Each row of the matrix contains the output of different combination of input elements The number of rows must be a power of two it defines the number of inputs using the equation number of row 2 number of input The number of outputs is equal to the number of columns of the matrix This block support only the int8 data type When the input is positive the input is considered as logical 1 When it is negative or zero it is considered as logical 0 This block can be activated by an implicit input event or it can inherit the clock from the regular input This block is used to implement SR and JK flipflops palettes 2588 Dialog box Truth table The matrix of outputs For more information see the description part Properties Type mat of size 12 Inherit0no 1yes Specifies if the clock is inherit or not Properties Type vec of size 1 Example The easiest example to consider is the OR example In this case we have two inputs and only one outputthe truth table for this example is 0111 input 1 input 2 output 0 0 0 0 1 1 1 0 1 1 1 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 5 port 2 size 11 type 5 palettes 2589 regular outputs port 1 size 11 type 5 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function logic Interfacing function SCImodulesscicosblocksmacrosIntegerOpLOGICsci Computational function SCImodulesscicosblockssrcclogicc See also SRFLIPFLOP SR flipflop JKFLIPFLOP JK flipflop Authors Fady NASSIF INRIA palettes 2590 Nome SHIFT Shift Bits Block Screenshot Contents Shift Bits Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This block shifts the bits of the input signal In this operation the digits are moved to the right or to the left The user can choose the rule to shifts the bits It can be normal or cycle by setting the Shifttype parameter to 0 or 1 When the Shifttype is 0 an arithmetic shift is applied to the input signal In this case the bits that are shifted out of either end are discarded Zeros are shifted in on the right in the case of left shift in the case of right shifts copies of the sign bit is shifted in on the left When the Shifttype is 1a circular shift is applied to the input signal In this case the bits are rotated as if the left and right ends of the register are joined The value that is shifted in on the right during a leftshift is whatever values was shifted out on the left and vice versa palettes 2591 Dialog box Datatype 3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 Number of bits to shift left use negative number to shift right It indicates the number of bits the input signal is shifted A positive value indicates a shift left negative values indicates shift right Properties Type vec of size 1 Shifttype0Arithmetic 1Circular It indicate the rule used to shift the bits It can be arithmetic or circular When the Shifttype is normal an arithmetic shift is applied to the input signal In this case the bits that are shifted Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 3 regular outputs port 1 size 12 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2592 object discretetime state no name of computational function shift32LA Interfacing function SCImodulesscicosblocksmacrosIntegerOpSHIFTsci Computational function SCImodulesscicosblockssrccshift32LAc SCImodulesscicosblockssrccshift32LCc SCImodulesscicosblockssrccshift32RAc SCImodulesscicosblockssrccshiftu32RAc SCImodulesscicosblockssrccshift32RCc SCImodulesscicosblockssrccshift16LAc SCImodulesscicosblockssrccshift16LCc SCImodulesscicosblockssrccshift16RAc SCImodulesscicosblockssrccshiftu16RAc SCImodulesscicosblockssrccshift16RCc SCImodulesscicosblockssrccshift8LAc SCImodulesscicosblockssrccshift8LCc SCImodulesscicosblockssrccshift8RAc SCImodulesscicosblockssrccshiftu8RAc SCImodulesscicosblockssrccshift8RCc See also BITSET BITSET Set a Bit BITCLEAR BITCLEAR Clear a Bit Authors Fady NASSIF INRIA palettes 2593 Nome SRFLIPFLOP SR flipflop Block Screenshot Contents SR flipflop Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Integer palette Description This block describe the simplest and the most fundamental latch the SR flip flop Where S and R are the input and Q and Q are the outputsIf S Set is pulsed high while R is held low then the Q output is forced high and stays high when S returns low similarly if R Reset is pulsed high while S is held low then the Q output is forced low and stays low when R returns low When both are low Qt takes the same state as Qt1 When they are both high both Q and Q take the low values we are in an unstable state Practically we have to avoid this caseThis block is almost used with digital number the input data type is int8 The truth table of this block is S R Qt Qt 0 0 Qt1 Qt1 0 1 0 1 1 0 1 0 1 1 0 0 This case is to avoid palettes 2594 Dialog box Initial Value Initial Value of the state Q Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 5 port 2 size 11 type 5 regular outputs port 1 size 11 type 5 port 2 size 11 type 5 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosIntegerOpSRFLIPFLOPsci palettes 2595 Compiled Super Block content See also DLATCH D latch flipflop DFLIPFLOP D flipflop JKFLIPFLOP JK flipflop Authors Fady NASSIF INRIA 11 Lookup tables palette palettes 2596 Nome Lookuptablespal Lookup tables palette Block Screenshot Module xcos Description The lookup tables palette includes blocks that compute output approximations from inputs Blocks INTRP2BLKf 2D interpolation INTRPLBLKf Interpolation LOOKUPf Lookup table palettes 2597 Nome INTRP2BLKf 2D interpolation Block Screenshot Contents 2D interpolation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Lookup tables palette Description The output of this block is a function of the inputs obtained by bilinear interpolation This block has two scalar inputs and a single scalar output The and give respectively the coordinate and the coordinate of the th data point to be interpolated and its value Dialog box X coord an nvector strictly increasing palettes 2598 Properties Type vec of size 1 Y coord an mvector strictly increasing Properties Type vec of size 1 Z values an matrix Properties Type mat of size 11 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function intrp2 Interfacing function SCImodulesscicosblocksmacrosNonLinearINTRP2BLKfsci Computational function SCImodulesscicosblockssrcfortranintrp2f Type 1 Authors Ramine Nikoukhah INRIA palettes 2599 Nome INTRPLBLKf Interpolation Block Screenshot Contents Interpolation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Lookup tables palette Description The output of this block is a function of the input obtained by linear interpolation This block has a single scalar input and a single scalar output port The coord and coord give respectively the coordi nate and the coordinate of the data points to be interpolated coord must be strictly increasing Dialog box X coord A vector strictly increasing Properties Type vec of size 1 palettes 2600 Y coord A vector same size as coord Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function intrpl Interfacing function SCImodulesscicosblocksmacrosNonLinearINTRPLBLKfsci Computational function SCImodulesscicosblockssrcfortranintrplf Type 0 Authors Ramine Nikoukhah INRIA palettes 2601 Nome LOOKUPf Lookup table Block Screenshot Contents Lookup table Palette Description Default properties Interfacing function Computational function Authors Palette Lookup tables palette Description This block realizes a nonlinear function defined using a graphical editor Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2602 object discretetime state no name of computational function lookup Interfacing function SCImodulesscicosblocksmacrosNonLinearLOOKUPfsci Computational function SCImodulesscicosblockssrcfortranlookupf Type 0 Authors Ramine Nikoukhah INRIA 12 Math operations palette palettes 2603 Nome Mathoperationspal Math operations palette Block Screenshot Module xcos Description The Math operations palette contains blocks that model general mathematical functions Blocks ABSVALUE Absolute value BIGSOMf Sum COSBLKf Cosinus Block EXPBLKm Exponential GAINBLKf Gain INVBLK Inverse palettes 2604 LOGBLKf Common logarithm MATMAGPHI Complex to Magnitude and Angle Conversion MATZREIM Complex decomposition MAXf MAX MAXMIN Max and Min MINf MIN POWBLKf Array power PRODf Multiplication PRODUCT Product SIGNUM Signum SINBLKf Sinus block SQRT Square root SUMf Addition SUMMATION Summation TANBLKf Tangent block TrigFun Trigonometric function palettes 2605 Nome ABSVALUE Absolute value Block Screenshot Contents Absolute value Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Abs block outputs the absolute value of the input Dialog box use zerocrossing Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2606 zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function absolutevalue Interfacing function SCImodulesscicosblocksmacrosNonLinearABSVALUEsci Computational function SCImodulesscicosblockssrccabsolutevaluec Type 4 Authors Ramine Nikoukhah INRIA palettes 2607 Nome BIGSOMf Sum Block Screenshot Contents Sum Palette Description Dialog box Default properties Interfacing function Computational function Palette Math operations palette Description The Sum block performs addition on its inputs This block can add scalar or vector inputs Dialog box Inputs ports signsgain Set sign and a gain for each inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no palettes 2608 mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function sum Interfacing function SCImodulesscicosblocksmacrosLinearBIGSOMfsci Computational function SCImodulesscicosblockssrccsumc Type 2 palettes 2609 Nome COSBLKf COSBLK Block Screenshot Contents COSBLK Palette Description Default properties Interfacing function Palette Math operations palette Description Description Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2610 object discretetime state no name of computational function cosblk Interfacing function SCImodulesscicosblocksmacrosNonLinearCOSBLKfsci palettes 2611 Nome EXPBLKm Exponential Block Screenshot Contents Exponential Palette Description Dialog box Default properties Interfacing function Computational function Palette Math operations palette Description This block realizes The input and output port sizes are determined by the compiler Dialog box a A real positive scalar Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2612 zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function expblkm Interfacing function SCImodulesscicosblocksmacrosNonLinearEXPBLKmsci Computational function SCImodulesscicosblockssrccexpblkmc Type 4 palettes 2613 Nome GAINBLKf Gain Block Screenshot Contents Gain Palette Description Dialog box Default properties Interfacing function Authors Palette Math operations palette Description The GAINBLK computes the product of a square matrix A by the input matrix U where the number of rowscols of A is equal to the number of rows of U Dialog box Gain This parameter defined the square matrix A Properties Type mat of size 11 Default properties always active no directfeedthrough yes palettes 2614 zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gain Interfacing function SCImodulesscicosblocksmacrosLinearGAINBLKfsci Authors Ramine Nikoukhah INRIA palettes 2615 Nome INVBLK Inverse Block Screenshot Contents Inverse Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description This block computes The input output size is determined by the context Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no palettes 2616 name of computational function invblk4 Interfacing function SCImodulesscicosblocksmacrosNonLinearINVBLKsci Computational function SCImodulesscicosblockssrccinvblk4c Type 4 palettes 2617 Nome LOGBLKf Log Block Screenshot Contents Log Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description This block realizes The input and output port sizes are determined by the context Dialog box Basis A real scalar greater than 1 Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2618 zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function logblk Interfacing function SCImodulesscicosblocksmacrosNonLinearLOGBLKfsci Computational function SCImodulesscicosblockssrcfortranlogblkf Type 0 Authors Ramine Nikoukhah INRIA palettes 2619 Nome MATMAGPHI Complex to Magnitude and Angle Conversion Block Screenshot Contents Complex to Magnitude and Angle Conversion Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Math operations palette Description MATMAGPHI Block has two types of decomposotions When the type is set to one the block converts a complex number to the magnitude and the radian angle in this case the input is complex and the outputs are real double If the input is real double the angle will be zero or PI and the magnitude will be equal to the absolute of the input number When the type is set to two the block outputs a complex number given the magnitude and the radian angle In this case the inputs are real double and the output is complex Dialog box decomposition type 1Complex2MAGampPHI 2MAGampPHI2Complex It indicates the rule of the conversion palettes 2620 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 2 regular outputs port 1 size 12 type 1 port 2 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matzabs Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATMAGPHIsci Computational function SCImodulesscicosblockssrccmatzabsc SCImodulesscicosblockssrccmatzabscc See also MATZREIM Complex decomposition Authors Fady NASSIF INRIA palettes 2621 Nome MATZREIM Complex decomposition Block Screenshot Contents Complex decomposition Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Math operations palette Description This block decomposes a complex number by separating the real and imaginary parts or compose a complex number by joining the two parts The user can select even to separate or to join real and imaginary part by setting the decomposition type to 1 or 2 When it is set to 1 the input is a complex matrix and the outputs are the real and imaginary parts of the input When it set to 2 The inputs are two real matrices the output is a complex number with real part the first input and imaginary part the second input Dialog box decomposition type 1Complex2RealampImag 2RealampImag2Complex Indicates the type to use for the decomposition See the description part for more information Properties Type vec of size 1 palettes 2622 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 2 regular outputs port 1 size 12 type 1 port 2 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matzreim Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATZREIMsci Computational function SCImodulesscicosblockssrccmatzreimc SCImodulesscicosblockssrccmatzreimcc See also MATMAGPHI MATMAGPHI Complex to Magnitude and Angle Conversion Authors Fady NASSIF INRIA palettes 2623 Nome MAXMIN Max and Min Block Screenshot Contents Max and Min Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The MinMax block outputs either the minimum or the maximum element or elements of the inputs You can choose the function to apply by selecting one of the choices from the Function parameter list Dialog box Min or Max The function min or max to apply to the input Properties Type vec of size 1 Number of input vectors palettes 2624 The number of inputs to the block Properties Type vec of size 1 zerocrossing Select to enable zero crossing detection to detect minimum and maximum values Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function minmax Interfacing function SCImodulesscicosblocksmacrosNonLinearMAXMINsci Computational function SCImodulesscicosblockssrccminmaxc Type 4 Authors Ramine Nikoukhah INRIA palettes 2625 Nome MAXf MAX Block Screenshot Contents MAX Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description That block find the max value in the elements of its input vector Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no palettes 2626 name of computational function maxblk Interfacing function SCImodulesscicosblocksmacrosNonLinearMAXfsci Computational function SCImodulesscicosblockssrcfortranmaxblkf Type 0 palettes 2627 Nome MINf MIN Block Screenshot Contents MIN Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description That block find the min value in the elements of its input vector Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no palettes 2628 name of computational function minblk Interfacing function SCImodulesscicosblocksmacrosNonLinearMINfsci Computational function SCImodulesscicosblockssrcfortranminblkf Type 0 palettes 2629 Nome POWBLKf Power Block Screenshot Contents Power Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description This block realizes The input and output port sizes are determined by the compiler according to the connected blocks port sizes Dialog box to the power of real scalar Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2630 zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function powblk Interfacing function SCImodulesscicosblocksmacrosNonLinearPOWBLKfsci Computational function SCImodulesscicosblockssrcfortranpowblkf Type 0 Authors Ramine Nikoukhah INRIA palettes 2631 Nome PRODUCT Product Block Screenshot Contents Product Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Product block performs multiplication or division of its inputs This block produces outputs using either elementwise or matrix multiplication depending on the value of the Multiplication parameter You specify the operations with the Number of inputs parameter Multiply1 and divide 1 cha racters indicate the operations to be performed on the inputs Dialog box Number of inputs or sign vector Enter the number of inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2632 zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function product Interfacing function SCImodulesscicosblocksmacrosNonLinearPRODUCTsci Computational function SCImodulesscicosblockssrccproductc Type 4 Authors Ramine Nikoukhah INRIA palettes 2633 Nome PRODf Multiplication Block Screenshot Contents Multiplication Palette Description Default properties Interfacing function Computational function Authors Palette Math operations palette Description The output is the element wise product of the inputs Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no palettes 2634 discretetime state no object discretetime state no name of computational function prod Interfacing function SCImodulesscicosblocksmacrosNonLinearPRODfsci Computational function SCImodulesscicosblockssrccprodc Type 2 Authors Ramine Nikoukhah INRIA palettes 2635 Nome SIGNUM Signum Block Screenshot Contents Signum Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Sign block indicates the sign of the input The output is 1 when the input is greater than zero The output is 0 when the input is equal to zero The output is 1 when the input is less than zero Dialog box use zerocrossing Select to enable zero crossing detection Properties Type vec of size 1 palettes 2636 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function signum Interfacing function SCImodulesscicosblocksmacrosNonLinearSIGNUMsci Computational function SCImodulesscicosblockssrccsignumc Type 4 Authors Ramine Nikoukhah INRIA palettes 2637 Nome SINBLKf SINBLK Block Screenshot Contents SINBLK Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description Description Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no palettes 2638 discretetime state no object discretetime state no name of computational function sinblk Interfacing function SCImodulesscicosblocksmacrosNonLinearSINBLKfsci Computational function SCImodulesscicosblockssrcfortransinblkf Type 0 palettes 2639 Nome SQRT Square root Block Screenshot Contents Square root Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Math operations palette Description This block computes the square root of each element of the input matrix It supported real and complex data types Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Scicos will print the message Datatype is not supported Properties Type vec of size 1 Default properties always active no palettes 2640 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matsqrt Interfacing function SCImodulesscicosblocksmacrosMatrixOpSQRTsci Computational function SCImodulesscicosblockssrccmatsqrtc SCImodulesscicosblockssrccmatzsqrtc See also POWBLKf Pow Authors Fady NASSIF INRIA palettes 2641 Nome SUMMATION Matrix Summation Block Screenshot Contents Matrix Summation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Sum block performs addition or subtraction on its inputs This block can add or subtract scalar vector or matrix inputs It can also collapse the elements of a single input vector The number of inputs is given by the second parameter This parameter can be a vector of 1 and 1 or it can be a positive value In the first case the size of the vector indicates the number of inputs and the signs indicates whether it is a summation or a subtraction In the second case the block is a summation block and the value indicates the number of inputs On overflow the result can take different forms 1 A normal non saturated result 2 A saturated result 3 An error message warning the user about the overflow The user can select one of these three forms by setting the DO ON OVERFLOW field to 01 or 2 palettes 2642 Dialog box Datatype 1real double 2complex 3int32 It indicates the type of the inputoutput data It support all datatype number must be between 1 and 8 Properties Type vec of size 1 Number of inputs or sign vector of 1 1 It indicates the number of inputs and the operation see the description for more detail Properties Type vec of size 1 Do on Overflow0Nothing 1Saturate 2Error When this parameter is set to zero the result is similar to a normal summation of two integer matrix When it is set to 1 on overflow the block saturate the result When it is set to 2 on overflow an error message box appears If the Data type is double or complex this parameter is not used Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2643 object discretetime state no name of computational function summation Interfacing function SCImodulesscicosblocksmacrosLinearSUMMATIONsci Computational function SCImodulesscicosblockssrccsummationc SCImodulesscicosblockssrccsummationzc SCImodulesscicosblockssrccsummationi32nc SCImodulesscicosblockssrccsummationi16nc SCImodulesscicosblockssrccsummationi8nc SCImodulesscicosblockssrccsummationui32nc SCImodulesscicosblockssrccsummationui16nc SCImodulesscicosblockssrccsummationui8nc SCImodulesscicosblockssrccsummationi32sc SCImodulesscicosblockssrccsummationi16sc SCImodulesscicosblockssrccsummationi8sc SCImodulesscicosblockssrccsummationui32sc SCImodulesscicosblockssrccsummationui16sc SCImodulesscicosblockssrccsummationui8sc SCImodulesscicosblockssrccsummationi32ec SCImodulesscicosblockssrccsummationi16ec SCImodulesscicosblockssrccsummationi8ec SCImodulesscicosblockssrccsummationui32ec SCImodulesscicosblockssrccsummationui16ec SCImodulesscicosblockssrccsummationui8ec Authors Fady NASSIF INRIA Alan Layec INRIA Ramine Nikoukhah INRIA palettes 2644 Nome SUMf Addition Block Screenshot Contents Addition Palette Description Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Sum block performs addition on its inputs This block can add scalar vector or matrix inputs Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 0 port 3 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 palettes 2645 continuoustime state no discretetime state no object discretetime state no name of computational function plusblk Interfacing function SCImodulesscicosblocksmacrosLinearSUMfsci Computational function SCImodulesscicosblockssrccplusblkc Type 2 Authors Ramine Nikoukhah INRIA palettes 2646 Nome TANBLKf TANBLK Block Screenshot Contents TANBLK Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description Description Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no palettes 2647 discretetime state no object discretetime state no name of computational function tanblk Interfacing function SCImodulesscicosblocksmacrosNonLinearTANBLKfsci Computational function SCImodulesscicosblockssrcfortrantanblkf Type 0 palettes 2648 Nome TrigFun Trigonometric function Block Screenshot Contents Trigonometric function Palette Description Dialog box Default properties Interfacing function Computational function Palette Math operations palette Description The Trigonometric Function block performs numerous common trigonometric functions You can select one of these functions from the Function list sin cos tan asin acos atan atan2 sinh cosh and tanh The block output is the result of the operation of the function on the input or inputs Dialog box Function The trigonometric function Properties Type str of size 1 Default properties always active no palettes 2649 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function sinblk Interfacing function SCImodulesscicosblocksmacrosNonLinearTrigFunsci Computational function SCImodulesscicosblockssrccsinblkc Type 4 13 Matrix operation palette palettes 2650 Nome Matrixpal Matrix operation palette Block Screenshot Module xcos Description Matrix palette contains all blocks that you need to do simple and complex matrix operations Blocks CUMSUM CUMSUM Cumulative Sum EXTRACT EXTRACT Matrix Extractor EXTTRI EXTTRI Triangular or Diagonal extraction MATBKSL MATBKSLleft matrix division MATCATH MATCATH Horizontal Concatenation MATCATV MATCATV Vertical Concatenation palettes 2651 MATDET MATDET Matrix Determinant MATDIAG MATDIAG Create Diagonal Matrix MATDIV MATDIV Matrix division MATEIG MATEIG Matrix Eigenvalues MATEXPM MATEXPM Matrix Exponential MATINV MATINV Matrix Inverse MATLU MATLU LU Factorization MATMAGPHI MATMAGPHI Complex to Magnitude and Angle Conversion MATMUL MATMUL Matrix Multiplication MATPINV MATPINV Matrix PseudoInverse MATRESH MATRESH Matrix Reshape MATSING MATSING SVD decomposition MATSUM Matrix Sum MATTRAN Matrix Transpose MATZCONJ Matrix Conjugate MATZREIM Complex decomposition RICC RICC Equation de Riccati ROOTCOEF Coefficient computation SQRT SQRT Square root SUBMAT SUBMAT Submatrix extraction palettes 2652 Nome CUMSUM Cumulative Sum Block Screenshot Contents Cumulative Sum Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The CUMSUM block sums the element of an input mn matrix u along either the rows the columns or the first non singleton dimension When the Sum along parameter is set to 1 the block sums across the elements of each row The result will be displayed as a m1 matrix When the Sum along parameter is set to 2 the block sums across the elements of each column The result will be display as a 1n matrix When the Sum along parameter is set to 0 the block sums across the first non singleton dimension The result will be displayed as one element This block is equivalent to cumsum in scilab Dialog box palettes 2653 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Scicos will print the message Datatype is not supported Properties Type vec of size 1 Sum along 0the first non singleton dimension 1Rows 2Columns Indicate whether to sum across the rows the columns or the first non singleton dimension Properties Type vec of size 1 Example A1 2 34 5 67 8 9 If the sum is along the row the result will be B121518 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cumsumm Interfacing function SCImodulesscicosblocksmacrosMatrixOpCUMSUMsci Computational function SCImodulesscicosblockssrcccumsummc SCImodulesscicosblockssrcccumsumrc palettes 2654 SCImodulesscicosblockssrcccumsumcc SCImodulesscicosblockssrcccumsumzmc SCImodulesscicosblockssrcccumsumzrc SCImodulesscicosblockssrcccumsumzcc See also MATSUM Matrix Sum xcos Block Authors Fady NASSIF INRIA palettes 2655 Nome EXTRACT Matrix Extractor Block Screenshot Contents Matrix Extractor Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The EXTRACT block extracts some elements from the matrix The size of the output depends on the number of rows and number of columns to extract Dialog box Datatype 1real double 2Complex palettes 2656 It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 Lines to extract It indicates the numbers of the lines to extract Properties Type mat of size 11 Columns to extract It indicates the numbers of the columns to extract Properties Type mat of size 11 Example A1 2 34 5 67 8 9 If the Lines to extract is 1 and 2 and the Column to extract is 1 and 3 then the output is B1 34 6 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function extract Interfacing function SCImodulesscicosblocksmacrosMatrixOpEXTRACTsci Computational function SCImodulesscicosblockssrccextractc palettes 2657 SCImodulesscicosblockssrccextractzc See also EXTTRI EXTTRI Triangular or Diagonal extraction xcos Block Authors Fady NASSIF INRIA palettes 2658 Nome EXTTRI Triangular or Diagonal extraction Block Screenshot Contents Triangular or Diagonal extraction Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The EXTTRI block extracts some elements from the input matrix u When the Extraction type is set to 1 the block copies the elements on and above the main diagonal to an output matrix of the same size The elements below the main diagonal are set to zero When the Extraction type is set to 2 the block copies the elements on and below the main diagonal to an output matrix of the same size The elements above the main diagonal are set to zero When the Extraction type is set to 3 the block copies the elements on the main diagonal to an output matrix of the same size The elements above and below the main diagonal are set to zero palettes 2659 Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 extraction type 1lower 2upper 3diagonal It indicates the form of the output matrix It can be an upper triangle a lower triangle or a diagonal matrix Properties Type vec of size 1 Example A1 2 34 5 67 8 910 11 12 If the extraction type is 2 then the output is B1 0 04 5 07 8 910 11 12 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2660 object discretetime state no name of computational function extrilz Interfacing function SCImodulesscicosblocksmacrosMatrixOpEXTTRIsci Computational function SCImodulesscicosblockssrccexttrilc SCImodulesscicosblockssrccexttriuc SCImodulesscicosblockssrccextdiagc SCImodulesscicosblockssrccexttrilzc SCImodulesscicosblockssrccexttriuzc SCImodulesscicosblockssrccextdiagzc See also EXTRACT EXTRACT Matrix Extractor xcos Block Authors Fady NASSIF INRIA palettes 2661 Nome MATBKSL left matrix division Block Screenshot Contents left matrix division Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATBKSL block outputs the left matrix division It is a solution to AxB The higher input is the A matrix the lower one is the B matrix and the output is x If A is an MbyN1 matrix B must be a MbyN2 where N1 and N2 can be different or equal The output x is a N1byN2 matrix The equivalent of BACKSLASH is ïn Scilab Dialog box Datatype 1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported palettes 2662 Properties Type vec of size 1 Example A1 7 323 32 29 B21 1813 10 then the result of the AxB equation is AB x4504 39223643 31320000 0000 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 13 type 1 regular outputs port 1 size 23 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matbksl Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATBKSLsci Computational function SCImodulesscicosblockssrccmatbkslc SCImodulesscicosblockssrccmatzbkslc See also MATDIV MATDIV Matrix division xcos Block MATMUL MATMUL Matrix Multiplication xcos Block palettes 2663 Authors Fady NASSIF INRIA palettes 2664 Nome MATCATH Horizontal Concatenation Block Screenshot Contents Horizontal Concatenation Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATCATH Block outputs the horizontal concatenation of multiple matrices It is also called concatenation according to the columns The inputs U1U2Un must have the same number of rows The output is a MbyN1N2Nn matrix where N1N2Nn are the numbers of columns of the inputs matrices and M is the number of rows The equivalent of MATCATH in Scilab is yU1 U2 Un Dialog box palettes 2665 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 number of columns of each matrix It indicates the number of columns of the inputs matrices Properties Type mat of size 11 Example A1 2 34 5 6 B7 89 10 The result of the horizental concatenation is C1 2 3 7 84 5 6 9 10 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 13 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matcath Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATCATHsci Computational function SCImodulesscicosblockssrccmatcathc palettes 2666 SCImodulesscicosblockssrccmatzcathc See also MATCATV MATCATV Vertical Concatenation xcos Block Authors Fady NASSIF INRIA palettes 2667 Nome MATCATV Vertical Concatenation Block Screenshot Contents Vertical Concatenation Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATCATV Block outputs the vertical concatenation of multiple matrices It is also called con catenation according to the rows The inputs U1U2Un must have the same number of columns The output is a M1M2MnbyN matrix where M1M2Mn are the numbers of rows of the inputs matrices and N is the number of columns The equivalent of MATCATH in Scilab is yU1U2Un Dialog box palettes 2668 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 number of line of each matrix It indicates the number of rows of the inputs matrices Properties Type mat of size 11 Example A1 23 45 6 B7 89 10 The result of the horizental concatenation is C1 23 45 67 89 10 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 13 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matcatv Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATCATVsci Computational function SCImodulesscicosblockssrccmatcatvc palettes 2669 SCImodulesscicosblockssrccmatzcatvc See also MATCATH MATCATH Horizontal Concatenation xcos Block Authors Fady NASSIF INRIA palettes 2670 Nome MATDET Matrix Determinant Block Screenshot Contents Matrix Determinant Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATDET outputs the determinant of a square input matrix If the input AA11 A12 A13A21 A22 A23A31 A32 A33 then the output of the block has the form of yA11A22A33A23A32 A12A21A33A23A31A13A21A32A22A31 The equivalent of MATDET in Scilab is det Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported palettes 2671 Properties Type vec of size 1 Example U1 0 632 2 59 9 4 y2215 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matdet Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATDETsci Computational function SCImodulesscicosblockssrccmatdetc SCImodulesscicosblockssrccmatzdetc See also MATINV MATINV Matrix Inverse xcos Block Authors Fady NASSIF INRIA palettes 2672 Nome MATDIAG Create Diagonal Matrix Block Screenshot Contents Create Diagonal Matrix Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATDIAG block create a diagonal matrix from a 1D vector If the input is a Mby1 vector than the output is an MbyM matrix Dialog box Datatype 1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 palettes 2673 Example if the input of the block is Uones51 then the output is y1 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matdiag Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATDIAGsci Computational function SCImodulesscicosblockssrccmatdiagc SCImodulesscicosblockssrccmatzdiagc See also EXTTRI EXTTRI Triangular or Diagonal extraction xcos Block Authors Fady NASSIF INRIA palettes 2674 Nome MATDIV Matrix division Block Screenshot Contents Matrix division Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATDIV block outputs the right matrix division It is a solution to xBA The higher input is the A matrix the lower one is the B matrix and the output is x If A is an M1byN matrix B must be a M2byN where M1 and M2 can be different or equal The output x is a M1byM2 matrix The equivalent of BACKSLASH is in Scilab Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Xcos will print the message Datatype is not supported palettes 2675 Properties Type vec of size 1 Example A1 7 323 32 29 B21 18 3413 10 1911 54 36 then the result of the xBA equation is AB x0475 0712 01564350 8381 0491 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 13 type 1 port 2 size 23 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matdiv Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATDIVsci Computational function SCImodulesscicosblockssrccmatdivc SCImodulesscicosblockssrccmatzdivc See also MATBKSL MATBKSLleft matrix division MATMUL MATMUL Matrix Multiplication palettes 2676 Authors Fady NASSIF INRIA palettes 2677 Nome MATEIG Matrix Eigenvalues Block Screenshot Contents Matrix Eigenvalues Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATEIG calculate the eigenvalues and the eigenvectors of a square input matrix U When the Decomposition type is set to 1 the block outputs the eigenvalues in a vector form if the input is a MbyM matrix the output is a Mby1 vector When the Decomposition type is set to 2 the block outputs two matrices for an MbyM input matrixthe first output is a MbyM diagonal matrix composed by the eigenvalues and the second is a MbyM matrices composed by the eigenvectors the eigenvectors are represented by the columns of the matrix The equivalent of the MATEIG block in Scilab is specA Dialog box palettes 2678 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 decomposition type 1eig values 2eig valueseig vectors To select the form of the output Properties Type vec of size 1 Example A1 12 3221 35 4670 8 19 When the Decomposition type is set to one the output is y356491427976369 When the Decomposition type is set to two the outputs are y135649 0000 00000000 14279 00000000 0000 76369 y20557 0080 03490330 0922 07700762 0379 0533 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 2 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matvps Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATEIGsci Computational function SCImodulesscicosblockssrccmatvpsc palettes 2679 SCImodulesscicosblockssrccmatvpvc SCImodulesscicosblockssrccmatzvpsc SCImodulesscicosblockssrccmatzvpvc See also MATSING MATSING SVD decomposition xcos Block Authors Fady NASSIF INRIA palettes 2680 Nome MATEXPM Matrix Exponential Block Screenshot Contents Matrix Exponential Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATEXPM outputs the matrix exponential of a square matrix input by the pades approximants The output is a square matrix with the same size of the input The equivalent of this block in Scilab is expm Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported palettes 2681 Properties Type vec of size 1 Example u1 2 32 3 14 2 1 y182612 196518 141735172973 190770 133577204677 220063 159067 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matexpm Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATEXPMsci Computational function SCImodulesscicosblockssrccmatexpmc SCImodulesscicosblockssrccmatzexpmc See also MATMUL MATMUL Matrix Multiplication xcos Block Authors Fady NASSIF INRIA palettes 2682 Nome MATINV Matrix Inverse Block Screenshot Contents Matrix Inverse Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATINV Block outputs the inverse of a square input matrix using the LU factorization A warning message is printed if the input is badly scaled or nearly singular The equivalent function of this block in Scilab is inv Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 palettes 2683 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matinv Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATINVsci Computational function SCImodulesscicosblockssrccmatinvc SCImodulesscicosblockssrccmatzinvc See also MATLU MATLU LU Factorization xcos Block MATPINV MATPINV Matrix PseudoInverse xcos Block Authors Fady NASSIF INRIA palettes 2684 Nome MATLU LU Factorization Block Screenshot Contents LU Factorization Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATLU Block outputs two matrices L and U with row pivoting from the LU factorization of a square input matrix If A is the input matrix then EALU where E is the permutation matrixThe equivalent function of this block in Scilab is lueluA Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 palettes 2685 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matlu Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATLUsci Computational function SCImodulesscicosblockssrccmatluc SCImodulesscicosblockssrccmatzluc See also MATINV MATINV Matrix Inverse xcos Block Authors Fady NASSIF INRIA palettes 2686 Nome MATMUL Matrix Multiplication Block Screenshot Contents Matrix Multiplication Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATMUL block computes the matrix multiplication of two inputs matricesThe number of rows of the second matrix must be equal to the number of columns of the first matrix The output is a matrix where the number of rows is equal to that of the first input matrix and the number of columns is equal to that of the second input matrix Dialog box Datatype1real double 2Complex palettes 2687 It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 Multiplication rule 1 2 Properties Type vec of size 1 Example A1 2 34 5 6 B9 8 7 65 4 3 29 7 5 3 y46 37 28 19115 94 73 52 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 23 type 1 regular outputs port 1 size 13 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matmulm Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATMULsci Computational function SCImodulesscicosblockssrccmatmulmc SCImodulesscicosblockssrccmatzmulmc palettes 2688 SCImodulesscicosblockssrccmatmul2mc SCImodulesscicosblockssrccmatzmul2mc See also INTMUL INTMUL integer matrix multiplication xcos Block MATDIV MATDIV Matrix division Scicos Block MATBKSL MATBKSLleft matrix division xcos Block MATEXPM MATEXPM Matrix Exponential xcos Block SUMMATION SUMMATION Matrix Summation xcos Block Authors Fady NASSIF INRIA Alan Layec INRIA palettes 2689 Nome MATPINV Matrix PseudoInverse Block Screenshot Contents Matrix PseudoInverse Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATPINV Block outputs the inverse of a non square input matrix using the SVD theoryif the SVD decomposition of A is equal to AUSV The pseudoinverse x of A is given by XVSU where Sij1Sij if Sij 0 U and V are respectively the transpose of U and V and we have AXAA and XAXX Both AX and XA are Hermitian A warning message is printed if the input is badly scaled or nearly singular When the input is a MbyN matrix the output is a NbyM matrix The equivalent function of this block in Scilab is pinv Dialog box palettes 2690 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matpinv Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATPINVsci Computational function SCImodulesscicosblockssrccmatpinvc SCImodulesscicosblockssrccmatzpinvc See also MATINV MATINV Matrix Inverse xcos Block MATSING MATSING SVD decomposition xcos Block Authors Fady NASSIF INRIA palettes 2691 Nome MATRESH Matrix Reshape Block Screenshot Contents Matrix Reshape Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The RESHAPE block changes the dimensions of a matrix or a vector to another dimensions specified by the user in the output size desired label The output size must be less or equal to the input size Dialog box Datatype1real double 2Complex palettes 2692 It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 input size It indicates the size of the input matrix Properties Type vec of size 1 output size desired It indicates the desired outputs size Properties Type vec of size 1 Example u1 2 3 45 6 7 8 When the output desired is 16 the output is y1 2 3 4 5 6 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matreshape Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATRESHsci Computational function SCImodulesscicosblockssrccmatreshapec palettes 2693 SCImodulesscicosblockssrccmatzreshapec See also EXTRACT EXTRACT Matrix Extractor xcos Block Authors Fady NASSIF INRIA palettes 2694 Nome MATSING SVD decomposition Block Screenshot Contents SVD decomposition Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATSING block computes the economy sized SVD of the MbyN input matrix A by finding US and V such that AUSV When the decomposition type is set to one the output is a vector composed by the singular values When the decomposition type is set to two we have three outputs the second output is a diagonal matrix S composed by the singular values and the other two outputs are the unitary matrices U and V The equivalent function of this block in Scilab is svd Dialog box palettes 2695 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 decomposition type 1singular values 2sing valuesmatrix U amp V It indicates the form of the output When it is set to one we have a unique vector output singular values When it is set to two we have three same sizes matricesUSV Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matsing Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATSINGsci Computational function SCImodulesscicosblockssrccmatsingc SCImodulesscicosblockssrccmatsvdc SCImodulesscicosblockssrccmatzsingc SCImodulesscicosblockssrccmatzsvdc See also MATEIG MATEIG Matrix Eigenvalues xcos Block palettes 2696 MATLU MATLU LU Factorization xcos Block Authors Fady NASSIF INRIA palettes 2697 Nome MATSUM Matrix Sum Block Screenshot Contents Matrix Sum Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATSUM block returns the sum of the element of an input matrixvector When the Sum along is set to all the block outputs the sum of all the elements of the matrix The output is then a scalar When the Sum along is set to lines the block is a rowwise sum The output is a row vector When the Sum along is set to Columns the block is a columnwise sum The output is a column vector The equivalent function of this block in Scilab is sum Dialog box Datatype1real double 2Complex palettes 2698 It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 Sum along 0all 1lines 2Columns Indicates the used rule to sum For more information see the description part Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matsum Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATSUMsci Computational function SCImodulesscicosblockssrccmatsumc SCImodulesscicosblockssrccmatsumlc SCImodulesscicosblockssrccmatsumcc SCImodulesscicosblockssrccmatzsumc SCImodulesscicosblockssrccmatzsumlc SCImodulesscicosblockssrccmatzsumcc See also SUBMAT SUBMAT Submatrix extraction xcos Block palettes 2699 SUMMATION SUMMATION Matrix Summation xcos Block Authors Fady NASSIF INRIA palettes 2700 Nome MATTRAN Matrix Transpose Block Screenshot Contents Matrix Transpose Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description This Block transposes an MxN matrix to a NxM matrix For complex data type it uses the hermitian transpose The equivalent of this block in Scilab is yu Dialog box Datatype1real double 2Complex It indicates the data type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported palettes 2701 Properties Type vec of size 1 Example Complex 1i 23i 32i Tranpose 1 i 4 i 4i 58i 62i 23i 58i 32i 62i Real 1 2 3 Tranpose 1 4 4 5 6 2 5 3 6 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function mattranm Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATTRANsci Computational function SCImodulesscicosblockssrccmattranmc SCImodulesscicosblockssrccmatztranmc palettes 2702 See also Matrixpal Matrix operation palette xcos Palette Authors Fady NASSIF INRIA Alan Layec INRIA palettes 2703 Nome MATZCONJ Matrix Conjugate Block Screenshot Contents Matrix Conjugate Palette Description Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description This blocks computes the conjugate of a complex input matrix Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 2 regular outputs port 1 size 12 type 2 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no palettes 2704 discretetime state no object discretetime state no name of computational function matzconj Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATZCONJsci Computational function SCImodulesscicosblockssrccmatzconjc See also Matrixpal Matrix operation palette xcos Palette Authors Fady NASSIF INRIA palettes 2705 Nome RICC Riccati Equation Block Screenshot Contents Riccati Equation Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description This block computes the solution of Riccati equation using different method and for both case conti nuous and discrete The Riccati equation in continuous time is AXXACXDX0 The Riccati equation in discrete time is AXinvInDAXC0 where A is an NxN matrix it is the first input of the block C and D are two NxN symmetrics matrices and are respectively the second and third input of the RICC block X represent the output of the block it is also a NxN matrix The user can choose between two methods of computation For the continuous time he can use even the Schur method or the matrix sign function approach method by setting the Model parameter to 1 or 2 For the discrete time the models are the Schur method and the inverse free spectral decomposition method palettes 2706 Dialog box Type 1Cont 2Disc For continuous time signal set this parameter to 1 For discrete input time set it to 2 Properties Type vec of size 1 Model1Schr 2signcont invdisc To use the Shur method in computation set this parameter to 1 To use matrix sign function appro ach in continuous case or the inverse free spectral decomposition method in discrete case set this parameter to 2 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 port 3 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function riccm palettes 2707 Interfacing function SCImodulesscicosblocksmacrosMatrixOpRICCsci Computational function SCImodulesscicosblockssrccriccmc See also Matrixpal Matrix operation palette xcos Palette Authors Fady NASSIF INRIA palettes 2708 Nome ROOTCOEF Coefficient computation Block Screenshot Contents Coefficient computation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Matrix operation palette Description This block computes the coefficients of a polynomial given its root values Dialog box Datatype1real double 2Complex This block can only support double inputs values These values can be real or complex Properties Type vec of size 1 input row size The input row size palettes 2709 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function rootcoef Interfacing function SCImodulesscicosblocksmacrosMatrixOpROOTCOEFsci Computational function SCImodulesscicosblockssrccrootcoefc SCImodulesscicosblockssrccrootzcoefc Authors Fady NASSIF INRIA palettes 2710 Nome SUBMAT Submatrix extraction Block Screenshot Contents Submatrix extraction Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Matrix operation palette Description This block outputs a sub matrix of the input matrix The output matrix will be defining by using the parameters of this block Dialog box palettes 2711 Datatype 1real double 2Complex Type of the output matrix It can be double or complex Properties Type vec of size 1 Starting Row Index The first row of the submatrix Properties Type vec of size 1 Ending Row Index The last row of the Submatrix Properties Type vec of size 1 Starting Column Index The first column of the submatrix Properties Type vec of size 1 Ending Column Index The last row of the submatrix Properties Type vec of size 1 Input Dimension The Matrix input dimensions Properties Type vec of size 2 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no palettes 2712 name of computational function submat Interfacing function SCImodulesscicosblocksmacrosMatrixOpSUBMATsci Computational function SCImodulesscicosblockssrccsubmatc SCImodulesscicosblockssrccsubmatzc Authors Fady NASSIF INRIA 14 Port Subsystem palette palettes 2713 Nome Portactionpal Port Subsystem palette Block Screenshot Module xcos Description The Port Subsystem palette includes blocks for creating subsystems Blocks CLKINVf Input activation port EventSelect CLKOUTVf Output activation port EventSelect INf Input Port INIMPLf Input implicit port OUTIMPLf Output implicit port OUTf Output Port SUPERf Super block palettes 2714 Nome INf Input Port Block Screenshot Contents Input Port Palette Description Dialog box Default properties Interfacing function Authors Palette Port Subsystem palette Description This block must only be used inside xcos Super Blocks to represent a regular input port The input size is determined by the context In a Super Block regular input ports must be numbered from 1 to the number of regular input ports Dialog box Port number an integer defining the port number Properties Type vec of size 1 Default properties always active no directfeedthrough no palettes 2715 zerocrossing no mode no regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function input Interfacing function SCImodulesscicosblocksmacrosSourcesINfsci Authors Ramine Nikoukhah INRIA palettes 2716 Nome OUTIMPLf Output implicit port Block Screenshot Contents Output implicit port Palette Description Dialog box Default properties Interfacing function Authors Palette Port Subsystem palette Description Outport blocks are the links from a system to a destination outside the system Dialog box Port number Specify the port number of the Outport block Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no palettes 2717 mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function outimpl Interfacing function SCImodulesscicosblocksmacrosSinksOUTIMPLfsci Authors Ramine Nikoukhah INRIA palettes 2718 Nome OUTf Output Port Block Screenshot Contents Output Port Palette Description Dialog box Default properties Interfacing function Authors Palette Port Subsystem palette Description This block must only be used inside Xcos Super Blocks to represent a regular output port In a Super Block regular output ports must be numbered from 1 to the number of regular output ports Size of the output is determined by the compiler according to the connected blocks port sizes Dialog box Port number an integer defining the port number Properties Type vec of size 1 Default properties always active no directfeedthrough no palettes 2719 zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function output Interfacing function SCImodulesscicosblocksmacrosSinksOUTfsci Authors Ramine Nikoukhah INRIA 15 Signal processing palette palettes 2720 Nome Signalprocessingpal Signal processing palette Block Screenshot Module xcos Description The signal processing palette contains blocks designed specifically for signal processing applications Blocks MCLOCKf MFCLCKf QUANTf Quantization SAMPHOLDm Sample and hold palettes 2721 Nome QUANTf Quantization Block Screenshot Contents Quantization Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal processing palette Description This block outputs the quantization of the input according to a choice of methods Dialog box Step scalar Quantization step Properties Type vec of size 1 Quantization Type scalar with possible values 123 or 4 Properties Type vec of size 1 palettes 2722 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function qzrnd Interfacing function SCImodulesscicosblocksmacrosNonLinearQUANTfsci Computational function SCImodulesscicosblockssrcfortranqzrndf SCImodulesscicosblockssrcfortranqztrnf SCImodulesscicosblockssrcfortranqzflrf SCImodulesscicosblockssrcfortranqzcelf Authors Ramine Nikoukhah INRIA palettes 2723 Nome SAMPHOLDm Sample and hold Block Screenshot Contents Sample and hold Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal Processing palette Description Each time an input event is received block copy its input on the output and hold it until input event For periodic Sample and hold event input must be generated by a Clock Dialog box Datatype1real double 2Complex 3int32 Output datatype This block can support all data types Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2724 zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function samphold4m Interfacing function SCImodulesscicosblocksmacrosLinearSAMPHOLDmsci Computational function SCImodulesscicosblockssrccsamphold4mc Type 4 Authors Fady NASSIF INRIA 16 Signal routing palette palettes 2725 Nome Signalroutingpal Signal routing palette Block Screenshot Module xcos Description The Signal routing palette includes blocks that transport signals from one point in a block diagram to another Blocks DEMUX Demultiplexer EXTRACTOR Extractor FROM FROM Receives data from a corresponding GOTO FROMMO Receives data from a corresponding GOTOMO GOTO GOTO Pass block input to From block GOTOMO Pass block input to FROMMO block GotoTagVisibility Define Scope of GOTO tag visibility GotoTagVisibilityMO Define Scope of GOTOMO tag visibility ISELECTm Iselect palettes 2726 MUX Multiplexer MSWITCH Multiport switch NRMSOMf Merge data RELAYf Relay SELECTm Select SWITCH2m Switch2 SWITCHf Switch palettes 2727 Nome DEMUX Demultiplexer Block Screenshot Contents Demultiplexer Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description Given a vector valued input this block splits inputs over vector valued outputs So where are numbered from top to bottom Input and Output port sizes are determined by the context Dialog box number of output ports or vector of sizes positive integer less than or equal to Properties Type vec of size 1 Default properties always active no palettes 2728 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 01 type 1 regular outputs port 1 size 11 type 1 port 2 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function multiplex Interfacing function SCImodulesscicosblocksmacrosBranchingDEMUXsci Computational function SCImodulesscicosblockssrccmultiplexc Type 4 Authors Ramine Nikoukhah INRIA palettes 2729 Nome EXTRACTOR Extractor Block Screenshot Contents Extractor Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description Extracts or select a regular input from a multiple regular input Dialog box indices to extract a regular input to be extracted from the multiple regular inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no palettes 2730 mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function extractor Interfacing function SCImodulesscicosblocksmacrosBranchingEXTRACTORsci Computational function SCImodulesscicosblockssrccextractorc Type 4 Authors Ramine Nikoukhah INRIA palettes 2731 Nome FROM FROM Receives data from a corresponding GOTO Block Screenshot Contents FROM Receives data from a corresponding GOTO Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal routing palette Description The main role of the GOTOFROM blocks is to transport signals from a block to another block without connecting them physically The FROM block transports its received data from the corresponding GOTO to its output Multiples FROM blocks can receive data from one GOTO although a GOTO can send data to multiple FROM The GOTO and FROM blocks are connected by the tag parameter For information on the visibility and limitation of these blocks please refer to the GOTO documen tation This block can support all the data types Dialog box palettes 2732 Tag The tag of the GOTO block passing the signal to this FROM block Properties Type str of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function from Interfacing function SCImodulesscicosblocksmacrosBranchingFROMsci See also GOTO GOTO Pass block input to From block GotoTagVisibility Define Scope of GOTO tag visibility Authors Fady NASSIF INRIA palettes 2733 Nome FROMMO Receives data from a corresponding GOTOMO Block Screenshot Contents Receives data from a corresponding GOTOMO Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal Routing palette Description This block is used to connect Modelica blocks For more information on how it works please refer to the documentation of the FROM block by clicking on the link in the See also field Dialog box Tag The tag of the GOTOMO block passing the signal to this FROMMO block Properties Type str of size 1 Default properties always active no palettes 2734 directfeedthrough no zerocrossing no mode no regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function frommo Interfacing function SCImodulesscicosblocksmacrosBranchingFROMMOsci See also FROM FROM Receives data from a corresponding GOTO xcos Block Authors Fady NASSIF INRIA palettes 2735 Nome GOTO GOTO Pass block input to From block Block Screenshot Contents GOTO Pass block input to From block Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal routing palette Description The main role of the GOTOFROM blocks is to transport signals from a block to another block without connecting them physically The GOTO block transports its input data to its corresponding FROM block A simple GOTO block can send data to multiple FROM although a FROM can receive data from only one GOTO The GOTO and FROM blocks are connected by the tag parameter The Tag Visibility parameter indicates if the location of the FROM block is limited Local means that the corresponding FROM of that GOTO must be in the same subsystem Scoped means that the corresponding FROM of that GOTO must be in the same subsystem or in any subsystem below the GotoTagVisibility block in the model hierarchy Global means that the corresponding FROM of that GOTO can be anywhere in the model This block can support all the data types palettes 2736 Dialog box Tag This parameter identifies the Goto block whose scope is defined in this block Properties Type str of size 1 Tag Visibility1Local 2scoped 3 global This parameter identifies the visibility of the block It can be local1 scoped2 or global3 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function goto Interfacing function SCImodulesscicosblocksmacrosBranchingGOTOsci See also FROM FROM Receives data from a corresponding GOTO GotoTagVisibility Define Scope of GOTO tag visibility palettes 2737 Authors Fady NASSIF INRIA palettes 2738 Nome GOTOMO Pass block input to FROMMO block Block Screenshot Contents Pass block input to FROMMO block Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal Routing palette Description This block is used to connect Modelica blocks For more information on how it works please refer to the documentation of the GOTO block by clicking on the link in the See also field Dialog box Tag This parameter identifies the Goto block whose scope is defined in this block Properties Type str of size 1 Tag Visibility1Local 2scoped 3 global This parameter identifies the visibility of the block It can be local1 scoped2 or global3 palettes 2739 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gotomo Interfacing function SCImodulesscicosblocksmacrosBranchingGOTOMOsci See also GOTO GOTO Pass block input to From block xcos Block Authors Fady NASSIF INRIA palettes 2740 Nome GotoTagVisibility Define Scope of GOTO tag visibility Block Screenshot Contents Define Scope of GOTO tag visibility Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal routing palette Description This block defines the accessibility of the GOTO block when it is configure as scoped The FROM block corresponding to that GOTO must be in the same subsystem of the GotoTagVisibility or in subsystems below it in the model hierarchy Dialog box GotoTag The Goto block tag whose visibility is defined by the location of this block Properties Type str of size 1 Default properties always active no palettes 2741 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gototagvisibility Interfacing function SCImodulesscicosblocksmacrosBranchingGotoTagVisibilitysci See also GOTO GOTO Pass block input to From block FROM FROM Receives data from a corresponding GOTO Authors Fady NASSIF INRIA palettes 2742 Nome GotoTagVisibilityMO Define Scope of GOTOMO tag visibility Block Screenshot Contents Define Scope of GOTOMO tag visibility Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal Routing palette Description This block is used in case of Modelica connection For more information on how it works please refer to the GotoTagVisibility block by clicking on the link in the See also field Dialog box GotoTag The Goto block tag whose visibility is defined by the location of this block Properties Type str of size 1 Default properties always active no palettes 2743 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gototagvisibilitymo Interfacing function SCImodulesscicosblocksmacrosBranchingGotoTagVisibilityMOsci See also GotoTagVisibility Define Scope of GOTO tag visibility xcos Block Authors Fady NASSIF INRIA palettes 2744 Nome ISELECTm Iselect Block Screenshot Contents Iselect Palette Description Dialog box Default properties Interfacing function Computational function Palette Signal routing palette Description Select signals from an incoming events This block has one regular input port Dialog box Datatype1 real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Xcos will print the message Datatype is not supported Properties Type vec of size 1 number of outputs a scalar Number of regular and event outputs palettes 2745 Properties Type vec of size 1 initial connected output an integer It must be between 1 and the number of inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 port 2 size 12 type 1 numbersizes of activation inputs 2 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function selectorm Interfacing function SCImodulesscicosblocksmacrosBranchingISELECTmsci Computational function SCImodulesscicosblockssrccselectormc Type 4 palettes 2746 Nome MUX Multiplexer Block Screenshot Contents Multiplexer Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description Given vector valued inputs this block merges inputs in an single output vector So where are numbered from top to bottom Input and Output port sizes are determined by the context Dialog box number of input ports or vector of sizes integer greater than or equal to 1 and less than 8 Properties Type vec of size 1 Default properties always active no palettes 2747 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 21 type 1 regular outputs port 1 size 01 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function multiplex Interfacing function SCImodulesscicosblocksmacrosBranchingMUXsci Computational function SCImodulesscicosblockssrccmultiplexc Type 4 Authors Ramine Nikoukhah INRIA palettes 2748 Nome MSWITCH Multiport switch Block Screenshot Contents Multiport switch Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description The MultiPort Switch block chooses between a number of inputs The first top input is called the control input while the rest of the inputs are called data inputs The value of the control input deter mines which data input is passed through to the output port Dialog box number of inputs Specify the number of data inputs to the block Properties Type vec of size 1 zero base indexing palettes 2749 If selected the block uses zerobased indexing Otherwise the block uses onebased indexing Properties Type vec of size 1 rounding rule int Select the rounding mode for the output Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 0 port 3 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function mswitch Interfacing function SCImodulesscicosblocksmacrosBranchingMSWITCHsci Computational function SCImodulesscicosblockssrccmswitchc Type 4 Authors Ramine Nikoukhah INRIA palettes 2750 Nome NRMSOMf Merge data Block Screenshot Contents Merge data Palette Description Dialog box Default properties Interfacing function Authors Palette Signal routing palette Description The Merge block combines its inputs into a single output line whose value at any time is equal to the most recently computed output of its driving blocks You can specify any number of inputs by setting the blocks Number of inputs parameter Dialog box number of inputs The number of input ports to be merged Properties Type vec of size 1 Default properties always active no palettes 2751 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function junk Interfacing function SCImodulesscicosblocksmacrosBranchingNRMSOMfsci Authors Ramine Nikoukhah INRIA palettes 2752 Nome RELAYf Relay Block Screenshot Contents Relay Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description This block routes one of the regular inputs to the unique regular output the choice of which input is to be routed is done initially by the initial connected input parameter Then every time an input event arrives on the ith input event port the ith regular input port is routed to the regular output Dialog box number of inputs a scalar Number of regular and event inputs Properties Type vec of size 1 palettes 2753 initial connected input an integer It must be between 1 and the number of inputs Properties Type vec of size 1 Default properties always active yes directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 2 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function relay Interfacing function SCImodulesscicosblocksmacrosBranchingRELAYfsci Computational function SCImodulesscicosblockssrccrelayc Type 2 Authors Ramine Nikoukhah INRIA palettes 2754 Nome SELECTm Select Block Screenshot Contents Select Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description A Selector block accepts either vector or matrix signals as input Set the Input Type parameter to the type of signal vector or matrix that the block should accept in your model The parameter dialog box and the blocks appearance change to reflect the type of input that you select The way the block determines the elements to select differs slightly depending on the type of input Dialog box Datatype1 real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Xcos will print the message Datatype is not supported Properties Type vec of size 1 palettes 2755 number of inputs a scalar Number of regular and event inputs Properties Type vec of size 1 initial connected input an integer It must be between 1 and the number of inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 2 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function selectorm Interfacing function SCImodulesscicosblocksmacrosBranchingSELECTmsci Computational function SCImodulesscicosblockssrccselectormc Type 4 Authors Fady NASSIF INRIA Ramine Nikoukhah INRIA palettes 2756 Nome SWITCH2m Switch2 Block Screenshot Contents Switch2 Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description The Switch block passes through the first top input or the third bottom input based on the value of the second middle input The first and third inputs are called data inputs The second input is called the control input You select the conditions under which the first input is passed with the Criteria for passing first input parameter You can make the block check whether the control input is greater than or equal to the threshold value purely greater than the threshold value or nonzero If the control input meets the condition set in the Criteria for passing first input parameter then the first input is passed Otherwise the third input is passed Dialog box palettes 2757 Datatype1 real double 2Complex a scalar Give the datatype of the inputsoutput Properties Type vec of size 1 pass first input if u2 a Select the conditions under which the first input is passed You can make the block check whether the control input is greater than or equal to the threshold value purely greater than the threshold value or nonzero If the control input meets the condition set in this parameter then the first input is passed Otherwise the third input is passed Properties Type vec of size 1 threshold a Assign the switch threshold that determines which input is passed to the output Properties Type vec of size 1 use zero crossing yes Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 12 type 1 port 2 size 11 type 0 port 3 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function switch2m palettes 2758 Interfacing function SCImodulesscicosblocksmacrosBranchingSWITCH2msci Computational function SCImodulesscicosblockssrccswitch2mc Type 4 Authors Fady NASSIF INRIA Ramine Nikoukhah INRIA palettes 2759 Nome SWITCHf Switch Block Screenshot Contents Switch Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description This is a Manual Switch block It selects one of its inputs to pass through to the output The selected input is propagated to the output while the unselected inputs are discarded Dialog box number of inputs Specify the number of data inputs to the block Properties Type vec of size 1 connected input an integer It must be between 1 and the number of inputs palettes 2760 Properties Type vec of size 1 Default properties always active yes directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function switchn Interfacing function SCImodulesscicosblocksmacrosBranchingSWITCHfsci Computational function SCImodulesscicosblockssrccswitchnc Type 2 Authors Ramine Nikoukhah INRIA 17 Sinks palette palettes 2761 Nome Sinkspal Sinks palette Block Screenshot Module xcos Description In Sinks palette you can find a variety of blocks used to display Scope and write data during simu lation and also some output ports used in superblocks The blocks of that palette doesnt have regular output ports Blocks AFFICHm Display CANIMXY yfx animated viewer CANIMXY3D zfxy animated viewer CFSCOPE Floating point scope CLKOUTVf Output activation port CMAT3D Matrix z values 3D viewer CMATVIEW Matrix Colormapped viewer CMSCOPE Multi display scope CSCOPE Single Display Scope CSCOPXY yfx permanent viewer CSCOPXY3D zfxy permanent viewer ENDBLK END block viewer palettes 2762 ENDc ENDc block viewer HALTf Halt block viewer OUTIMPLf Output implicit port viewer OUTf Output port viewer TOWSc Data to Scilab worspace TRASHf Trash block WFILEf Write to file WRITEAUf Write AU sound file Write binary data palettes 2763 Nome AFFICHm Display Block Screenshot Contents Display Palette Description Dialog box Default properties Interfacing function Computational function Palette Sinks palette Description This block displays the value of its unique input inside the block in the diagram during simulation Dialog box palettes 2764 Input Size Explicitly define the size of the input port Properties Type mat of size 12 Font number integer the selected font number see xset Properties Type vec of size 1 Font size integer the selected font size set xset Properties Type vec of size 1 Color integer the selected color for the text see xset Properties Type vec of size 1 Total number of digits an integer greater than 3 the maximum number of digits used to represent the number sign integer part and rational part Properties Type vec of size 1 Number of rational part digits n integer greater than or equal 0 the number of digits used to represent the rational part Properties Type vec of size 1 Block inherits Options to choose event inheritance from regular input or from explicit event input 0 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no palettes 2765 discretetime state yes object discretetime state no name of computational function affich2 Interfacing function SCImodulesscicosblocksmacrosSinksAFFICHmsci Computational function SCImodulesscicosblockssrcfortranaffich2f Type 0 palettes 2766 Nome CANIMXY yfx animated viewer Block Screenshot Contents yfx animated viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description This block realizes the visualization of the evolution of the two regular input signals by drawing the second input as a function of the first at instants of events on the event input port When a point is drawn on screen it stays until the buffer length is reached This scope is useful to make simple animations palettes 2767 Dialog box Number of Curves Set the number of curves Properties Type vec of size 1 color an integer It is the color number or marker type used to draw the evolution of the input port signal Seexset for color dash type definitions Properties Type vec of size 1 line or mark size an integer Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Properties Type vec of size 1 Output window position palettes 2768 a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Xmin Minimum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Xmax Maximum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Ymin Minimum and maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Ymax Maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Buffer size An integer value In order to minimize the number of graphics outputs data may buffered Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 palettes 2769 continuoustime state no discretetime state no object discretetime state no name of computational function canimxy Interfacing function SCImodulesscicosblocksmacrosSinksCANIMXYsci Computational function SCImodulesscicosblockssrcccanimxyc Type 4 See also CANIMXY3D zfxy animated viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2770 Nome CANIMXY3D zfxy animated viewer Block Screenshot Contents zfxy animated viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description This block realizes the visualization of the evolution of the three regular input signals by drawing the third input as a function of the two others at instants of events on the event input port When a point is drawn on screen it stays until the buffer length is reached This scope is useful to make simple animations palettes 2771 Dialog box Number of Curves Set the number of curves Properties Type vec of size 1 color an integer It is the color number or marker type used to draw the evolution of the input port signal Seexset for color dash type definitions Properties Type vec of size 1 line or mark size an integer Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Properties Type vec of size 1 Output window position palettes 2772 a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Xmin and Xmax Minimum and Maximum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Ymin and Ymax Minimum and Maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Zmin and Zmax Minimum and Maximum values of the third input used to set up the Zaxis of the plot in the graphics window Properties Type vec of size 1 Alpha and Theta Set Alpha and Theta for the 3D view Properties Type vec of size 1 Buffer size An integer value In order to minimize the number of graphics outputs data may buffered Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 port 3 size 11 type 1 palettes 2773 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function canimxy3d Interfacing function SCImodulesscicosblocksmacrosSinksCANIMXY3Dsci Computational function SCImodulesscicosblockssrcccanimxy3dc Type 4 See also CANIMXY yfx animated viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2774 Nome CFSCOPE Floating point scope Block Screenshot Contents Floating point scope Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description This is a floating scope block palettes 2775 Dialog box Color a vector of integers The ith element is the color number or dash type used to draw the evolution of the ith input port signal Seeplot2d for color dash type definitions Properties Type vec of size 8 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If default value is used1 Xcos define the output window number Properties Type vec of size 1 Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Ymin Minimum values of the input used to set up the Yaxis of the plot in the graphics window palettes 2776 Properties Type vec of size 1 Ymax Maximum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Refresh period Maximum value on the Xaxis time The plot is redrawn when time reaches a multiple of this value Properties Type vec of size Buffer size To improve efficiency it is possible to buffer the input data The drawing is only done after each Buffer size call to the block Properties Type vec of size 1 Links to view This parameter allows you to display the output of specified link Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cfscope Interfacing function SCImodulesscicosblocksmacrosSinksCFSCOPEsci Computational function SCImodulesscicosblockssrcccfscopec Type 4 Authors Ramine Nikoukhah INRIA palettes 2778 Nome CMAT3D Matrix z values 3D viewer Block Screenshot Contents Matrix z values 3D viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description CMAT3D is a scope that shows matrix values as z values on a xy grid Dialog box palettes 2779 Bounds Vector X 1 for standard If you let 1 the x ticks would be between 0 and 1 else you can put your own vector Properties Type vec of size 1 Bounds Vector Y 1 for standard If you let 1 the x ticks would be between 0 and 1 else you can put your own vector Properties Type vec of size 1 ColorMap The colormap is a range color linked to the window output of the scope You can put a jetcolormap or hotcolormap or graycolormap or your own see colormap help Properties Must be a mx3 matrix and m 3 Zmin Minimum value in Z values Properties Type vec of size 1 Zmax Maximum values in Z values Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cmat3d Interfacing function SCImodulesscicosblocksmacrosSinksCMAT3Dsci palettes 2780 Computational function SCImodulesscicosblockssrcccmat3dc Type 4 See also CMATVIEW Matrix Colormapped viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2781 Nome CMATVIEW Matrix Colormapped viewer Block Screenshot Contents Matrix Colormapped viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description CMATVIEW is a scope that shows matrix values on a colormapped grid Dialog box ColorMap palettes 2782 The colormap is a range color linked to the window output of the scope You can put a jetcolormap or hotcolormap or graycolormap or your own see colormap help Properties Must be a mx3 matrix and m 3 Minimum level range The minimum level range is the minimum value who comes in the regular input port It would be linked to the cold value of the colormap Properties A scalar Maximum level range The maximum level range is the maximum value who comes in the regular input port It would be linked to the hot value of the colormap Properties A scalar Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cmatview Interfacing function SCImodulesscicosblocksmacrosSinksCMATVIEWsci Computational function SCImodulesscicosblockssrcccmatviewc Type 4 See also CMAT3D Matrix z values 3D viewer Authors palettes 2783 Ramine Nikoukhah INRIA Benoit Bayol palettes 2784 Nome CMSCOPE Multi display scope Block Screenshot Contents Multi display scope Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description When you start a simulation Xcos open Scope windows The Scope block displays its input with respect to simulation time The Scope block can have multiple axes one per port all axes have a common time range with independent yaxes The Scope allows you to adjust the amount of time and the range of input values displayed palettes 2785 Dialog box Input ports sizes It allows multiple input ports Properties Type vec of size 1 Drawing colors a vector of integers The ith element is the color number or dash type used to draw the evolution of the ith input port signal Seeplot2d for color dash type definitions Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If default value is used1 Xcos define the output window number Properties Type vec of size 1 Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes palettes 2786 a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size size 1 Ymin vector Minimum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size size1 Ymax vector Maximum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size size1 Refresh period Maximum value on the Xaxis time The plot is redrawn when time reaches a multiple of this value Properties Type vec of size size1 Buffer size To improve efficiency it is possible to buffer the input data The drawing is only done after each Buffer size call to the block Properties Type vec of size 1 Accept herited events 01 if 0CSCOPEf draws a new point only when an event occurs on its event input port if 1CSCOPEf draws a new point when an event occurs on its event input port and when its regular input changes due to an event on an other upstrem block herited events Properties Type vec of size 1 Name of Scope Namelabel of the block Properties Type str of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 palettes 2787 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cmscope Interfacing function SCImodulesscicosblocksmacrosSinksCMSCOPEsci Computational function SCImodulesscicosblockssrcccmscopec Type 4 Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2788 Nome CSCOPE Single Display Scope Block Screenshot Contents Single Display Scope Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description The Scope block displays its input with respect to simulation time Both axes have a common range The Scope allows you to adjust the amount of time and the range of input values displayed palettes 2789 Dialog box Color a vector of integers The ith element is the color number or dash type used to draw the evolution of the ith input port signal Seeplot2d for color dash type definitions Properties Type vec of size 8 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If default value is used1 Scicos define the output window number Properties Type vec of size 1 Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Ymin palettes 2790 Minimum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Ymax Maximum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Refresh period Maximum value on the Xaxis time The plot is redrawn when time reaches a multiple of this value Properties Type vec of size 1 Buffer size To improve efficiency it is possible to buffer the input data The drawing is only done after each Buffer size call to the block Properties Type vec of size 1 Accept herited events 01 if 0CSCOPEf draws a new point only when an event occurs on its event input port If 1CSCOPEf draws a new point when an event occurs on its event input port and when its regular input changes due to an event on an other upstream block herited events Properties Type vec of size 1 Name of Scope Namelabel of the block Properties Type str of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cscope palettes 2791 Interfacing function SCImodulesscicosblocksmacrosSinksCSCOPEsci Computational function SCImodulesscicosblockssrcccscopec Type 4 See also CMSCOPE Multi display scope Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2792 Nome CSCOPXY yfx permanent viewer Block Screenshot Contents yfx permanent viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description This block realizes the visualization of the evolution of the two regular inputs signals by drawing the second input as a function of the first at instants of events on the event input port When a point is drawn on screen it stays until the simulation is finished palettes 2793 Dialog box Number of Curves Set the number of curves Properties Type vec of size 1 color an integer It is the color number or dash type used to draw the evolution of the input port signal Seeplot2d for color dash type definitions Properties Type vec of size 1 line or mark size an integer Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Properties Type vec of size 1 Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position palettes 2794 Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Xmin Minimum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type of size Xmax Maximum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Ymin Minimum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Ymax Maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Buffer size To improve efficiency it is possible to buffer the input data The drawing is only done after each Buffer size call to the block Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no Benoit Bayol palettes 2795 discretetime state no object discretetime state no name of computational function cscopxy Interfacing function SCImodulesscicosblocksmacrosSinksCSCOPXYsci Computational function SCImodulesscicosblockssrcccscopxyc Type 4 See also CSCOPXY3D zfxy permanent viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2796 Nome CSCOPXY3D zfxy permanent viewer Block Screenshot Contents zfxy permanent viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description This block realizes the visualization of the evolution of the three regular inputs signals by drawing the third input as a function of the two others at instants of events on the event input port When a point is drawn on screen it stays until the simulation is finished palettes 2797 Dialog box Number of Curves Set the number of curves Properties Type vec of size 1 color an integer It is the color number or marker type used to draw the evolution of the input port signal Seexset for color dash type definitions Properties Type vec of size 1 line or mark size an integer Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Properties Type vec of size 1 Output window position palettes 2798 a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Xmin and Xmax Minimum and Maximum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Ymin and Ymax Minimum and Maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Zmin and Zmax Minimum and Maximum values of the third input used to set up the Zaxis of the plot in the graphics window Properties Type vec of size 1 Alpha and Theta Set Alpha and Theta for the 3D view Properties Type vec of size 1 Buffer size An integer value In order to minimize the number of graphics outputs data may buffered Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 port 3 size 11 type 1 palettes 2799 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cscopxy3d Interfacing function SCImodulesscicosblocksmacrosSinksCSCOPXY3Dsci Computational function SCImodulesscicosblockssrcccscopxy3dc Type 4 See also CSCOPXY yfx permanent viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2800 Nome ENDBLK END block Block Screenshot Contents END block Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Sinks Sinks palette Description That block can be used to set the final time of the simulation When that block is truely parametrized then the simulator will jump to the final integration time defined in the Setup item of the simulate Menu from the time defined by the parameter Final simulation time of the dialog box That parameter can be a numerical value or a symbolic variable defined in the scicos context Dialog box Final simulation time Set the final time of the simulation When simulator reaches that value then the current time will jump to the final integration time Properties Type vec of size 1 palettes 2801 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosMiscENDBLKsci Compiled Super Block content See also ENDc ENDc block Scicos Block Authors Alan Layec INRIA palettes 2802 Nome ENDc ENDc block Block Screenshot Contents ENDc block Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks Sinks palette Description That block increases the current time to the final integration time of the simulation when it is activated with Tcur the activation date of the block and Tf the final integration time defined in the in the Setup item of the simulate Menu scsmpropstf Dialog box Final simulation time palettes 2803 That parameter is a date for an initial output event By using a feed back from the event output port to the event input port then that block can himself end the simulation at the time defined by this parameter Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function scicosexit Interfacing function SCImodulesscicosblocksmacrosEventsENDcsci Computational function SCImodulesscicosblockssrccscicosexitc Type 4 See also ENDBLK END block Scicos Block Authors Alan Layec INRIA palettes 2804 Nome TOWSc Data to Scilab worspace Block Screenshot Contents Data to Scilab worspace Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description That block is used to put simulated data in the scilab workspace Each sampling time both dates and values of input are recorded Dialog box Size of buffer Set the size of the input buffer That gives the total number of samples recorded during the simu lation palettes 2805 That buffer is a circulate buffer Properties Type vec of size 1 Scilab variable name Set the name of the Scilab variable This must be a valid variable name The simulation must be finished to retrieve that variable in the Scilab workspace Properties Type str of size 1 Inherit no0 yes1 Options to choose event inheritance from regular input or from explicit event input 0 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function towsc Interfacing function SCImodulesscicosblocksmacrosSinksTOWScsci Computational function SCImodulesscicosblockssrcctowscc Type 4 Authors Alan Layec INRIA palettes 2806 Nome TRASHf Trash block Block Screenshot Contents Trash block Palette Description Default properties Interfacing function Computational function Palette Sinks palette Description That block is an endblock It do nothing Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function trash palettes 2807 Interfacing function SCImodulesscicosblocksmacrosSinksTRASHfsci Computational function SCImodulesscicosblockssrcfortrantrashf Type 0 palettes 2808 Nome WFILEf Write to file Block Screenshot Contents Write to file Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description This block allows user to save data in a file in formatted and binary mode Each call to the block corresponds to a record in the file Each record has the following form where is the value of time when block is called and is the ith input value This block does not manage UTF filename The pair block is Dialog box palettes 2809 Input size a scalar This fixes the input size Properties Type vec of size 1 Output file name a character string defining the path of the file Properties Type str of size 1 Output Format a character string defining the Fortran format to use or nothing for an unformatted binary wri te If given the format must began by a left parenthesis and end by a right parenthesis exam ple Properties Type str of size 1 Buffer size To improve efficiency it is possible to buffer the input data Write on the file is only done after eachBuffer size call to the block Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function writef Interfacing function SCImodulesscicosblocksmacrosSinksWFILEfsci Computational function SCImodulesscicosblockssrcfortranwriteff Type 0 palettes 2810 Authors Ramine Nikoukhah INRIA palettes 2811 Nome WRITEAUf Write AU sound file Block Screenshot Contents Write AU sound file Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description This block writes a sound file specified by the string au file The data should be arranged with one channel per column Amplitude values outside the range 11 are clipped prior to writing auwrite supports multichannel data for 8bit mulaw and 8 and 16bit linear formats Dialog box Buffer size To improve efficiency it is possible to buffer the input data read on the file is only done after each Buffer size call to the block Properties Type vec of size 1 palettes 2812 Swap mode 01 WithSwap mode1 the file is supposed to be coded in little endian IEEE format and data are swaped if necessary to match the IEEE format of the processor IfSwap mode0 then automatic bytes swap is disabled Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function writeau Interfacing function SCImodulesscicosblocksmacrosSinksWRITEAUfsci Computational function SCImodulesscicosblockssrccwriteauc Type 2 Authors Ramine Nikoukhah INRIA palettes 2813 Nome WRITECf Write binary data Block Screenshot Contents Write binary data Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description This block allows user to write data in a C binary file Dialog box Input size palettes 2814 a scalar the size of the input Properties Type vec of size 1 Output file name a character string defining the output file name Properties Type str of size 1 Output Format a character string defining the format to use Properties Type str of size 1 Buffer size To improve efficiency it is possible to buffer the input data read on the file is only done after eachBuffer size call to the block Properties Type vec of size 1 Swap mode 01 WithSwap mode1 the file is supposed to be coded in little endian IEEE format and data are swaped if necessary to match the IEEE format of the processor IfSwap mode0 then automatic bytes swap is disabled Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function writec Interfacing function SCImodulesscicosblocksmacrosSinksWRITECfsci palettes 2815 Computational function SCImodulesscicosblockssrccwritecc Type 2 Authors Ramine Nikoukhah INRIA 18 Sources palette palettes 2816 Nome Sourcespal Sources palette Block Screenshot Module xcos Description Most of blocks of the Source palette can be viewed as data generators That palette also contains blocks to read data from files and input ports used in superblocks The blocks of that palette doesnt have regular input ports Blocks CLKINVf Input activation port CLOCKc Activation clock CONSTm Constant Counter Counter palettes 2817 CURVf Curve FROMWSB Data from Scilab workspace to Xcos GENSINf Sin generator GENSQRf Square wave generator INf Input Port INIMPLf Input implicit port ModuloCount Modulo counter RAMP Ramp RANDm Random generator READAUf Read AU sound file READCf Read binary data RFILEf Read from file SampleCLK Sample Time Clock SAWTOOTHf Sawtooth generator Sigbuilder Signal creatorgenerator STEPFUNCTION Step function generator TIMEf Time TKSCALE Adjust constant value with a tk widget palettes 2818 Nome CLKINVf Input activation port Block Screenshot Contents Input activation port Palette Description Dialog box Default properties Interfacing function Authors Palette Sources palette Description This block must only be used inside Xcos Super Blocks to represent an event input port In a Super Block the event input ports must be numbered from 1 to the number of event input ports Dialog box Port number an integer defining the port number Properties Type vec of size 1 Default properties always active no directfeedthrough no palettes 2819 zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function input Interfacing function SCImodulesscicosblocksmacrosSourcesCLKINVfsci Authors Ramine Nikoukhah INRIA palettes 2820 Nome CLOCKc Activation clock Block Screenshot Contents Activation clock Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Sources palette Description This block is a Super Block constructed by feeding back the output of the block into its input event port The unique output of this block generates a regular train of events thats scheduled by the dialog parameter Period Dialog box Period scalar One over the frequency of the clock palettes 2821 Period is the time that separates two output events Properties Type vec of size 1 Init time scalar Starting date If negative the clock never starts Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosSourcesCLOCKcsci Compiled Super Block content palettes 2822 See also EVTDLYc Event delay Authors Alan Layec INRIA palettes 2823 Nome CONSTm Constant Block Screenshot Contents Constant Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a constant value generator Dialog box Constant A matrix of any type The size of the matrix gives the size of the regular output port The constantij value is the componentij value of the output port From this value the block inherits its data type Properties Type mat of size 12 palettes 2824 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cstblk4 Interfacing function SCImodulesscicosblocksmacrosSourcesCONSTmsci Computational function SCImodulesscicosblockssrcccstblk4c Type 4 Authors Fady NASSIF INRIA Alan Layec INRIA palettes 2825 Nome CURVf Curve Block Screenshot Contents Curve Palette Description Default properties Interfacing function Computational function See also Authors Palette Sources palette Description This block defines a tabulated function of time Between mesh points block performs a linear inter polation Outside tabulation block outputs last tabulated value User may define the tabulation of the function using a curve editor Default properties always active yes directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2826 object discretetime state no name of computational function intplt Interfacing function SCImodulesscicosblocksmacrosSourcesCURVfsci Computational function SCImodulesscicosblockssrcfortranintpltf Type 0 See also Sigbuilder Signal creatorgenerator Authors Ramine Nikoukhah INRIA palettes 2827 Nome Counter Counter Block Screenshot Contents Counter Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sources palette Description This block counts from minimal to maximal or from maximal to minimal depending on the choice of the rule Dialog box Minimum The lowest number of the counter palettes 2828 Properties Type vec of size 1 Maximum The highest number of the counter Properties Type vec of size 1 Rule 1Increment 2Decrement The rule of counting If it is 1 then the counter counts from the lower number to the higher number the count in this case is increasing otherwise if the rule is equal to 2 the counter will decrease and it will count from the higher number to the lower one Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function counter Interfacing function SCImodulesscicosblocksmacrosSourcesCountersci Computational function SCImodulesscicosblockssrcccounterc Type 4 See also ModuloCount Modulo counter xcos Block Authors Fady NASSIF INRIA palettes 2829 Nome FROMWSB Data from Scilab workspace to Xcos Block Screenshot Contents Data from Scilab workspace to Xcos Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Sources palette Description That block is used to get data defined in the Scilab workspace and use them in Xcos Data should have time and values fields Dialog box Variable name This variable is defined in Scilab and should be a structure with two fields ie a time field of size Nx1 and a values filed of size NxM time is a column vector of size palettes 2830 Nx1 and values is a matrix of size NM time filed can only be of Real type whereas the values field can be and Interpolation method Variables read by Xcos are data values read at discrete instants given by the time field This option causes the block to interpolate at time steps for which no corresponding workspace data exists There are four interpolation methods available 0 Zero order method This method generates a piecewise constant signal ie for This method is available for all data types 1 Linear method This method generates a piecewise linear signal ie for For data types other than double and complex the linear interpolation can be used but the final output will be com puted by casting interpolation result into the original data type 2NATURAL method This cubic spline is computed by using the following conditions con sidering points This method is only available for Real and complex data types 3NOTAKNOT method The cubic spline is computed by using the following conditions considering points This method is only available for Real and complex data types Enable zero crossing0No 1Yes Enables zero crossing detection When and interpolation methods are chosen the output signal will be discontinuous at data time instants These possible discontinuities may cause problem for the numerical solver In order to perform a reliable numerical integration the zero crossing option is used If output of the block affects data used by the nume rical solver at discontinuous points a discrete event is generated and the numerical solver is cold restarted The discrete event is also generated at the and for other interpolating methods Output at end0Zero 1Hold 2Repeat This option is for selecting method for generating out put after the last time point for which data is available from the workspace 0 Zero The output is set to zero 1 Hold The output is hold 2 Repeat The output is repeated from workspace Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs palettes 2831 port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosSourcesFROMWSBsci Compiled Super Block content See also TOWSc Data to Scilab worspace Authors Masoud Najafi INRIA palettes 2832 Nome GENSINf Sin generator Block Screenshot Contents Sin generator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a sine wave generator Dialog box Magnitude a scalar The magnitude M Properties Type vec of size 1 palettes 2833 Frequency a scalar The frequency F Properties Type vec of size 1 phase a scalar The phase P Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gensin Interfacing function SCImodulesscicosblocksmacrosSourcesGENSINfsci Computational function SCImodulesscicosblockssrcfortrangensinf Type 0 Authors Ramine Nikoukhah INRIA palettes 2834 Nome GENSQRf Square wave generator Block Screenshot Contents Square wave generator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a square wave generator output takes values M and M Every time an event is received on the input event port the output switches from M to M or M to M Dialog box Amplitude a scalar Properties Type vec of size 1 Default properties always active no palettes 2835 directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function gensqr Interfacing function SCImodulesscicosblocksmacrosSourcesGENSQRfsci Computational function SCImodulesscicosblockssrcfortrangensqrf Type 0 Authors Ramine Nikoukhah INRIA palettes 2836 Nome INIMPLf Input implicit port Block Screenshot Contents Input implicit port Palette Description Dialog box Default properties Interfacing function Authors Palette Sources palette Description Inport blocks are the links from outside a system into the system Dialog box Port number Specify the port number of the Inport block Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no palettes 2837 mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function inimpl Interfacing function SCImodulesscicosblocksmacrosSourcesINIMPLfsci Authors Ramine Nikoukhah INRIA palettes 2838 Nome ModuloCount Modulo counter Block Screenshot Contents Modulo counter Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description It is a discrete block The block outputs a periodic scalar signal having a waveform that the user specifies Dialog box initial state A scalar initial discrete state Properties Type vec of size 1 Modulo what number palettes 2839 Number of required discrete signals Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function modulocount Interfacing function SCImodulesscicosblocksmacrosSourcesModuloCountsci Computational function SCImodulesscicosblockssrccmodulocountc Type 4 Authors Ramine Nikoukhah INRIA palettes 2840 Nome RAMP Ramp Block Screenshot Contents Ramp Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description The Ramp block generates a signal that starts at a specified time and value and changes by a specified rate The blocks Slope Start time and Initial output parameters determine the characteristics of the output signal All must have the consistent dimensions after scalar expansion Dialog box Slope The rate of change of the generated signal Properties Type vec of size 1 palettes 2841 Start time The time at which the signal begins to be generated Properties Type vec of size 1 Initial output The initial value of the signal Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing yes mode yes regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function ramp Interfacing function SCImodulesscicosblocksmacrosSourcesRAMPsci Computational function SCImodulesscicosblockssrccrampc Type 4 Authors Ramine Nikoukhah INRIA palettes 2842 Nome RANDm Random generator Block Screenshot Contents Random generator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a random wave generator each output component takes piecewise constant random values Every time an event is received on the input event port the outputs take new independent random values Output port size is given by the size of A and B matrices palettes 2843 Dialog box Datatype1real double 2complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Scicos will print the message Datatype is not supported Properties Type vec of size 1 flag 0 or 1 0 for uniform distribution on AAB 1 for normal distribution Properties Type vec of size 1 A matrix Properties Type mat of size 12 B matrix Properties Type mat of size 12 seed matrix Seed value for a sequence of random number First number is for the real part and the second for the imaginary part Properties Type mat of size 12 palettes 2844 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function rndblkm Interfacing function SCImodulesscicosblocksmacrosSourcesRANDmsci Computational function SCImodulesscicosblockssrccrndblkmc SCImodulesscicosblockssrccrndblkzmc Authors Fady Nassif INRIA Ramine Nikoukhah INRIA palettes 2845 Nome READAUf Read AU sound file Block Screenshot Contents Read AU sound file Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description Loads a sound file specified by the string au file returning the sampled data in y The au extension is appended if no extension is given Amplitude values are in the range 11 auread supports mul tichannel data in the following formats 8bit mulaw 8 16 and 32bit linear Floatingpoint Dialog box palettes 2846 Input file name a character string defining the path of the file Properties Type str of size 1 Buffer size To improve efficiency it is possible to buffer the input data Read on the file is only done after each Buffer size call to the block Properties Type vec of size 1 Swap mode 01 WithSwap mode1 the file is supposed to be coded in little endian IEEE format and data are swaped if necessary to match the IEEE format of the processor IfSwap mode0 then automatic bytes swap is disabled Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function readau Interfacing function SCImodulesscicosblocksmacrosSourcesREADAUfsci Computational function SCImodulesscicosblockssrccreadauc Type 2 Authors Ramine Nikoukhah INRIA palettes 2847 Nome READCf Read binary data Block Screenshot Contents Read binary data Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block allows user to read data in a C file Output record selection and Time record Selection allows the user to select data among file records Each call to the block advance one record in the file palettes 2848 Dialog box Time record selection an empty matrix or a positive integer If an integer i is given the i th element of the read record is assumed to be the date of the output event If empty no output event exists Properties Type vec of size 1 Outputs record selection a vector of positive integer The th element of the read record gives the value of output Properties Type vec of size 1 Input file name a character string defining the path of the file Properties Type str of size 1 Input Format a character string defining the format to use Properties Type str of size 1 Record size palettes 2849 The file is supposed to be formed by a sequence of data with same format These data are organized in a sequence of record each of them containing Record size data Properties Type vec of size 1 Buffer size To improve efficiency it is possible to buffer the input data Read on the file is only done after each Buffer size call to the block Properties Type vec of size 1 Initial record index a scalar This fixes the first record of the file to use Properties Type vec of size 1 Swap mode 01 WithSwap mode1 the file is supposed to be coded in little endian IEEE format and data are swaped if necessary to match the IEEE format of the processor IfSwap mode0 then automatic bytes swap is disabled Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function readc Interfacing function SCImodulesscicosblocksmacrosSourcesREADCfsci Computational function SCImodulesscicosblockssrccreadcc Type 2 palettes 2850 Authors Ramine Nikoukhah INRIA palettes 2851 Nome RFILEf Read from file Block Screenshot Contents Read from file Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources Description This block allows user to read data in a file in formatted or binary mode Output record selection and Time record selection allows the user to select data among file records Each call to the block advance one record in the file The pair block is Dialog box palettes 2852 Time record selection an empty matrix or a positive integer If an integer is given the th element of the read record is assumed to be the date of the output event If empty no output event exists Properties Type vec of size 1 Outputs record selection a vector of positive integer The th element of the read record gives the value of i th output Properties Type vec of size 1 Input file name a character string defining the path of the file Properties Type str of size 1 Input Format a character string defining the Fortran format to use or nothing for an unformatted binary wri te If given the format must began by a left parenthesis and end by a right parenthesis exam ple Properties Type str of size 1 Buffer size To improve efficiency it is possible to buffer the input data read on the file is only done after eachBuffer size call to the block Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 palettes 2853 continuoustime state no discretetime state yes object discretetime state no name of computational function readf Interfacing function SCImodulesscicosblocksmacrosSourcesRFILEfsci Computational function SCImodulesscicosblockssrcfortranreadff Type 0 Authors Ramine Nikoukhah INRIA palettes 2854 Nome SAWTOOTHf Sawtooth generator Block Screenshot Contents Sawtooth generator Palette Description Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a sawtooth wave generator output is from to where and denote the times of two succes sive input events Default properties always active yes directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function sawtth palettes 2855 Interfacing function SCImodulesscicosblocksmacrosSourcesSAWTOOTHfsci Computational function SCImodulesscicosblockssrcfortransawtthf Type 0 Authors Ramine Nikoukhah INRIA palettes 2856 Nome STEPFUNCTION Step function generator Block Screenshot Contents Step function generator Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Authors Palette Sources palette Description The Step block provides a step between two definable levels at a specified time If the simulation time is less than the Step time parameter value the blocks output is the Initial value parameter value For simulation time greater than or equal to the Step time the output is the Final value parameter value Dialog box Step time The time in seconds when the output jumps from the Initial value parameter to the Final value parameter Properties Type vec of size 1 palettes 2857 Initial value The block output until the simulation time reaches the Step time parameter Properties Type vec of size 1 Final value The block output when the simulation time reaches and exceeds the Step time parameter Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosSourcesSTEPFUNCTIONsci Compiled Super Block content palettes 2858 Authors Ramine Nikoukhah INRIA palettes 2859 Nome SampleCLK Sample Time Clock Block Screenshot Contents Sample Time Clock Palette Description Dialog box Default properties Interfacing function See also Authors Palette Sources palette Description The difference between the SampleCLK and the CLOCKc is that all the SampleCLK blocks in our diagram are synchronous The synchronism is done due to two different methods of computation in the compilation phase The first method consists of computing a clock that is faster than all the SampleCLK connected to a counter which activate the event select block The clock is calculated due to the following rule If all the blocks have the same offset then the frequency of the clock is the gcd of the sample time and the offset of the clock is equal to the offset If the offsets are different then the frequency of the clock is the gcd of the sample time and the offset and the offset of the clock is equal to 0 The Counter counts from one to the least common multiple of the sample time lcm The number of outputs of the ESELECTf block is equal to the lcm The second method uses the Multifrequency block it generates events only for specific time Events in this method are not periodically generated as in the first one palettes 2860 Dialog box Sample time The Sample time value Properties Type vec of size 1 Offset The offset value Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function sampleclk Interfacing function SCImodulesscicosblocksmacrosSourcesSampleCLKsci See also CLOCKc Activation clock Counter Counter ESELECTf Synchronous block EventSelect Mfreq Multiple Frequencies palettes 2861 Authors Fady NASSIF INRIA palettes 2862 Nome Sigbuilder Signal creatorgenerator Block Screenshot Contents Signal creatorgenerator Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Authors Palette Sources palette Description The Signal Builder block is a superblock containing a block whose output event port is connected to its input event port This event feedback gives the possibility to generate events at discontinuous point of the signal The generated events automatically restart the numerical solver and avoids numerical problems The generated event is also made available to the user for possible use Remind that if higher interpolation methods are used the events are generated only at the beginning and at the end of the signal palettes 2863 Dialog box The parameters of Sigbuilder block is the same as that of block Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosSourcesSigbuildersci palettes 2864 Compiled Super Block content Authors Masoud Najafi INRIA palettes 2865 Nome TIMEf Time Block Screenshot Contents Time Palette Description Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a time generator The unique regular output is the current time Default properties always active yes directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no palettes 2866 name of computational function timblk Interfacing function SCImodulesscicosblocksmacrosSourcesTIMEfsci Computational function SCImodulesscicosblockssrcfortrantimblkf Type 0 Authors Ramine Nikoukhah INRIA palettes 2867 Nome TKSCALE Adjust constant value with a tk widget Block Screenshot Contents Adjust constant value with a tk widget Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This source block generates a piecewise constant signal the value of which can be set interactively using a TK widget in the course of the simulation The output value is the value set by the slider an integer between Min value and Max value divided by the Normalization factor Increasing proporti onaly all three block parameters does not change the output range but it does increase precision Dialog box Min value palettes 2868 An integer specifying the min value in the range of the scale Properties Type vec of size 1 Max value An integer specifying the max value in the range of the scale Properties Type vec of size 1 Normalization The output of the block is the integer value specified by the slider an integer between Min value and the Max value divided by this Normalization factor Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function tkscaleblk Interfacing function SCImodulesscicosblocksmacrosSourcesTKSCALEsci Computational function SCImodulesscicosmacrosscicosscicostkscaleblksci Type 5 Authors Ramine Nikoukhah INRIA 19 Thermohydraulics palette palettes 2869 Nome ThermoHydraulicspal ThermalHydraulics toolbox Block Screenshot Module xcos Description ThermalHydraulics toolbox contains some basic thermalhydraulic components such as pressure source pipe control valves etc Blocks Bache Thermalhydraulic tank reservoir PerteDP Thermalhydraulic pipe PuitsP Thermalhydraulic drain well SourceP Thermalhydraulic constant pressure source VanneReglante Thermalhydraulic control valve palettes 2870 Nome Bache Thermalhydraulic tank reservoir Block Screenshot Contents Thermalhydraulic tank reservoir Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description The Bache block represents a thermalhydraulic tank or reservoir This block has two inlets and two outlets whose altitudes can be changed by the user Conventionally for input ports black ports flow direction is positive when fluid flows into the tank On the other hand for output ports white ports flow direction is positive when fluid flows out of the tank The user can set the surface area of the tank the initial temperature and initial level of the fluid in the tank If an input or output port is left unused it should be blocked by a stopper block palettes 2871 Dialog box Pression dans le ciel de la bache Patm Pa Atmospheric pressure inside the tank Properties Type vec of size 1 Section de la bache A m2 Surface area of the tank Properties Type vec of size 1 Altitude du piquage d entrée 1 ze1 m Altitude of the first input port Properties Type vec of size 1 Altitude du piquage d entrée 2 ze2 m Altitude of the second input port Properties Type vec of size 1 Altitude du piquage de sortie 1 zs1 m Altitude of the first output port Properties Type vec of size 1 Altitude du piquage de sortie 2 zs2 m Altitude of the second output port Properties Type vec of size 1 palettes 2872 Altitude initiale du fluide z0 m Initial fluid level in the tank Properties Type vec of size 1 Température initiale du fluide T0 K Temperature of fluid in the tank Properties Type vec of size 1 Si 0 masse volumique imposée du fluide prho kgm3 Density of fluid Properties Type vec of size 1 Default properties Inputs Modelica variable name Ce1 Implicit variable Modelica variable name Ce2 Implicit variable Outputs Modelica variable name Cs1 Implicit variable Modelica variable name Cs2 Implicit variable Modelica variable name yNiveau Explicit variable Parameters Modelica parameter name Patm Default value 101300 Is a state variable no Modelica parameter name A Default value 1 Is a state variable no Modelica parameter name ze1 Default value 40 Is a state variable no palettes 2873 Modelica parameter name ze2 Default value 0 Is a state variable no Modelica parameter name zs1 Default value 40 Is a state variable no Modelica parameter name zs2 Default value 0 Is a state variable no Modelica parameter name z0 Default value 30 Is a state variable no Modelica parameter name T0 Default value 290 Is a state variable no Modelica parameter name prho Default value 0 Is a state variable no File name of the model Bache Interfacing function SCImodulesscicosblocksmacrosHydraulicsBachesci Modelica model SCImodulesscicosblocksmacrosHydraulicsBachemo palettes 2874 Nome PerteDP Thermalhydraulic pipe Block Screenshot Contents Thermalhydraulic pipe Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description A PertDP block represents a hydraulic pipe with linear resistance losses This component represents a hydraulic resistance and pressure loss is directly proportional to the flow rate Conventionally the flow direction is the positive when fluid flows from the black port to the white port The pressure loss is obtained with The key parameters of this block are the pipes length the pipes diameter inlet and outlet altitudes and some other thermalhydraulic coefficients palettes 2875 Dialog box Longueur du tube L m Length of pipe Properties Type vec of size 1 Diamètre interne du tube D m Pipe diameter Properties Type vec of size 1 Coefficient de perte de chargefrottementSU lambda Coefficient of thermohydraluc resistance Properties Type vec of size 1 Altitude entrée tuyauterie z1 m Altitude of the first port z1 Properties Type vec of size 1 Altitude sortie tuyauterie z2 m Altitude of the second port z2 Properties Type vec of size 1 Si 0 masse volumique imposée fu fluide prho kgm3 Fluid density Properties Type vec of size 1 Default properties Inputs Modelica variable name C1 Implicit variable palettes 2876 Outputs Modelica variable name C2 Implicit variable Parameters Modelica parameter name L Default value 10 Is a state variable no Modelica parameter name D Default value 02 Is a state variable no Modelica parameter name lambda Default value 003 Is a state variable no Modelica parameter name z1 Default value 0 Is a state variable no Modelica parameter name z2 Default value 0 Is a state variable no Modelica parameter name prho Default value 0 Is a state variable no File name of the model PerteDP Interfacing function SCImodulesscicosblocksmacrosHydraulicsPerteDPsci Modelica model SCImodulesscicosblocksmacrosHydraulicsPerteDPmo palettes 2877 Nome PuitsP Thermalhydraulic drain well Block Screenshot Contents Thermalhydraulic drain well Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description This thermalhydraulic component represents a thermalhydraulic constant pressure drain well This block is specified with its pressure and temperature Conventionally the flow direction is positive when fluid flows into the block Dialog box Pression de la source P0 Pa Pressure of the thermohydraulic source Properties Type vec of size 1 Temperature de la source T0 K palettes 2878 Temperature of the thermohydraulic source Properties Type vec of size 1 Enthalpie spécifique de la source H0 Jkg Specific Enthaly of the thermohydraulic source Properties Type vec of size 1 1température fixée 2enthalpie fixée optiontemperature Temperature option 1 fixed temperature 2 fixed enthalpy Properties Type vec of size 1 Default properties Inputs Modelica variable name C Implicit variable Parameters Modelica parameter name P0 Default value 100000 Is a state variable no Modelica parameter name T0 Default value 290 Is a state variable no Modelica parameter name H0 Default value 100000 Is a state variable no Modelica parameter name optiontemperature Default value 1 Is a state variable no File name of the model Puits Interfacing function SCImodulesscicosblocksmacrosHydraulicsPuitsPsci Modelica model SCImodulesscicosblocksmacrosHydraulicsPuitsmo palettes 2879 Nome SourceP Thermalhydraulic constant pressure source Block Screenshot Contents Thermalhydraulic constant pressure source Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description This thermalhydraulic component represents a thermalhydraulic constant pressure supply This block is specified with its output pressure and temperature Conventionally the flow direction is positive when the fluid flows out of the block Dialog box Pression de la source P0 Pa Pressure of the thermohydraulic source Properties Type vec of size 1 Temperature de la source T0 K palettes 2880 Temperature of the thermohydraulic source Properties Type vec of size 1 Enthalpie spécifique de la source H0 Jkg Specific enthalpie of the thermohydraulic source Properties Type vec of size 1 1température fixée 2enthalpie fixée optiontemperature Temperature option 1 fixed temperature 2 fixed enthalpy Properties Type vec of size 1 Default properties Outputs Modelica variable name C Implicit variable Parameters Modelica parameter name P0 Default value 300000 Is a state variable no Modelica parameter name T0 Default value 290 Is a state variable no Modelica parameter name H0 Default value 100000 Is a state variable no Modelica parameter name optiontemperature Default value 1 Is a state variable no File name of the model Source Interfacing function SCImodulesscicosblocksmacrosHydraulicsSourcePsci Modelica model SCImodulesscicosblocksmacrosHydraulicsSourcemo palettes 2881 Nome VanneReglante Thermalhydraulic control valve Block Screenshot Contents Thermalhydraulic control valve Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description The VanneReglante block represents a variable orifice control valve The flow rate through the valve is proportional to the valve opening where is the valve opening is the pressure difference and is the flow rate This model is only used for the laminar flow regimes is a constant depending on the valve geometry and mass density of fluid Dialog box Cvmax palettes 2882 Cvmax maximum opening of the valve Properties Type vec of size 1 prho Fluid density Properties Type vec of size 1 Default properties Inputs Modelica variable name C1 Implicit variable Modelica variable name Ouv Explicit variable Outputs Modelica variable name C2 Implicit variable Parameters Modelica parameter name Cvmax Default value 800542 Is a state variable no Modelica parameter name prho Default value 0 Is a state variable no File name of the model VanneReglante Interfacing function SCImodulesscicosblocksmacrosHydraulicsVanneReglantesci Modelica model SCImodulesscicosblocksmacrosHydraulicsVanneReglantemo 20 User defined functions palette palettes 2883 Nome Userdefinedfunctionspal User defined functions palette Block Screenshot Module xcos Description The user defined function contains blocks that allow you to model the component behaviour The output is expressed as a function of the input Blocks cblock C file function CBLOCK New C EXPRESSION Mathematical expression fortranblock Fortran genericblock3 Generic block MBLOCK Modelica generic block PDE 1D PDE block scifuncblockm Scilab function block SUPERf Super block TEXTf Text palettes 2884 Nome CBLOCK New C Block Screenshot Contents New C Palette Description Dialog box Default properties Interfacing function Authors Palette User defined functions palette Description This block creates skeleton of the Ccomputing function It also creates library file and object files palettes 2885 Dialog box simulation function Name of the function to be generated Properties Type str of size 1 is block implicit If yes y is selected it calls implicit solver dasrt else n it calls explicit solver lsodar Properties Type str of size 1 input ports sizes Number of regular input ports Properties Type vec of size 1 output ports sizes Number of regular output ports Properties Type vec of size 1 palettes 2886 input event ports sizes Number of event input ports Properties Type vec of size 1 output events ports sizes Number of event output ports Properties Type vec of size 1 initial continuous state Initial Conditions Properties Type vec of size 1 number of zero crossing surfaces Select to enable zero crossing detection Properties Type vec of size 1 initial discrete state Initial conditions of the discrete states Properties Type vec of size 1 Real parameters vector Real Parameter vector that the function accepts Properties Type vec of size 1 Integer parameters vector Integer Parameter vector that the function accepts Properties Type vec of size 1 initial firing vector A vector Size of this vector corresponds to the number of event outputs The value of the entry specifies the time of the preprogrammed event firing on the output event port If less than zero no event is preprogrammed Properties Type vec of size sum6 direct feedthrough The input to the block at the current time determine the output of the block at the current time This forces the input to feed through to the output as if the system were operating at steadystate Properties Type str of size 1 time dependence Create a signal that specifies the time dependence Properties Type str of size 1 palettes 2887 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function Interfacing function SCImodulesscicosblocksmacrosMiscCBLOCKsci Authors Ramine Nikoukhah INRIA palettes 2888 Nome EXPRESSION Mathematical expression Block Screenshot Contents Mathematical expression Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette User defined functions palette Description The Expression block applies the specified Scilab functions to its input Dialog box number of inputs Block input can be a scalar or vector palettes 2889 Properties Type vec of size 1 scilab expression The Scilab expression applied to the input Properties Type vec of size 1 use zerocrossing Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function evaluateexpr Interfacing function SCImodulesscicosblocksmacrosMiscEXPRESSIONsci Computational function SCImodulesscicosblockssrccevaluateexprc Type 4 Authors Ramine Nikoukhah INRIA palettes 2890 Nome MBLOCK Modelica generic block Block Screenshot Contents Modelica generic block Palette Description Dialog box Default properties Interfacing function Authors Palette User Defined function palette Description The block MBlock provides an easy way to build a xcos block whose behavior is specified by a Modelica program Using this block the user will be able to write and compile Modelica programs in xcos without creating any interfacing function The associated Modelica program of this block can be either given in a file or written in the window opened by the block In order to link this block to other xcos blocks that may be other Modelica blocks the types of block ports as well as their associated variables should be specified palettes 2891 Dialog box Input variables In this filed the ports connected to the left hand side of the block are defined If the port is an explicit port it will be an input port In this case the variable should be declared in the Modelica program as Real If the port is an implicit port the variable desinating this port should be a connector Remind that for implicit port the notion of input and output does not exist and specifying an implicit variable in this filed is just placing the port at the left hend side of the block Input variables types In this filed the type of ports are specified ie I for implicit ports and E for explicit ports The size of the vector of input variables and the vector of inputvectortype should be equal Output variables Similar to the input variables vector the explicit output variables and implicit variables which are displayed at the right hand side of the block are specified in this filed Output variables types The type of variables given in the Output variable vector are specified ie I for implicit ports and E for explicit ports Parameters in Modelica The values of parameters declared in the Modelica program can be overloaded To overload a para meter value the name of parameters are given in this field and their corresponding values are given in the parameter values fields that are displayed in the second dialog box Parameters properties The type of the Modelica parameters For that time being one can parametrize three types of Mo delica variable 0 the parameter is set to be a Modelica parameter variable scalar or vector palettes 2892 1 the parameter is set to be an initial condition of Modelica state variable scalar or vector 2 the parameter is set to be an initial condition of Modelica state variable with the property fixedtrue scalar or vector Function name The Modelica class name is specified in this filed If the Modelica class name is specified without any path or extension an interactive window is opened and the user can write or edit the Modelica program This window is opened each time the user clicks on the block If the Modelica class name is specified with path and mo extension the compiler looks for the file and if it is found the file will be compiled otherwise a window is opened and the user can write the Modelica program This Modelica file will be saved with the given filename in the specified path The next time only inputoutput characteristics of the block can be changed and the Modelica file should be edited with another text editor Parameter values The value of Modelica parameters are given in the Set parameters values dialog box These values that can be scalar or vector can also be defined in the xcos context In order to access the xcos context click on the Diagram menu then click on the Context submenu For instan ce here is an example of overloading of parameters in a Modelica program Parameters vector SpeedPositionLength Parameters properties vector 021 Speed value 120 Position value 00 01 POS Length value 130 121 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function generic palettes 2893 Interfacing function SCImodulesscicosblocksmacrosMiscMBLOCKsci Authors M NajafiA Layec INRIA palettes 2894 Nome SUPERf Super block Block Screenshot Contents Super block Palette Description Default properties Interfacing function Authors Palette User defined functions palette Description This block opens up a new Scicos window for editing a new block diagram This diagram describes the internal functions of the super block Super block inputs and outputs regular or event are designated by special input or output blocks Regular input blocks must be numbered from 1 to the number of regular input ports Regular input ports of the super block are numbered from the top of the block shape to the bottom Regular output ports must be numbered from 1 to the number of regular output ports Regular output ports of the super block are numbered from the top of the block shape to the bottom Event input blocks must be numbered from 1 to the number of event input ports Event input ports of the super block are numbered from the left of the block shape to the right Event output ports must be numbered from 1 to the number of event output ports Event output ports of the super block are numbered from the left of the block shape to the right Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs palettes 2895 port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function super Interfacing function SCImodulesscicosblocksmacrosMiscSUPERfsci Authors Ramine Nikoukhah INRIA palettes 2896 Nome cblock C language Block Screenshot Contents C language Palette Description Dialog box Default properties Interfacing function Authors Palette User defined functions palette Description This block creates skeleton of the C computing function Also it creates library file and object files Dialog box input ports sizes Number of regular input ports Properties Type vec of size 1 palettes 2897 output port sizes Number of regular output ports Properties Type vec of size 1 System parameters vector Number of parameters that this function accepts Properties Type vec of size 1 function name Name of the function to be generated Properties Type str of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function Interfacing function SCImodulesscicosblocksmacrosMisccblocksci Authors Ramine Nikoukhah INRIA palettes 2898 Nome fortranblock Fortran Block Screenshot Contents Fortran Palette Description Dialog box Default properties Interfacing function Authors Palette User defined functions palette Description This block creates skeleton of the FORTRAN computing function Also it creates library file and object files Dialog box input ports sizes Number of regular input ports Properties Type vec of size 1 palettes 2899 output port sizes Number of regular output ports Properties Type vec of size 1 System parameters vector Number of parameters that this function accepts Properties Type vec of size 1 function name Name of the function to be generated Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function Interfacing function SCImodulesscicosblocksmacrosMiscfortranblocksci Authors Ramine Nikoukhah INRIA palettes 2900 Nome genericblock3 Generic block Block Screenshot Contents Generic block Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette User defined functions palette Description The block provides a generic interfacing function but the computational function needs to be defined separately either as a Scilab function or a Fortran or a C function Besides the name of the function user should specify information such as the type whether or not the block contains a direct feedth rough term The function realising computational functions of generic blocks of a Scicos diagram must be saved along with the diagram and loaded or dynamically linked before simulation palettes 2901 Dialog box Simulation function Name of the function to be loaded Properties Type str of size 1 Function type Type of the computational function supported by Scicos Properties Type vec of size 1 palettes 2902 Input ports sizes Number of regular input ports Properties Type mat of size 12 Input ports type Set the datatype of the regular input ports Properties Type vec of size 1 Iutput port sizes Number of regular input ports Properties Type mat of size 12 Output ports type Set the datatype of the regular output ports Properties Type vec of size 1 Input event ports sizes a vector of ones size of event input ports The size of the vector gives the number of event input ports Properties Type vec of size 1 Output events ports sizes a vector of ones size of event output ports The size of the vector gives the number of of event output ports Properties Type vec of size 1 Initial continuous state A column vector of Initial State Conditions Properties Type vec of size 1 Initial discrete state A column vector Initial discrete Conditions Properties Type vec of size 1 Initial object state A Scilab list that defined the initial object state oz Properties Type lis of size 1 Real parameters vector column vector Any parameters used in the block can be defined here as a column vector Properties Type vec of size 1 Integer parameters vector palettes 2903 column vector Any integer parameters used in the block can be defined here as a column vector Properties Type vec of size 1 Object parameters list A Scilab list that defined the list of the Object parameters opar Properties Type lis of size 1 Number of modes Number of Right hand side functions in the system Properties Type vec of size 1 Number of zerocrossings No of zerocrossings Properties Type vec of size 1 Initial firing vector vector Size of this vector corresponds to the number of event outputs The value of the ith entry specifies the time of the preprogrammed event firing on the ith output event port If less than zero no event is preprogrammed Properties Type vec of size sum6 Direct feedthrough character y or n specifies if block has a direct input to output feedthrough Properties Type vec of size 1 Time dependence Time dependance character y or n specifies if block output depends explicitly on time Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 palettes 2904 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function sinblk Interfacing function SCImodulesscicosblocksmacrosMiscgenericblock3sci Computational function SCImodulesscicosblockssrcfortransinblkf Type 4 Authors Alan Layec INRIA Ramine Nikoukhah INRIA palettes 2905 Nome scifuncblockm Scilab function block Block Screenshot Contents Scilab function block Palette Description Dialog box Default properties Interfacing function Computational function Palette User defined functions palette Description This block can realize any type of Scicos block The function of the block is defined interactively using dialogue boxes and in Scilab language During simulation these instructions are interpreted by Scilab the simulation of diagrams that include these types of blocks is slower For more information see Scicos reference manual palettes 2906 Dialog box input ports sizes a scalar Number of regular input ports Properties Type vec of size 1 output port sizes a scalar Number of regular output ports Properties Type vec of size 1 input event ports sizes a scalar Number of input event ports Properties Type vec of size 1 output events ports sizes a scalar Number of output event ports Properties Type vec of size 1 initial continuous state a column vector Properties Type vec of size 1 initial discrete state a column vector palettes 2907 Properties Type vec of size 1 System parameters vector a string c or d CBB or DBB other types are not supported Properties Type vec of size 1 initial firing vector vector Size of this vector corresponds to the number of event outputs The value of the ith entry specifies the time of the preprogrammed event firing on the ith output event port If less than zero no event is preprogrammed Properties Type vec of size sum4 is block always active other dialogues are opened consecutively where used may input Scilab code associated with the computations needed block initialization outputs continuous and discrete state output events date block ending Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function scifunc Interfacing function SCImodulesscicosblocksmacrosMiscscifuncblockmsci Computational function SCImodulesscicossrcfortranscifuncf Type 3 palettes 2908 21 Zero crossing detection palette palettes 2909 Nome Zerocrossingdetectionpal Zero crossing detection palette Block Screenshot Module xcos Description Zero crossing detection blocks are used to detect values crossing of state variables during the simula tion This blocks use the solvers ODE or DAE to do that operation Blocks CLINDUMMYf Dummy GENERALf Zero crossing NEGTOPOSf Threshold negative to positive POSTONEGf Threshold positive to negative ZCROSSf Threshold detection at zero palettes 2910 Nome GENERALf GENERALf title Block Screenshot Contents GENERALf title Palette Description Dialog box Default properties Interfacing function Computational function Palette Zero crossing detection palette Description Add here a paragraph of the function description Dialog box Input size The parameter description 1 Properties Type vec of size 1 Number of event output The parameter description 2 palettes 2911 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function zcross Interfacing function SCImodulesscicosblocksmacrosThresholdGENERALfsci Computational function SCImodulesscicosblockssrcfortranzcrossf Type 1 palettes 2912 Nome NEGTOPOSf Threshold negative to positive Block Screenshot Contents Threshold negative to positive Palette Description Default properties Interfacing function Computational function Authors Palette Zero crossing detection palette Description An output event is generated when the unique input crosses zero with a positive slope Default properties always active no directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function zcross palettes 2913 Interfacing function SCImodulesscicosblocksmacrosThresholdNEGTOPOSfsci Computational function SCImodulesscicosblockssrcfortranzcrossf Type 1 Authors Ramine Nikoukhah INRIA palettes 2914 Nome POSTONEGf Threshold positive to negative Block Screenshot Contents Threshold positive to negative Palette Description Default properties Interfacing function Computational function Authors Palette Zero crossing detection palette Description An output event is generated when the unique input crosses zero with a negative slope Default properties always active no directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function zcross palettes 2915 Interfacing function SCImodulesscicosblocksmacrosThresholdPOSTONEGfsci Computational function SCImodulesscicosblockssrcfortranzcrossf Type 1 Authors Ramine Nikoukhah INRIA palettes 2916 Nome ZCROSSf Threshold detection at zero Block Screenshot Contents Threshold detection at zero Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Zero crossing detection palette Description An output event is generated when all inputs if more than one cross zero simultaneously Dialog box Input size a positive integer Property Type vec of size 1 Default properties always active no palettes 2917 directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function zcross Interfacing function SCImodulesscicosblocksmacrosThresholdZCROSSfsci Computational function SCImodulesscicosblockssrcfortranzcrossf Type 1 Authors Ramine Nikoukhah INRIA 2918 Capítulo 8 Programming xcos Blocks 1 C Computational Functions Programming xcos Blocks 2919 Nome Cmacros Utilities C macros Contents Cmacros Utilities C macros Module Description Inputsoutputs Events Parameters States and work Zero crossing surfaces and modes Authors Module xcos Description The following C macros are avialable by including the file in a C computational function Inputsoutputs Macro Description GetNinblk Get number of regular input port GetInPortRowsblkx Get number of rows first dimension of regular input port number x GetInPortColsblkx Get number of columns second dimension of re gular input port number x GetInPortSizeblkxy Get regular input port size number x y1 for the first dimension y2 for the second dimension GetInTypeblkx Get type of regular input port number x GetInPortPtrsblkx Get regular input port pointer of port number x GetRealInPortPtrsblkx Get pointer of real part of regular input port num ber x GetImagInPortPtrsblkx Get pointer of imaginary part of regular input port number x Getint8InPortPtrsblkx Get pointer of int8 typed regular input port num ber x Getint16InPortPtrsblkx Get pointer of int16 typed regular input port num ber x Getint32InPortPtrsblkx Get pointer of int32 typed regular input port num ber x Programming xcos Blocks 2920 Getuint8InPortPtrsblkx Get pointer of uint8 typed regular input port num ber x Getuint16InPortPtrsblkx Get pointer of uint16 typed regular input port number x Getuint32InPortPtrsblkx Get pointer of uint32 typed regular input port number x GetSizeOfInblkx Get the sizeof of the regular input port number x GetNoutblk Get number of regular output port GetOutPortRowsblkx Get number of rows first dimension of regular output port number x GetOutPortColsblkx Get number of columns second dimension of re gular output port number x GetOutPortSizeblkxy Get regular output port size number x y1 for the first dimension y2 for the second dimension GetOutTypeblkx Get type of regular output port number x GetOutPortPtrsblkx Get regular output port pointer of port number x GetRealOutPortPtrsblkx Get pointer of real part of regular output port num ber x GetImagOutPortPtrsblkx Get pointer of imaginary part of regular output port number x Getint8OutPortPtrsblkx Get pointer of int8 typed regular output port num ber x Getint16OutPortPtrsblkx Get pointer of int16 typed regular output port number x Getint32OutPortPtrsblkx Get pointer of int32 typed regular output port number x Getuint8OutPortPtrsblkx Get pointer of uint8 typed regular output port number x Getuint16OutPortPtrsblkx Get pointer of uint16 typed regular output port number x Getuint32OutPortPtrsblkx Get pointer of uint32 typed regular output port number x GetSizeOfOutblkx Get the sizeof of the regular output port number x Events Macro Description GetNevInblk Get the input event number GetNevOutblk Get number of event output port GetNevOutPtrsblk Get pointer of event output register Parameters Macro Description GetNiparblk Get number of integer parameters Programming xcos Blocks 2921 GetIparPtrsblk Get pointer of the integer parameters register GetNrparblk Get number of real parameters GetRparPtrsblk Get pointer of the real parameters register GetNoparblk Get number of object parameters GetOparTypeblkx Get type of object parameters number x GetOparSizeblkxy Get size of object parameters number x y1 for the first dimension y2 for the second dimension GetOparPtrsblkx Get pointer of object parameters number x GetRealOparPtrsblkx Get pointer of real object parameters number x GetImagOparPtrsblkx Get pointer of imaginary part of object parameters number x Getint8OparPtrsblkx Get pointer of int8 typed object parameters num ber x Getint16OparPtrsblkx Get pointer of int16 typed object parameters num ber x Getint32OparPtrsblkx Get pointer of int32 typed object parameters num ber x Getuint8OparPtrsblkx Get pointer of uint8 typed object parameters num ber x Getuint16OparPtrsblkx Get pointer of uint16 typed object parameters number x Getuint32OparPtrsblkx Get pointer of uint32 typed object parameters number x GetSizeOfOparblkx Get the sizeof of the object parameters number x States and work Macro Description GetNstateblk Get number of continuous state GetStateblk Get pointer of the continuous state register GetDstateblk Get number of discrete state GetNdstateblk Get pointer of the discrete state register GetNozblk Get number of object state GetOzTypeblkx Get type of object state number x GetOzSizeblkxy Get size of object state number x y1 for the first dimension y2 for the second dimension GetOzPtrsblkx Get pointer of object state number x GetRealOzPtrsblkx Get pointer of real object state number x GetImagOzPtrsblkx Get pointer of imaginary part of object state num ber x Getint8OzPtrsblkx Get pointer of int8 typed object state number x Getint16OzPtrsblkx Get pointer of int16 typed object state number x Getint32OzPtrsblkx Get pointer of int32 typed object state number x Getuint8OzPtrsblkx Get pointer of uint8 typed object state number x Programming xcos Blocks 2922 Getuint16OzPtrsblkx Get pointer of uint16 typed object state number x Getuint32OzPtrsblkx Get pointer of uint32 typed object state number x GetSizeOfOzblkx Get the sizeof of the object state number x GetWorkPtrsblkblk Get the pointer of the Work array Zero crossing surfaces and modes Macro Description GetNgblk Get number of zero crossing surface GetGPtrsblk Get pointer of the zero crossing register GetNmodeblk Get number of modes GetModePtrsblk Get pointer of the mode register Authors Alan Layec INRIA Programming xcos Blocks 2923 Nome Cstruct C Block structure of a computational function Contents Cstruct C Block structure of a computational function Module Description Inputsoutputs Events Parameters States and work Zero crossing surfaces and modes Miscallaneous Authors Module xcos Description The C structure of a xcos block defines all the fields to handle data provided by the simulator such inputsoutputs parameters states That structure of type is defined in the file and user must include that header in each computational functions in the form The fields that can be either C pointers or directly data are then accessible via the structure This access is a approach and most of users should prefer the approach for facilities purpose In the current version of xcos the structure is defined Inputsoutputs blocknin Integer that gives the number of regular input ports of the block One cant override the index when reading sizes of input ports in the array and the index when reading data in the array with a C computational function The number of regular input ports can also be got by the use of the C macros blockinsz An array of integers of size that respectively gives the first dimensions the second dimensions and the type of data driven by regular input ports Programming xcos Blocks 2924 Note that this array of size differs from the array and to provide full compatibilty with blocks that only use a single dimension Suppose that you have a block with three inputs the first is an int32 matrix of size 32 the second a single complex number matrix of size 11 and the last a real matrix of size 41 In thescicosmodel of such a block the inputs will be defined and the corresponding field at C computational function level will be coded as Do the difference here in the type numbers defined at the 213 and the type numbers defined at the 841110 The following table gives the corres pondance for all xcos type blockinptr An array of pointers of size nin1 that allow to directly access to the data contained in the regular input matrices Suppose the previous example block with three inputs an int32 matrix of size 32 a complex scalar and a real matrix of size 41 contains three pointers and should be viewed as arrays contained the data for the int32 the real and the complex matrices For ie to directly access to the data the user can use theses instructions One can also use the set of C macros to have the appropiate pointer of the data to handle and to handle number dimensions and type of regular input ports For the previous example that gives Finally note that the regular input port registers are only accessible for reading blocknout Integer that gives the number of regular output ports of the block One cant override the index when reading sizes of output ports in the array and the index when reading data in the array with a C computational function The number of regular output ports can also be got by the use of the C macros blockoutsz An array of integers of size that respectively gives the first dimensions the second dimensions and the type of data driven by regular output ports Note that this array of size differs from the array and to provide full compatibilty with blocks that only use a single dimension Suppose that you have a block with two outputs the first is an int32 matrix of size 32 the second a single complex number matrix of size 11 and the last a real matrix of size 41 In thescicosmodel of such a block the outputs will be defined and the corresponding field at C computational function level will be coded as Do the difference here in the type numbers defined Programming xcos Blocks 2925 at the 213 and the type numbers defined at the 841110 and please report to the previous table to have the correspondence for all xcos type blockoutptr An array of pointers of size nout1 that allow to directly acces to the data contained in the regular output matrices Suppose the previous example block with three outputs an int32 matrix of size 32 a complex scalar and a real matrix of size 41 contains three pointers and should be viewed as arrays contained the data for the int32 the real and the complex matrices For ie to directly access to the data the user can use theses instructions One can also use the set of C macros to have the appropiate pointer of the data to handle and to handle number dimensions and type of regular output ports For the previous example that gives Finally note that the regular output port registers must be only written for 1 Events blocknevprt Integer that gives the event input port number by which the block has been acti vated This number is a binary coding For ie if block have two event inputs ports can take the value 1 if the block has been called by its first event input port the value 2 if it has been called by the second event input port and 3 if it is called by the same event on both input port 1 and 2 Note that can be 1 if the block is internally called One can also retrieve this number by using the C macros blocknevout Integer that gives the number of event output ports of the block also called the length of the output event register One cant override the index when setting value of events in the output event register The number of event output ports can also be got by the use of the C macro blockevout Array of double of size nevout1 corresponding to the output event register That register is used to program date of events during the simulation When setting values in that array you must understand that you give a delay relative to the current time of simulator Programming xcos Blocks 2926 where is the date of the programmed event is the current time in the simulator and the value that must be informed in the output event register For ie suppose that you want generate an event with the first event output port 1ms after each calls of the block then youll use Note that every events generated from output event register will be asynchronous with event coming from event input port even if you set The event output register must be only written for 3 Parameters blocknrpar Integer that gives the length of the real parameter register One cant override the index when reading value of real parameters in the register The total number of real parameters can also be got by the use of the C macro blockrpar Array of double of size nrpar1 corresponding to the real parameter register That register is used to pass real parameters coming from the scilabxcos environment to your block model The C type of that array is or C xcos type Suppose that you have defined the following real parameters in thescicosmodel of a block you can retrieve the previous data in the C computational function with You can also use the C macro to get the pointer of the real parameter register For ie if we define the following in an interfacing function of a xcos block in the corresponding C computational function of that block well use Note that real parameters register is only accessible for reading blocknipar Integer that gives the length of the integer parameter register One cant override the index when reading value of integer parameters in the register The total number of integer parameters can also be got by the use of the C macro blockipar Array of int of size nipar1 corresponding to the integer parameter register That register is used to pass integer parameters coming from the scilabxcos environment to your block model The C type of that array is or C xcos type Suppose that you have defined the following integer parameters in thescicosmodel of a block you can retrieve the previous data in the C computational function with You can also use the C macro to get the pointer of the real parameter register Most of time in the xcos C block libraries the integer register is used to parametrize the length of real parameters For ie if you define the following in a block the array of real parameters parametrized by ipar can be retrieved in the correspondig C computational function with Note that integer parameters register is only accessible for reading blocknopar Integer that gives the number of the object parameters One cant override the index when accessing data in the arrays and in a C computational function Programming xcos Blocks 2927 This value is also accessible via the C macro blockoparsz An array of integer of size nopar2 that contains the dimensions of matrices of object parameters The first column is for the first dimension and the second for the second dimension For ie if we want the dimensions of the last object parameters well use the instructions The dimensions of object parameters can be get with the following C macro with an integer that gives the index of the object parameter blockopartyp An array of integer of size nopar1 that contains the type of matrices of object parameters The following table gives the correspondence for xcos type expressed in Scilab number in C number and also corresponding C pointers and C macros used for The type of object parameter can also be got by the use of the C macro For ie if we want the C number type of the first object parameter well use the following C instructions blockoparptr An array of pointers of size nopar1 that allow to directly acces to the data con tained in the object parameter Suppose that you have defined in the editor a block with the followingopar field inscicosmodel Then we have two object parameters one is an 32bit integer matrix with two rows and two columns and the second is a vector of complex numbers that can be understand as a matrix of size 13 At the C computational function level the instructions will respectively return the values 2123 and the instructions the values 11 and 84 will contain then two pointers and should be viewed as arrays contained data of object parameter as shown in the following figure For ie to directly access to the data the user can use theses instructions One can also use the set of C macros to have the appropiate pointer of the data to handle For the previous example that gives Note that object parameters register is only accessible for reading States and work blocknx Integer that gives the length of the continus state register One cant override the index when reading or writing data in the array or with a C computational function blockx Array of double of size nx1 corresponding to the continuous state register That gives the result of the computation of the state derivative A value of a continuous state is readable for ie the first state with the C instructions Note that on 4 user can write some initial conditions in that register Programming xcos Blocks 2928 The pointer of that array can also be retrieve via the C macro blockxd Array of double of size nx1 corresponding to the derivative of the continuous state register When systems are explicitly given in terms of Ordinary Differential Equations ODE it can be explicitly expressed or implicitly used in the residual vector when systems are expressed in terms of Differantial Algebraic Equations DAE Both systems must be programmed with For ie the Lorentz attractor written as an ODE system with three state variables of the form will be defined blockres Array of double of size nx1 corresponding to Differential Algebraic Equation DAE residual It is used to write the vector of systems that have the following form For ie the Lorentz attractor written as a DAE system with three state variables will be defined blocknz Integer that gives the length of the discrete state register One cant override the index when reading data in the array with a C computational function This value is also accessible via the C macros blockz Array of double of size nz1 corresponding to the discrete state register A value of a discrete state is directly readable for ie the second state with the C instructions Note that the state register should be only written for 4 and 2 The pointer of that array can also be retrieve via the C macro blocknoz Integer that gives the number of the discrete object states One cant override the index when accessing data in the arrays and in a C computational function This value is also accessible via the C macro blockozsz An array of integer of size noz2 that contains the dimensions of matrices of discrete object states The first column is for the first dimension and the second for the second dimension For ie if we want the dimensions of the last object state well use the instructions The dimensions of object discrete states can be get with the following C macro with an integer that gives the index of the discrete object state blockoztyp An array of integer of size noz1 that contains the type of matrices of discrete object states The following table gives the correspondence table for xcos type expressed in Scilab number in C number and also corresponding C pointers and C macros used for The type of discrete object state can also be got by the use of the C macro For ie if we want the C number type of the first discrete object state well use the following C instructions blockozptr An array of pointers of size noz1 that allow to directly acces to the data contained in the discrete object state Suppose that you have defined in the editor a block with the followingodstate field inscicosmodel Then we have two discrete object states one is an 32bit integer matrix with two rows and two Programming xcos Blocks 2929 columns and the second is a vector of complex numbers that can be understand as a matrix of size 13 At the C computational function level the instructions will respectively return the values 2123 and the instructions the values 11 and 84 will contain then two pointers and should be viewed as arrays contained data of discrete object state as shown in the following figure For ie to directly access to the data the user can use theses instructions One can also use the set of C macros to have the appropiate pointer of the data to handle For the previous example that gives Finally note that the discrete objects state should be only written for 4 and 2 blockwork A free pointer to set a working array for the block The work pointer must be firstly allocated when 4 and finally be free in the 5 Then a basic life cyle of that pointer in a C computational function should be Note that if a block use a pointer it will be called with 2 even if the block dont use discrete states The pointer of that array can also be retrieve via the C macro Zero crossing surfaces and modes blockng Integer that gives the number of zero crossing surface of the block One cant override the index when readingwriting data in the array with a C computational function The number of zero crossing surface can also be got by the use of the C macro blockg Array of double of size ng1 corresponding to the zero crossing surface register That register is used to detect zero crossing of state variable during time domain integration Note that it is accessible for writting for 9 The pointer of that array can also be retrieve via the C macro blocknmode Integer that gives the number of mode of the block One cant override the index when readingwriting data in the array with a C computational function The number of mode can also be got by the use of the C macro blockmode Array of integer of size nmode1 corresponding to the mode register That register is used to set the mode of state variable during time domain integration It is typically accessible for writting for 9 The pointer of that array can also be retrieve via the C macro Programming xcos Blocks 2930 Miscallaneous blocktype Integer that gives the type of the computational function For C blocks this number is equal to 4 blocklabel Strings array that allows to retrieve the label of the block Authors Alan Layec INRIA Programming xcos Blocks 2931 Nome Cutils Utilities C functions Contents Cutils Utilities C functions Module Description Authors Module xcos Description The header provides some utilities functions to interact with the simulator in the C computational functions void docoldrestart This function forces the solver to do a cold restart It should be used in situations where the block creates a non smooth signal Note that in most situations non smooth situations are detected by zerocrossings and this function is not needed This block is used in very exceptional situations int getphasesimulation That function returns an integer which says if the simulator is realizing time domain integration It can returns 1 The simulator is on a discrete activation time 2 The simulator is realizing a continuous time domain integration double getscicostime That function returns the current time of simulator int getblocknumber That function returns an integer the block index in the compiled structure Each block in the si mulated diagram have a single index and blocks are numbered from 1 to nblk the total number of blocks in the compiled structure void setblockerrorint Function to set a specific error during the simulation for the current block If it is used then after the execution of the computational function of the block the simulator will end and will return an error message associated to the number given in the integer argument The following calls are allowed setblockerror1 the block has been called with input out of its domain setblockerror2 singularity in a block setblockerror3 block produces an internal error Programming xcos Blocks 2932 setblockerror16 cannot allocate memory in block void endscicossim A very specific function to set the current time of the simulator to the final time integration Only expert user should use this function void setpointerxpropertyint pointer This function set a vector of integer to inform the type algebraic or differential of the continuous state variables of the block void scicosmallocsizet That function must be used to do allocation of scicos pointers inside a C computational function and in particular for 4 for the work pointer void scicosfreevoid p That function must be used to free scicos pointers inside a C computational function and in particular for 5 for the work pointer Authors Alan Layec INRIA Ramine Nikoukhah INRIA 2 Scilab Computational Functions Programming xcos Blocks 2933 Nome scistruct Scicos block structure of a scilab computational function Contents scistruct Scicos block structure of a scilab computational function Module Description Inputsoutputs Events Parameters States Zero crossing surfaces and modes Miscallaneous Authors Module xcos Description A Scicos computational function of type 5 can be realized by the use of a Scilab function That function doesnt really differs from all other scilab function one can use all functions and instructions of the scilab language inside that function to do the computation Such a function must be written in a file with extension sci must be loaded inside scilab by the common loading scilab function and must have two right hand side arguments and one left hand side argument as the following calling sequence When the simulator is calling such a computational function it build a scilab structure in the previous exemple this is the named rhslhs arguments from his own internal C reprensation of a block structure see for more details about the C structure of scicos blocks That scilab structure is a scilab typed list variable that have the following fields Each fields are then accessible inside the scilab computational function by the use of Inputsoutputs blocknin a scalar that gives the number of regular input ports This is a read only data blockinsz a vector of size that gives the dimensions and types of the regular input ports are the first dimensions are the second dimensions are the type of data C coding Programming xcos Blocks 2934 This is a read only data blockinptr a list of size that enclosed typed matrices for regular input ports Each element corres pond to only one regular input port Then ith matrix of the blockinptr list will have the dimensions and the type The data type that can be provided by regular input ports are 1 matrix of real numbers 2 matrix of complex numbers 3 matrix of int32 numbers 4 matrix of int16 numbers 5 matrix of int8 numbers 6 matrix of uint32 numbers 7 matrix of uint16 numbers 8 matrix of uint8 numbers This is a read only data blocknout a scalar that gives the number of regular output ports This is a read only data blockoutsz a vector of size that gives the dimensions and types of the regular output ports are the first dimensions are the second dimensions are the type of data C coding This is a read only data blockoutptr a list of size that enclosed typed matrices for regular output ports Each element correspond to only one regular output port Then ith matrix of the blockoutptr list will have the dimensions and the type The data type that can be provided by regular output ports are 1 matrix of real numbers 2 matrix of complex numbers 3 matrix of int32 numbers 4 matrix of int16 numbers 5 matrix of int8 numbers 6 matrix of uint32 numbers 7 matrix of uint16 numbers 8 matrix of uint8 numbers Values of regular output ports will be saved in theC structure of the block only for 6 and 1 Programming xcos Blocks 2935 Events blocknevprt a scalar given the event input port number binary coding which have activated the block This is a read only data blocknevout a scalar given the number of output event port of the block This is a read only data blockevout a vector of size corresponding to the register of output event Values of output event register will be saved in theC structure of the block only for 3 Parameters blocknrpar a scalar given the number of real parameters This is a read only data blockrpar a vector of size corresponding to the real parameter register This is a read only data blocknipar a scalar given the number of integer parameters This is a read only data blockipar a vector of size correspondig to the integer parameter register This is a read only data blocknopar a scalar given the number of object parameters This is a read only data blockoparsz a matrix of size that respectively gives the first and the second dimension of object parameters This is a read only data blockopartyp a vector of size given the C coding type of data This is a read only data blockopar a list of size given the values of object parameters Each element of can be either a typed matrix or a list Only matrix that encloses numbers of type real complex int32 int16 int8 uint32 uint16 and uint8 are allowed all other types of scilab data will be enclosed in a sublist This is a read only data States blocknz a scalar given the number of discrete state for the block This is a read only data blockz a vector of size corresponding to the discrete state register Values of discrete state register will be saved in theC structure of the block only for 4 6 2 and 5 blocknoz a scalar that gives the number of discrete object state This is a read only data blockozsz a matrix of size that respectively gives the first and the second dimension of discrete object state This is a read only data blockoztyp a vector of size given the C coding type of data blockoz a list of size given the values of discrete object states Each element of can be either a typed matrix or a list Only matrix that encloses numbers of type real complex int32 int16 int8 uint32 uint16 and uint8 are allowed all other types of scilab data will be enclosed in a sublist Values of discrete object state will be saved in theC structure of the block only for 4 6 2 and 5 blocknx a scalar given the number of continuous state for the block This is a read only data blockx a vector of size given the value of the continuous state register Values of the continuous state register will be saved in theC structure of the block only for 4 6 and 2 Programming xcos Blocks 2936 blockxd a vector of size given the value of the derivative continuous state register Values of the derivative continuous state register will be saved in theC structure of the block only for 4 6 0 and 2 blockres a vector of size corresponding to the Differential Algebraic Equation DAE residual Values of that register will be saved in theC structure of the block only for 0 and 10 Zero crossing surfaces and modes blockng a scalar given the number of zero crossing surfaces for the block This is a read only data blockg a vector of size corresponding to the zero crossing register Values of that register will be saved in theC structure of the block only for 9 blocknmode a scalar given the number of mode for the block This is a read only data blockmode a vector of size that corresponds to the mode register Values of that register will be saved in theC structure of the block only for 9 with 1 Miscallaneous blocktype a scalar given the type of the block This is a read only data blocklabel a string given the label of the block This is a read only data Authors Alan Layec INRIA 3 Utilities Functions Programming xcos Blocks 2937 Nome curblock Return the current called xcos block during the simulation Module xcos blkcurblock Parameters blk the current block number in the compiled structure Authors Ramine Nikoukhah INRIA Programming xcos Blocks 2938 Nome getblocklabel Get the label of a scicos block Module xcos labelgetblocklabelblk Parameters blk Integer parameter Set the index of a block in the compiled structure label String parameter Gives the string of the label of the block numbered blk Programming xcos Blocks 2939 Nome getscicosvars Supervisor utility function myvargetscicosvarsstr myvargetscicosvarsstr1str2 Module xcos Description That utility function is used to retrieve working arrays of Scicos simulator and compiler during simu lation It can be used inside a Scilab block to get information of all type of blocks That function is very useful to debug diagrams and to do prototypes of simulations myvargetscicosvarsstr myvargetscicosvarsstr1str2 Parameters strstr1str2 That parameter can be a string or a matrix of string The following entries are allowed x get the continuous state register nx get the length of the continuous state register xptr get the pointers register of the continuous state register zcptr get the pointers register of the zerocrossing surfaces register z get the discrete state register nz get the length of the continuous state register zptr get the pointers register of the discrete state register noz get the number of elements of the discrete object state list oz get the discrete object state list ozsz get the size of the elements of the discrete object state list oztyp get the type of the elements of the discrete object state list ozptr get the pointers register of the discrete object state list rpar get the real parameter register rpptr get the pointers register of the real parameter register ipar get the integer parameter register ipptr get the pointers register of the integer parameter register opar get the object parameter list Programming xcos Blocks 2940 oparsz get the size of the elements of the object parameter list opartyp get the type of the elements of the object parameter list opptr get the pointers register of the object parameter list outtb get the output register inpptr get the pointers register of the number of regular input ports outptr get the pointers register of the number of regular output ports inplnk get the pointers register of the links connected to regular input ports outlnk get the pointers register of the links connected to regular output ports subs not used tevts get the current date register of the agenda evtspt get the current event register of the agenda pointi get the next event to be activated iord get the vector of blocks activated at the start of the simulation oord get the vector of blocks whose outputs affects computation of continuous state derivatives zord get the vector of blocks whose outputs affects computation of zerocrossing surfaces funtyp get the vector of type of computational functions ztyp get the pointers vector for blocks which use zerocrossing surfaces cord get the vector of blocks whose outputs evolve continuously ordclk get the matrix associated to blocks activated by output activation ports clkptr get the pointers vector for output activation ports ordptr get the pointers vector to ordclk designating the part of ordclk corresponding to a given activation critev get the vector of the critical events mod get the vector pointers of block modes nmod get the length of the vector pointers of block modes iz get the register that store pointers of block work izptr get the pointers vector of the register that store C pointers of block work nblk get the number of block outtbptr get the register that store C pointers of outtb Programming xcos Blocks 2941 outtbpsz get the register that store the size of the elements of outtb outtbtyp get the register that store the type of the elements of outtb nlnk get the number of output ncord get the number of blocks whose outputs evolve continuously nordptr get the number of blocks whose outputs evolve by activation iwa nd blocks get a scilab list that contains all block structures contains in the diagram ng get length of the zerocrossing surfaces register g get the zerocrossing surfaces register t0 get the current time of the simulation tf get the final time of the simulation Atol get the integrator absolute tolerance for the numerical solver rtol get the integrator relative tolerance for the numerical solver ttol get the tolerance on time of the simulator deltat get the maximum integration time interval hmax get the maximum step size for the numerical solver nelem get the number of elements in outtb outtbelem get the vector of the number of elements in outtb myvar That output parameter can be an int32 matrix a double matrix or a Tlist This is given by the input parameter See Also DEBUGSCICOS Debug block Scicos Block Authors Alan Layec INRIA Ramine Nikoukhah INRIA Programming xcos Blocks 2942 Nome phasesimulation Get the current simulation phase psimphasesimulation Module xcos Description That function says if the Scicos simulator is realizing the time domain integration psimphasesimulation Parameters psim get the current phase of the simulation 1 The simulator is on a discrete activation time 2 The simulator is realizing a continuous time domain integration Programming xcos Blocks 2943 Nome pointerxproperty Get the type of a continuous time state variable xproppointerxproperty Module xcos Description This function returns a vector that informs the type algebraic or differential of the continuous state variables of a block xproppointerxproperty Parameters xprop The value gives the type of the states 1 an algebraic state 1 a differential state See Also setxproperty Set the type of a continuous time state variable Scilab Function Programming xcos Blocks 2944 Nome scicostime Returns the current time during simulation Module xcos tscicostime Parameters t that is the current simulated time returned in real number Programming xcos Blocks 2945 Nome setblockerror set the block error number setblockerrorn Module xcos Description Function to set a specific error during the simulation for the current block If it is used then after the execution of the computational function of the block the simulator will end and will return an error message associated to the number given in argument setblockerrorn Parameters n an error number The following calls are allowed setblockerror1 the block has been called with input out of its domain setblockerror2 singularity in a block setblockerror3 block produces an internal error setblockerror16 cannot allocate memory in block Authors Alan Layec INRIA Programming xcos Blocks 2946 Nome setxproperty Set the type of a continuous time state variable setxpropertyxprop Module xcos Description This function set a vector to inform the type algebraic or differential of the continuous state variables of a block setxpropertyxprop Parameters xprop The value gives the type of the states 1 an algebraic state 1 a differential state See Also pointerxproperty Get the type of a continuous time state variable Scilab Function 2947 Capítulo 9 Scilab Data Structures 1 Blocks Scilab Data Structures 2948 Nome scicosblock Define a block structure Module xcos block Basic structure that define a xcos block That structure includes fields graphics model gui and doc Size 5 Type scilab list graphics Scilab object including graphical information concerning the features of the block Size 14 Type scilab list model Scilab list that contains the features of the block used for the compilation Size 23 Type Scilab list gui The name of the Scilab GUI function associated with the block Size 1 Type string doc Field used for documentation of the block Size 1 Type string File content SCImodulesscicosmacrosscicosscicosscicosblocksci Scilab Data Structures 2949 Nome scicosgraphics Define a graphics structure Module xcos graphics Scilab object including graphical information concerning the features of the block Size 14 Type scilab list orig Vector xoyo where xo is the x coordinate of the block origin and yo is the y coordinate of the block origin xoyo is the coordinate of downleft point of the block shape Size 2 Type row vector of real sz Vector wh where w is the block width and h the block height Size 2 Type row vector of real flip Set the block orientation If true the input ports are on the left of the box and output ports are on the right If false the input ports are on the right of the box and output ports are on the left Size 1 Type boolean theta Set the angle of the Scicos object This value is in degree and is included in 360360 Size 1 Type real exprs Strings including formal expressions used in the dialog box of the block Scilab Data Structures 2950 Size number of formal expressions Type column vector of strings pin Vector pini is the number of the link connected to the ith regular input port counting from one or 0 if this port is not connected Size number of regular input ports Type column vector of integers pout Vector pouti is the number of the link connected to the ith regular output port counting from one or 0 if this port is not connected Size number of regular output ports Type column vector of integers pein Vector peini is the number of the link connected to the ith event input port counting from one or 0 if this port is not connected Size number of events input ports Type column vector of integers peout Vector peouti is the number of the link connected to the ith event output port counting from one or 0 if this port is not connected Size number of events output ports Type column vector of integers gri Strings including Scilab graphics expressions for customizing the block graphical aspect This field may be set with Icon submenu Size Type column vector of strings id A string including an identification for the block The string is displayed under the block in the diagram Size 1 Type string inimplicit A vector of strings including E or I Scilab Data Structures 2951 E and I stand respectively for explicit and implicit port and this vector indicates the nature of each input port For regular blocks not implicit this vector is empty or contains only E Size nul or number of regular input ports Type column vector of strings outimplicit A vector of strings including E or I E and I stand respectively for explicit and implicit port and this vector indicates the nature of each output port For regular blocks not implicit this vector is empty or contains only E Size nul or number of regular output ports Type column vector of strings File content SCImodulesscicosmacrosscicosscicosscicosgraphicssci Scilab Data Structures 2952 Nome scicosmodel Define a model structure Module xcos model Scilab list that contains the features of the block used for the compilation Size 23 Type Scilab list sim A list containing two elements The first element is a string containing the name of the computa tional function C Fortranor Scilab The second element is an integer specifying the type of the computational function Currently type 4 and 5 are used but older types continue to work to ensure backward compatibility For some older case sim can be a single string and that means that the type is supposed to be 0 Size 2 Type Scilab list in A vector specifying the number and size of the first dimension of regular input ports indexed from top to bottom of the block If no input port exist in The size can be negative equal to zero or positive If a size is less than zero the compiler will try to find the appropriate size If a size is equal to zero the compiler will affect this dimension by added all positive size found in that vector If a size is greater than zero then the size is explicitly given Size number of regular input ports Type column vector of integer numbers in2 A vector specifying the second dimension of regular input ports indexed from top to bottom of the block in with in2 formed then the regular input sizes matrix For compatibility this dimension can stay empty That means that the dimensions of input ports will be in1 The size can be negative equal to zero or positive Scilab Data Structures 2953 If a size is less than zero the compiler will try to find the appropriate size If a size is equal to zero the compiler will affect this dimension by added all positive size found in that vector If a size is greater than zero then the size is explicitly given Size number of regular input ports Type column vector of integer numbers intyp A vector specifying the types of regular input ports Its sizes is equal to the sizes of in The types of regular input ports can be 1 real matrix 2 complex matrix 3 int32 matrix 4 int16 matrix 5 int8 matrix 6 uint32 matrix 7 uint16 matrix 8 uint8 matrix Size number of regular input ports Type column vector of integer numbers out A vector specifying the number and size of the first dimension of regular output ports indexed from top to bottom of the block If no output port exist out The size can be negative equal to zero or positive If a size is less than zero the compiler will try to find the appropriate size If a size is equal to zero the compiler will affect this dimension by added all positive size found in that vector If a size is greater than zero then the size is explicitly given Size number of regular output ports Scilab Data Structures 2954 Type column vector of integer numbers out2 A vector specifying the second dimension of regular output ports indexed from top to bottom of the block out with out2 formed then the regular output sizes matrix For compatibility this dimension can stay empty That means that the dimensions of output ports will be out1 That dimension can be negative equal to zero or positive If a size is less than zero the compiler will try to find the appropriate size If a size is equal to zero the compiler will affect this dimension by added all positive size found in that vector If a size is greater than zero then the size is explicitly given Size number of regular output ports Type column vector of integer numbers outtyp A vector specifying the types of regular output ports Its sizes is equal to the sizes of out The types of regular output ports can be 1 real matrix 2 complex matrix 3 int32 matrix 4 int16 matrix 5 int8 matrix 6 uint32 matrix 7 uint16 matrix 8 uint8 matrix Size number of regular output ports Type column vector of integer numbers evtin A vector specifying the number and sizes of activation inputs Currently activation ports can be only of size one If no event input port exists evtin must be equal to Scilab Data Structures 2955 Size number of input event ports Type column vector of integer numbers evtout A vector specifying the number and sizes of activation outputs Currently activation ports can be only of size one If no event output port exists evtout must be equal to Size number of output event ports Type column vector of integer numbers state Vector containing initial values of continuoustime state Must be if no continuous state Size number of continuoustime state Type column vector of real numbers dstate Vector containing initial values of discretetime state Must be if no discrete state Size number of discretetime state Type column vector of real numbers odstate List containing initial values of objects state Must be list if no objects state Objects state can be any types of scilab variable In the computational function case of type 4 C blocks only elements containing matrix of real complex int32 int16 int8 uint32 uit16 and uint8 will be correctly provided for readindwriting Size number of objects state Type scilab list of scilab objects rpar The vector of floating point block parameters Must be if no floating point parameters Size number of real parameters Type column vector of real numbers ipar Scilab Data Structures 2956 The vector of integer block parameters Must be if no integer parameters Size number of integer parameters Type column vector of integer numbers opar List of objects block parameters Must be list if no objects parameters Objects parameters can be any types of scilab variable In the computational function case of type 4 C blocks only elements containing matrix of real complex int32 int16 int8 uint32 uit16 and uint8 will be correctly provided for reading Size number of objetcs parameters Type list of scilab object blocktype Character that can be set to c or d indifferently for standard blocks x is used if we want to force the computational function to be called during the simulation phase even if the block does not contribute to computation of the state derivative l m and s are reserved Not to be used Size 1 Type Character firing Vector of initial event firing times of size equal to the number of activation output ports see evout It contains output initial event dates Events generated before any input event arises Negative values stands for no initial event on the corresponding port Size number of output event ports Type column vector of real numbers deput Boolean vector depu dept depu true if block is always active output depends continuously of the time dept true if block has direct feedthrough ie at least one of the outputs depends directly not through the states on one of the inputs In other words when the computational function is called with flag 1 the value of an input is used to compute the output Size 2 Scilab Data Structures 2957 Type Boolean vector label String that defines a label It can be used to identify a block in order to access or modify its para meters during simulation Size 1 Type string nzcross Number of zerocrossing surfaces Size Number of zerocrossing surfaces Type column vector of integer numbers nmode Length of the mode register Note that this gives the size of the vector mode and not the total number of modes in which a block can operate in Suppose a block has 3 modes and each mode can take two values then the block can have up to 238 modes Size Number of modes Type column vector of integer numbers equations Used in case of implicit blocks Data structure of type modelica which contains modelica code description if any That list contains four entries model a string given the name of the file that contains the modelica function inputs a colunm vector of strings that contains the names of the modelica variables used as inputs outputs a colunm vector of strings that contains the names of the modelica variables used as outputs parameters a list with two entries The first is a vector of strings for the name of modelica variable names used as parameters and the second entries is a list that contains the value of parameters Names of modelica states can also be informed with parameters In that case a third entry is used to do the difference between parameters and states For ie moparameterslistCvlistCv01 means that C is a parameter0 of value C and v is a state1 with initial value v Scilab Data Structures 2958 Size 5 Type scilab list File content SCImodulesscicosmacrosscicosscicosscicosmodelsci 2 CompilationSimulation Scilab Data Structures 2959 Nome scicoscpr Compiled Scicos structure Module xcos cpr The Scilab object cpr contains the result of the compilation That structure includes fields state sim cor and corinv Size 5 Type scilab list state Scilab typed list of type xcs It contains all the states of the model that is everything than can evolve during the simulation state contains x z oz iz tevts evtspt pointi and outtb Size 9 Type scilab tlist sim Scilab typed list of type scs It contains static arrays coming from the result of the compilation That arrays does not evolve during the simulation Size 33 Type scilab tlist cor It is a list with same recursive structure as scsm Each leaf contains the index of associated block in sim data structure Size number of objects in scsm Type scilab list corinv corinvi is the path of i th block defined in sim data structure in the scsm data structure Size number of blocks in the compiled structre Type scilab list File content SCImodulesscicosmacrosscicosscicosscicoscprsci Scilab Data Structures 2960 Nome scicossim Define a sim structure Module xcos sim Scilab typed list of type scs It contains static arrays coming from the result of the compilation That arrays does not evolve during the simulation Size 33 Type scilab tlist funs A list containing names of the computational functions or scilab functions Size number of blocks Type list of strings andor scilab function xptr A vector pointer to the continuous time state register x The continuoustime state of block i is statexsimxptrisimxptri11 Size number of blocks 1 Type column vector of integers zptr A vector pointer to the discrete time state register z The discretetime state of block i is statezsimzptrisimzptri11 Size number of blocks 1 Type column vector of integers ozptr A vector pointer to the object discrete state register oz The object discrete state of block i is stateozsimozptrisimozptri11 Size number of blocks 1 Type column vector of integers zcptr A vector pointer to the zerocrossing surfaces register That vector gives by block the used number of the zerocrossing Size number of blocks 1 Scilab Data Structures 2961 Type column vector of integers inpptr siminpptri1siminpptri gives the number of regular input ports of the i block inpptri points to the beginning of ith block inputs within the indirection table inplnk Size number of blocks 1 Type column vector of integers outptr simoutptri1simoutptri gives the number of regular ouyput ports of the i block outptri points to the beginning of ith block outputs within the indirection table outlnk Size number of blocks 1 Type column vector of integers inplnk cprsiminplnkcprsiminpptri1j is the index of the link connected to the jth input port of the ith block where j goes from 1 to cprsiminpptri1cprsiminpptri Size total number of regular input port Type column vector of integers outlnk cprsimoutlnkcprsimoutptri1j is the index of the link connected to the jth output port of the ith block where j goes from 1 to cprsimoutptri1cprsimoutptri Size total number of regular output port Type column vector of integers rpar Vector of real parameters that is obtained by concatenating the real parameters registers of all the blocks Size total number of real parameters Type column vector of real numbers rpptr A vector pointer to the real parameters register rpar The real parameters of block i are simrparsimrpptrisimrpptri11 Size number of blocks 1 Type column vector of integer ipar Vector of integer parameters that is obtained by concatenating the integer parameters registers of all the blocks Scilab Data Structures 2962 Size total number of integer parameters Type column vector of integer ipptr A vector pointer to the integer parameters register ipar The integer parameters of block i are simiparsimipptrisimipptri11 Size number of blocks 1 Type column vector of real numbers opar List of object parameters that is obtained by concatenating the list of object parameters of all the blocks Size total number of object parameters Type list of scilab objects opptr A vector pointer to the object parameters list opar The object parameters of block i are simoparsimopptrisimopptri11 Size number of blocks 1 Type column vector of integers clkptr A vector pointer to output activation ports cprsimclkptricprsimclkptri11 gives the number of output event ports of the block i Size number of blocks 1 Type column vector of integers ordptr A vector pointer to ordclk designating the part of ordclk corresponding to a given activation cprsimordptricprsimordptri11 points to the region within ordclk indicates the number of blocks activated by the output event ports numbered i Size number of sources of activation 1 Type column vector of integers execlk Unused Size Type matrix of real ordclk A matrix associated to blocks activated by output activation ports The first column contains the block number and the second the event code by which the block should be called Scilab Data Structures 2963 Size total number of blocks summed by source of activations Type matrix of integers cord A matrix associated to always active blocks The first column contains the block number and the second the event code by which the block should be called Size ncord Type matrix of integers oord Subset of cord Blocks of that matrix have outputs which affect computation of continuous state derivatives Size noord Type matrix of integers zord Subset of zord Blocks of that matrix have outputs which affect computation of zerocrossing sur faces Size nzord Type matrix of integers critev A vector of size equal to the number of activations and containing zeros and ones The value one indicates that the activation is critical in the sense that the continuoustime solver must be cold restarted Size number of source of activation Type column vector of integers nb Number of blocks Note that the number of blocks may differ from the original number of blocks in the diagram because cpass2 may duplicate some conditional blocks Size 1 Type integer ztyp A vector of size equal to the number of blocks A 1 entry indicates that the block may have zerocrossings even if it doesnt in the context of the diagram Usually not used by the simulator Size number of blocks Type column vector of integers Scilab Data Structures 2964 nblk Not used Set to nb Size 1 Type integer ndcblk Not used Size Type integer subscr Not used Size 0 Type empty real funtyp A vector of size equal to the number of blocks indicating the type of the computational function of the block Block type can be 0 through 5 Currently only type 4 C language and type 5 Scilab language computational functions should be used But older blocks can also be used Size number of blocks Type column vector of integer iord A matrix associated to blocks that must be activated at the start of the simulation This includes blocks inheriting from constant blocks and always active blocks Size niord Type matrix of integers labels A string vector of size equal to the number of blocks containing block labels Size numbers of blocks Type column vector of strings modptr A vector pointer to the block modes Size number of blocks 1 Type column vector of integer File content SCImodulesscicosmacrosscicosscicosscicossimsci Scilab Data Structures 2965 Nome scicosstate Define a state structure Module xcos state Scilab typed list of type xcs It contains all the states of the model that is everything than can evolve during the simulation state contains x z oz iz tevts evtspt pointi and outtb Size 9 Type scilab tlist x The continuoustime state register which is obtained by concatenating the continuoustime states of all the blocks Size total of all the size of continuoustime state registers Type column vector of real numbers z The discretetime state register which is obtained by concatenating the discretetime states of all the blocks Size total of all the size of discretetime state registers Type column vector of real number oz The list of the object discretetime state which is obtained by concatenating the object discretetime states of all the blocks Size total of all the size of object state Type list of scilab object iz Vector of size equal to the number of blocks That vector is used to store pointers of the working state register work If a block needs to allocate memory at initialization flag 4 the associated pointer is saved here Size number of blocks Type column vector of real numbers tevts Scilab Data Structures 2966 Vector of size equal to the number of activation sources It contains the scheduled times for pro grammed activations in evtspt Size number of activation sources Type column vector of integers evtspt Vector of size equal to the number of activation sources It is an event scheduler Size number of activation sources Type column vector of integers pointi The number of the next programmed event Size 1 Type integer outtb Scilab list containing all output registers of blocks Each element of that list contains typed ma trixbased data Size number of regular output ports Type list of scilab matrix File content SCImodulesscicosmacrosscicosscicosscicosstatesci 3 Diagram Scilab Data Structures 2967 Nome scicosdiagram Define a scsm structure Module xcos diagram Size 4 Type scilab list props Diagram properties This entry contains various informations such some main diagram initials values This variable is a tlist of type and contains wpar title tol tf context options and doc Size 11 Type Scilab tlist of type objs List of objects included in the Scicos diagram The objects used in scicos areblock link and Text The objects can also be deleted object data structure Deleted object data structure is marked listDeleted Size total number of objects in the diagram Type Scilab tlist of type or Text version A string that gives the version of the Scicos diagram This is used to provide compatibility with old diagram Note that you can get the current version of Scicos by using the entry About scicos in the help menu or by using the function getscicosversion Size 1 Type String File content SCImodulesscicosmacrosscicosscicosscicosdiagramsci Scilab Data Structures 2968 Nome scicosparams Define a param structure Module xcos params Size 11 Type scilab list wpar This vector is not currently used It may be used in the future to code window sizes of the editor Size 6 Type column vector or real title Vector of character strings where the first one is the diagram title and default name of save file name and the second one is the path of the directory of the file name Size 2 Type row vector of strings tol A vector containing simulation parameters including various tolerances used by the solver atol Integrator absolute tolerance for the numerical solver rtol Integrator relative tolerance for the numerical solver ttol Tolerance on time If an integration period is less than ttol the numerical solver is not called deltat Maximum integration time interval If an integration period is larger than deltat the numerical solver is called more than once in such a way that for each call the integration period remains below deltat scale Scilab Data Structures 2969 Realtime scaling the value 0 corresponds to no realtime scaling It associates a Scicos simulation time to the real time in seconds A value of 1 means that each Scicos unit of time corresponds to one second solver Choice of numerical solver The value 0 implies an ODE solver and 100 implies a DAE solver hmax Maximum step size for the numerical solver 0 means no limit Size 7 Type column vector of real tf Final time simulation The simulation stops at this time The default value is 100000 Size 1 Type real context A vector of strings containing Scilab instructions defining Scilab variables to be used inside blocks dialog box as symbolic parameters All valid Scilab instructions can be used and also comments Size number of lines of the context Type column vector of strings void1 unused field Size Type options Scilab object of type scsopt defining graphical properties of the editor such as background color and link color The fields are the following Scilab Data Structures 2970 3D A list with two entries The first one is a boolean indicating whether or not blocks should have 3D aspect The second entry indicates the color in the current colormap to be used to create the 3D effect The default is 33 which corresponds to gray added by Scicos to the standard colormap which contains 32 colors The default value is listt33 Background Vector with two entries background and foreground colors The default value is 81 link Default link colors for regular and activation links These colors are used only at link construction Changing them does not affect already constructed links The default value is 15 which corresponds to black and red if the standard Scilab colormap is used ID A list of two vectors including font number and sizes The default value is 5141 Cmap An n3 matrix containing RGB values of colors to be added to the colormap The default value is 080808 ie the color gray Size 6 Type scilab tlist of type scsopt void2 unused field Size Type void3 unused field Scilab Data Structures 2971 Size Type doc User defined diagram documentation structure Size 1 Type Strings File content SCImodulesscicosmacrosscicosscicosscicosparamssci 4 Links Scilab Data Structures 2972 Nome scicoslink Define a link structure Module xcos link Size 8 Type scilab list xx Vector of x coordinates of the link path A link is defined as a polyline line Size number of points of the link Type column vector of real numbers yy Vector of y coordinates of the link path A link is defined as a polyline line Size number of points of the link Type column vector of real numbers id Character string the link identification Size 1 Type string thick Vector of size two defining line thickness Size 2 Type row vector of integers ct The first entry of this vector designates the color and the second the nature of the link The second entry is 1 for a regular link 1 for an activation link and 2 for an implicit link Size 2 Type row vector of integers from Scilab Data Structures 2973 Vector of size three including the block number port number and port type 0 for output 1 for input at the origin of the link Note that the third entry may be 1 if the link is implicit otherwise it is zero Size 3 Type row vector of integers to Vector of size three including the block number port number and port type 0 for output 1 for input at the destination of the link Note that the third entry may be 1 if the link is implicit otherwise it is zero Size 3 Type row vector of integers File content SCImodulesscicosmacrosscicosscicosscicoslinksci 2974 Capítulo 10 Scilab Utilities Functions Scilab Utilities Functions 2975 Nome buildouttb Build of the sublist cprstateouttb outtbbuildouttblnkszlnktyp Module xcos Description Build an initialized outtb list outtbbuildouttblnkszlnktyp Parameters outtb a list of size n lnksz That parameter gives the size of Scilab object in outtb This matrix of integer or real numbers can have a n2 or 2n size lnktyp That parameters gives the type of Scilab object in outtb 1 double 2 complex 3 int32 4 int16 5 int8 6 uint32 7 uint16 8 uint8 else double This matrix of integer or real numbers can have a n1 or 1n size Authors Alan Layec INRIA Scilab Utilities Functions 2976 Nome createpalette Palette generator routinesIntFunc createpalettePath Module xcos Description This function generates a palette if Path is a string indicating the directoy in which the interfacing functions of the blocks are to be found If Path is not present or if it is t then standard scicos palettes are regenerated If f then only IntFunc list of interfacing functions is returned List of routines is empty in this case routinesIntFunc createpalettePath Parameters Path a string given the directory path that contains Scicos blocks interfacing functions routines a vector of strings that contains names of computational functions used in scicos blocks IntFunc a vector of strings that contains names of interfacing functions used in scicos blocks File content SCImodulesscicosmacrosscicosutilscreatepalettesci Scilab Utilities Functions 2977 Nome getscicosversion Get the current Scicos version scicosver getscicosversion Module xcos Description This function is used to know the current version number of Scicos scicosver getscicosversion Parameters scicosver a string given the current number version of Scicos Example Get the scicos version getscicosversion File content SCImodulesscicosmacrosscicosutilsgetscicosversionsci Authors Alan Layec INRIA Scilab Utilities Functions 2978 Nome scicosdebug Set the level of the Scicos debugging scicosdebuglevel levelscicosdebug Module xcos Description This Scilab function is used to set the debug level of a Scicos simulation One can used it in the Calc mode of the Scicos editor or as an instruction in a Scilab block or in an interfacing function scicosdebuglevel levelscicosdebug Parameters level setget the current level of the Scicos simulation debugging 0 no debugging 1 light debugging information printout 2 more information printout and execution of Debug Block if any in diagram 3 silent debugging mode no information printout and execution of Debug Block if any in diagram See Also DEBUGSCICOS Debug block Scicos Block Authors Alan Layec INRIA Ramine Nikoukhah INRIA Scilab Utilities Functions 2979 Nome var2vec Transform a scilab variable in a vector of double vecvar2vecvar Module xcos Description var2vec vec2var functions are used inside the interfacing functions of Scilab blocks to give the possibility to the user to handle Scilab objects with the real parameter rpar and with the discrete state register z vecvar2vecvar Parameters var Input parameter Can be any types of Scilab objects vec Output parameter A vector of real numbers Example alistcos112 a a1 cos a2 11 2 bvar2veca b 4244314 1273313 8488314 2122314 4941324 8488314 5093313 2122314 2122314 9881324 11 2 See Also vec2var Transform a vector of double in a scilab variable Scilab Function Scilab Utilities Functions 2980 Nome vec2var Transform a vector of double in a scilab variable varvec2varvec Module xcos Description var2vec vec2var functions are used inside the interfacing functions of Scilab blocks to give the possibility to the user to handle Scilab objects with the register of real parameters rpar and with the discrete state register z varvec2varvec Parameters vec Input parameter A vector of real numbers var Output parameter Can be any types of Scilab objects Example alistcos112 a a1 cos a2 11 2 bvar2veca b 4244314 1273313 8488314 2122314 4941324 8488314 5093313 2122314 2122314 9881324 11 2 cvec2varb c c1 cos c2 11 2 Scilab Utilities Functions 2981 See Also var2vec Transform a scilab variable in a vector of double Scilab Function 2982 Nome xcos Block diagram editor and GUI for the hybrid simulator xcosfilename xcosscsmlist Module xcos Description Xcos is a visual editor for constructing models of hybrid dynamical systems Invoking Xcos with no argument opens up an empty Xcos window Models can then be assembled loaded saved compiled simulated using GUI of Xcos Xcos serves as an interface to the various block diagram compilers and the hybrid simulator scicosim xcosmydiagramxcos Parameters filename a character string containing the path of the diagram file cos cosf or xcos extension If no input argument is used an empty diagram is opened default name Untitled scsmlist a Xcos diagram structure after edition Example Open a new diagram xcos xcos Load a diagram xcos SCIscicosdemosbouncecosf Load a structure loadmondiagrcos xcosscsm See Also scicosim Scicos batch simulation function Scilab Function scicossimulate Function for running xcos simulation in batch mode Scilab Function Menu entries 2983 Nome Menuentries Editor menu entries File menu FileNew Clicking on the New menu item loads an empty diagram in the active editor xcos window If the previous content of the window is not saved it will be lost With this menu you can open a new diagram or a new palette FileOpen Ctrlo Select the Open menu item to load an ASCII or binary file containing a saved block diagram or palette A dialog box allows user choosing the file FileSave Ctrls Select the save menu item to save the block diagram in a binary file already selected by a previous select the Save As menu item If you select this menu item and you have never clicked on the Save As menu item the diagram is saved in the current directory as windownamecos where windowname is the name of the window appearing on top of the window usually Untitled or Super Block The cos binary files are machine independent FileSave As CtrlShifts Select the Save As menu item to save the block diagram or palette in a file A dialog box allows choosing the file which must have a cos or cosf extension The diagram takes the name of the file Menuentries 2984 without the extension If extension is cosf an ASCII formatted save is performed instead of binary save Formatted save is slower than regular save FileExport Ctrle This menu is used to export a figure of the current xcos diagram The export can be done directly in postscript format or done first in a graphic window to export in a second step in all the format that scilab can provide FileRecent Files Via this menu you have a quick access to the recent opened files FilePrint Ctrlp Print the current diagram onto a printer FileClose Ctrlw If several diagram are opened the Close action closes the current diagram If only one diagram is opened the Close action will close xcos and closes the viewport and palettes windows if these windows are opened FileQuit Ctrlq If several diagram are opened the Quit action will close xcos and closes the viewport and palettes windows if these windows are opened It will close all the opened diagram Edit menu Menuentries 2985 EditUndo Ctrlz Select the Undo menu item to undo the last edit operation EditRedo Ctrly Select the Redo menu item to redo the last undo edit operation EditCut Ctrlx Cut is used to remove the selected object from the diagram and keep a copy in the clipboard if the object is a block EditCopy Ctrlc Copy is used to place a copy of the selected object in the clipboard if the object is a block EditPaste Ctrlv Paste places the object in the Clipboard in the diagram EditDelete Delete To delete blocks or a links select first the Delete menu item then click successively on the selected objects with left button When you delete a block all links connected to it are deleted as well EditSelect all Ctrla Select all the blocks in the current diagram EditInvert selection Invert the current selection EditBlock Parameters Ctrlb Open the block configuration window for the current selected block EditRegion to superblock Convert a selection of blocks into a superblock Menuentries 2986 View menu ViewZoom in Ctrlplus When you select this menu item the diagram is zoomed in by a factor of 10 ViewZoom out Ctrlminus When you select this menu item the diagram is zoomed out by a factor of 10 ViewFit diagram to view When you select this menu item the diagram is fit to the size of the current window ViewNormal 100 Resize the work area so as the diagram fits onto this work area ViewPalette browser Open the palette browser ViewDiagram browser Displays a window which lists all the blocks of a diagram and print some informations related to the scsm structure of the blocks ViewViewport Menuentries 2987 Display the viewport The viewport is an image of the current diagram With the viewport you can move the working area onto a piece of the diagram You can zoom and unzoom part of a diagram Above you have an example of the viewport which is used to zoom on a part of a diagram and on the right the xcos window displays the zoomed part of the diagram ViewDetails Displays a window which lists all the selected blocks of a diagram and print some informations related to the scsm structure of these blocks Menuentries 2988 Simulation menu SimulationSetup In the main Xcos window clicking on the Setup menu item invokes a dialog box that allows you to change integration parameters Final integration time integration ends at this time it always starts from 0 Real time scaling forces real time simulation by setting xcos unit of time to 1 second Absolute and relative error tolerances solver properties Time tolerance the smallest time interval for which the ode solver is used to update continuous states Max integration time interval the maximum time interval for each call to solver it must be reduced if the error message too many calls is encountered Solver choose the numerical solver to be used Max step size max time step taken by solver Execution trace and Debug Set Xcos in debug mode Allows diagram debugging SimulationSet Context When you select this menu item you obtain a dialog to enter Scilab instructions for defining symbo lic Xcos parameters used in block definitions or to do whatever you want These instructions will be Menuentries 2989 evaluated each time the diagram is loaded If you change the value of a symbolic Xcos parameters in the context all the blocks are updated Eval is performed SimulateCompile Select the Compile menu item to compile the block diagram This menu item need never be used since compilation is performed automatically if necessary before the beginning of every simulation Run menu item Normally a new compilation is not needed if only system parameters and internal states are modified In some cases however these modifications are not correctly updated and a manual compilation may be needed before a Restart or a Continue Please report if you encounter such a case Simulatestart Select the Run menu item to start the simulation If the system has already been simulated a dialog box appears where you can choose to Continue Restart or End the simulation SimulationStop You may interrupt the simulation by clicking on the stop button change any of the block para meters and continue the simulation with the new values Format menu FormatRotate Ctrlr Rotate allows to turn a block on the Left Each time the block is turned left his angle is decresead of 45 degrees If no blocks or many blocks are selected this is the block under the mouse pointer which turns Menuentries 2990 FormatFlip Ctrlf To reverse the positions of the regular inputs and outputs of a block placed on its sides select the Flip menu item first and then click on the selected block This does not affect the order nor the position of the input and output event ports which are numbered from left to right FormatShowHide shadow This menu allows to select 3D shape for selected blocks and associated parameters FormatAlign Blocks When you select several blocks it is possible to align them vertically Top Bottom and Middle and horizontally Left Right Center Format Border Color This menu allows to change the border color FormatLine Color This menu allows to change the line color FormatLink Style Menuentries 2991 This menu allows to the the style of the link Horizontal Straight Vertical FormatDiagram background This menu allows to change the background color FormatGrid This menu allows to activate desactivate the grid Using a grid it is easier to place a block on the working area Tools menu ToolsCode generation This menu allows to generate the simulation code associated with a discrete time Super Block The code generation is obtained simply by selecting this menu and then the desired Super Block If the Super Block satisfies the required conditions a dialog box pops up to ask for a block name a directory where to put the generated files and for optional libraries requested by the linker Given this information the code is generated compiled and linked with Scilab The Super Block is auto Menuentries 2992 matically replaced by a new block which implements the generated code It is then possible to run the modified diagram The code for standalone use is also generated Help menu HelpXcos Help This menu opens the help browser HelpBlock Help To get help on a Xcos object a block select first an object a block and then click on this menuHelp menu item and then on the selected object or menu item HelpXcos Demos The Demos menu allows to open some examples of Xcos diagram HelpAbout Xcos About xcos item display the current version of Xcos and gives some useful informations Parte LVI scilab editor 2994 Name editerror opens in scilab editor the source of the last recorded error answ editerrorclearerror Parameters clearerror boolean if true the error condition is cleared if false it is kept as in lasterror answ a string stating which source file is open or why no file was open Description This function opens in scilab editor the source of the function which caused the last recorded error This function works only for functions which are defined in libraries ie not for internal functions nor with functions defined online nor loaded with individual exec or getd This is since Scilab presently retains only the path to libraries and not to individual function sources Correspondance between the function name foo and function filename foosci is tacitly assumed Examples acosh abc editerror See Also lasterror errclear Authors Enrico Segre Allan CORNET 2995 Name Editor Embedded Scilab text editor editor editorfile editorfile1 file2 editorfile linenumber editorfile1 file2 linenumber1 linenumber2 Parameters file a string the file we want to open file1 file2 a matrix of string files we want to open linenumber an integer number of the line we want to highlight at the opening of the file linenumber1 linenumber2 a matrix of integer each opened file will have its corresponding line highlighted Description Editor is an embedded Scilab text editor It can be started with a fresh text buffer pressing the Editor button on top of the main Scilab window or from Scilab command line with the instruction editor or it can open specific files if invoked with any of the calling sequences above whithout any parameters it opens editor with a blank file The same invocation adds further files to an already opened Editor Keyboard shortcuts are defined for most possible editing actions and reported by the menu entries editor can be started in the following ways By the menu Applications Choose Applications Editor From the command line editor editorfile editorfile1 file2 editorfile linenumber editorfile1 file2 linenumber1 linenumber2 Menus and Shortcuts Menu File Editor 2996 Commande Shortcut Description New CTRLN Open a new file Open CTRLO Open an existing file Recent Files Display files recently opened Save CTRLS Save a file Save as CTRLMAJS Save a file as Page Setup Setup page for printing Print Preview CTRLMAJP Open a print preview window Print CTRLP Print a file Close CTRLW Close a file Quit CTRLQ Close Editor Menu Edit Commande Shortcut Description Undo CTRLZ Undo action Redo CTRLY Redo action Cut CTRLX Cut the selection Copy CTRLC Copy the selection Paste CTRLV Paste the selection Select All CTRLA Select the entire document Delete Delete the selection Comment Selection CTRLD Comment selected lines Uncomment Selection CTRLMAJD Uncomment selected lines Tabify Selection TAB Tabify selected lines Untabify Selection MAJTAB Untabify selected lines Indent CTRLI Indent selected lines Menu Search Commande Shortcut Description FindReplace CTRLF Find andor Replace an element Goto line CTRLG Goto line Menu View Commande Shortcut Description ShowHide Toolbar Option to show or hide the tool bar Highlight current line CTRLJ Highlight the current line Line Numbers CTRLB Display documents line num bers Set Colors Color settings for documents Set Fonts Font settings for documents Reset default font Reset default font settings for documents Editor 2997 Menu Document Commande Shortcut Description Syntaxe Type Syntaxe type settings default type is Scilab Encoding Encoding settings default type is UTF8 Encoding Colorize Colorize the document Auto Indent Activate the automatic indenta tion Menu Execute Commande Shortcut Description Load Into Scilab CTRLL Load the entire document into the Scilab console Evaluate Selection Load the selection into the Scilab console Execute Into Scilab CTRLE If the file exist execute the con tent of the file Remarks Document The default text colourisation is the Scilabs syntaxe colourisation The autoindent mode indent a line according to Scilabs syntaxe after a return action Bugs You can reported bugs in the Bugzilla httpbugzillascilaborg There are still a few bugs that we are trying to fix details can be found in the given link by filtering entries with the Editor element Examples editor without parameters editor editor with a file name editorSCImodulestimemacrosdatenumsci editor with a matrix of files name editorSCImodulestimemacrosdatenumsciSCImodulestimemacrosdatevecsci editor with a file name and the line number to highlight editorSCImodulestimemacrosdatenumsci 5 editor with a matrix of files name and the corresponding matrix of lines to highlight the files name matrix and the lines to highlight matrix should have the same size editorSCImodulestimemacrosdatenumsciSCImodulestimemacrosdatevecsci 510 Author Sylvestre KOUMAR Parte LVII API Scilab 3000 Índice 11 Scilab Gateway API 3001 1 How to 3001 CheckColumn 3023 CheckDimProp 3024 CheckDims 3025 CheckLength 3026 CheckLhs 3027 CheckRhs 3028 CheckRow 3029 CheckSameDims 3030 CheckScalar 3032 CheckSquare 3033 CheckVector 3034 CreateListVarFrom 3035 CreateListVarFromPtr 3038 CreateVar 3041 FindOpt 3043 FirstOpt 3045 GetListRhsVar 3047 GetRhsVar 3049 GetType 3051 IsOpt 3052 Lhs 3054 LhsVar 3055 NumOpt 3057 OverLoad 3059 Rhs 3061 Scierror 3062 Scilab C Types 3063 getoptionals 3065 istk 3067 scitypes 3068 sciprint 3071 stk 3072 12 listmanagement 3073 Boolean reading Scilab gateway 3074 Boolean writing Scilab gateway 3086 Boolean sparse reading Scilab gateway 3090 Boolean sparse writing Scilab gateway 3102 Create List Scilab gateway 3106 Double reading Scilab gateway 3110 Double writing Scilab gateway 3122 Get child item Scilab gateway 3126 Item Number Scilab gateway 3129 Integer reading Scilab gateway 3132 Integer writing Scilab gateway 3144 Pointer reading Scilab gateway 3149 Pointer writing Scilab gateway 3161 Polynomial reading Scilab gateway 3165 Polynomial writing Scilab gateway 3177 Sparse reading Scilab gateway 3181 Sparse writing Scilab gateway 3193 String reading Scilab gateway 3197 String writing Scilab gateway 3209 3001 Capítulo 11 Scilab Gateway API 1 How to Scilab Gateway API 3002 Name Calling a scilab function macros from a C gateway Calling a scilab function macros from a C interface Calling a scilab function macros from a C interface WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead When you write a interface with scilab you can need to call another function directly from your function You can pass a pointer on scilab function to your function The source files of this example are stored in the directory examplescallscifunction How to use this example exec callscifunctionsce launch scilab v callscifunc3012scilabfoo you pass a pointer on a scilab function scilabfoo macro to your function callscifunc C2Fscifunction calls another scilab function here scilabfoo You need to indicate position of the first element Rhs in the Scilab memory pointer on scilab function number of Lhs output of scilab function called number of Rhs input of scilab function called The script callscifunctionsce used to build and load the C interface into Scilab is the following filesscicallscifuncc Defines the list of file ilibbuildcallscifunccallscifuncscicallscifuncfiles Build the files and creates the loader exec loadersce function r scilabfooxy r x y endfunction v callscifunc3012scilabfoo dispresult stringv v callscifunc300120scilabfoo dispresult stringv ulink unload the dynamic library The file scicallscifuncc is the following include stackch include Scierrorh include localizationh Scilab Gateway API 3003 int scicallscifuncchar fname int m1 0 n1 0 l1 0 int m2 0 n2 0 l2 0 int m3 0 n3 0 l3 0 int rm1 0 rn1 0 rl1 0 int mout 1 nout 1 lout 0 double v1 0 v2 0 r 0 int positionFirstElementOnStackForScilabFunction 0 int numberOfRhsOnScilabFunction 0 int numberOfLhsOnScilabFunction 0 int pointerOnScilabFunction 0 CheckRhs33 CheckLhs11 if GetType1 scimatrix Scierror999s Wrong type for input argument d A real expected fname1 return 0 GetRhsVar1 MATRIXOFDOUBLEDATATYPE m1 n1 l1 if m1 n1 n1 1 v1 stkl1 else Scierror999s Wrong size for input argument d A scalar expected fname1 return 0 if GetType2 scimatrix Scierror999s Wrong type for input argument d A real expected fname2 return 0 GetRhsVar2 MATRIXOFDOUBLEDATATYPE m2 n2 l2 if m2 n2 n2 1 v2 stkl2 else Scierror999s Wrong size for input argument d A scalar expected fname2 return 0 if GetType3 scicfunction Scierror999s Wrong type for input argument d A scilab function expected fname3 return 0 get pointer on external function here scilabfoo GetRhsVar3 EXTERNALDATATYPE m3 n3 l3 Scilab Gateway API 3004 r scilabfoox y rhs eq 2 lhs eq 1 Position first element in the Scilab memory to use by Scilab Function v callscifunc300120scilabfoo On stack 300 is on Top position 1 120 second position scilabfoo third position we want to pass 300 120 to scilab Function First position is here 1 positionFirstElementOnStackForScilabFunction 1 numberOfRhsOnScilabFunction 2 numberOfLhsOnScilabFunction 1 pointerOnScilabFunction l3 r scilabfoox y Scifunction call a scilab function ScifunctionpositionFirstElementOnStackForScilabFunction pointerOnScilabFunction numberOfLhsOnScilabFunction numberOfRhsOnScilabFunction result r is now on position positionFirstElementOnStackForScilabFunction on stack GetRhsVar1 MATRIXOFDOUBLEDATATYPE rm1 rn1 rl1 r stkrl1 CreateVarRhs1 MATRIXOFDOUBLEDATATYPE mout nout lout stklout r LhsVar1 Rhs 1 return 0 The main function in this C file is Scifunction It allows to call a Scilab function inside a C interface See Also CheckLhs CheckRhs stk LhsVar GetType Scierror Rhs Lhs scitypes Scilab Gateway API 3005 Nome How to access a matrix How to access a matrix using the C gateway functions Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The goal is to get a matrix of doubles send to a function written in C For this we will wrote a C gateway function in which we will retrieve the matrix we will perform some simple steps in this C function First we will get an access to the matrix in the Scilab memory We will perform some simple operations on the matrix in this example we will multiply by 2 each elements of the matrix We will return the result to Scilab This example is available in the directory SCImodulescoreexamplesex1 The C function include stackch int scimultiplybytwochar fname int minvar ninvar linvar int moutvar noutvar loutvar int irow jcol double pMatrix NULL First access to the input variable a matrix of doubles GetRhsVar1 MATRIXOFDOUBLEDATATYPE minvar ninvar linvar Create the returned variable a matrix of doubles moutvar minvar noutvar ninvar CreateVar2 MATRIXOFDOUBLEDATATYPE moutvar noutvar loutvar pMatrix stklinvar Perform some simple operations on the matrix forirow0 irowminvar irow forjcol0 jcolninvar jcol pMatrixirow jcol moutvar 2 pMatrixirow jcol minvar Return the output variable LhsVar1 2 return 0 Scilab Gateway API 3006 This file must be saved as multiplybytwoc The main thing to highlight is that to build a C gateway function we need to include the header stack ch In this header we find the prototypes and macros of the main C gateway functions To be able to build and link such a C function to scilab we need to write a Scilab script which will compile this C function and then create a loader script which will link the C function to a Scilab function The builder script This is the buildersce must be run from this directory lines0 ilibname libmultiplybytwo files multiplybytwoc libs table multiplybytwo scimultiplybytwo ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags This file must be saved as buildersce This script will tell Scilab which files must be compiled here its multiplybytwoc what will be the name of the shared library here its libmultiplybytwo and which C symbol will be linked to a Scilab function here we will link the scimultiplybytwo C symbol to the Scilab function multiplybytwo To build this function we just need to to exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce The script loadersce is normally automatically built by buildersce Testing our new function We now write a simple example to test our new function A 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Scilab Gateway API 3007 B multiplybytwoA dispB The script must be saved as testsce Lets run our scripts and see what is the result exec buildersce Generate a gateway file Generate a loader file Generate a Makefile ilibgenMake Copy compilation files Makefile libtool to TMPDIR ilibgenMake Copy multiplybytwoc to TMPDIR ilibgenMake Copy libmultiplybytwoc to TMPDIR ilibgenMake Modification of the Makefile in TMPDIR Running the makefile exec loadersce Shared archive loaded Link done exec testsce 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 This simple function has produced a new matrix which corresponds to the matrix transmitted as an input argument and for which each element of the matrix has been multiplied by 2 Rebuilding a gateway function Lets imagine that our gateway function has already been build and we would like to make some changes in our function multiply by 3 instead of 2 How do we perform such a changes without restarting Scilab First we need to list all the dynamic libraries which has been loaded into Scilab The can be done using the linkshow function linkshow Number of entry points 1 Shared libraries 0 1 libraries Entry point libmultiplybytwo in shared library 0 ans 0 Here in our current Scilab session only 1 dynamic library has been loaded This library has a reference number For our library its 0 Now that we know the reference number of our library we are able to unload this library using the function ulink0 0 is the reference number of our library Scilab Gateway API 3008 perform some modification in the source code of our C gateway function replace multiply by 2 by 3 rebuild the C gateway function exec buildersce load the modified C gateway function into scilab exec loadersce This is what is done is the following example ulink0 exec buildersce Generate a gateway file Generate a loader file Generate a Makefile ilibgenMake Copy compilation files Makefile libtool to TMPDIR ilibgenMake Copy multiplybytwoc to TMPDIR ilibgenMake Copy libmultiplybytwoc to TMPDIR ilibgenMake Modification of the Makefile in TMPDIR Running the makefile exec loadersce Shared archive loaded Link done exec testsce 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 See Also GetRhsVar Scilab C Types CreateVar LhsVar stk ilibbuild link ulink Scilab Gateway API 3009 Nome How to check parameters how to check parameter send to an interface using the C gateway functions Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The goal is to get a set of parameters via a set of C gateway functions and then to perform some checks in the C function This example is available in the directory coreexamplescheckproperties The C function include stackch include sciprinth int scicheckproperties1char fname int m1 n1 l1 int m2 n2 l2 int m3 n3 l3 int m4 n4 l4 int m5 n5 l5 CheckRhs55 CheckLhs01 Getting first argument GetRhsVar1 d m1 n1 l1 CheckVector1m1n1 Check that first argument is a vector CheckLength1m1n14 Check vector length Getting second argument GetRhsVar2 d ampm2 ampn2 ampl2 CheckRow2m2n2 Checks that second argument is a row vector CheckColumn can also be used CheckDimProp12 m1 n1 n2 Check compatibility beetween arg 1 and arg 2 We want m1n1 n2 Getting third argument GetRhsVar3 d m3 n3 l3 CheckSameDims13m1n1m3n3 Checks that arg 1 and arg3 have same dimensions Scilab Gateway API 3010 Getting fourth argument GetRhsVar4dm4n4l4 CheckScalar4m4n4 arg 4 must be scalar Getting fourth argument GetRhsVar5dm5n5l5 CheckSquare5m5n5 square matrix CheckDims5m5m555 check dimensions LhsVar10 return 0 We must be careful on the scilab name function 8 chars max int scicheckproperties2char fname int m1n1l1 CheckRhs11 CheckLhs01 switchVarType1 case 1 GetRhsVar1 d m1 n1 l1 sciprint1 is a scalar matrix break case 10 GetRhsVar1 c m1 n1 l1 sciprint1 is a string break case 5 sciprint1 is a sparse trying to overload OverLoad1 LhsVar1 0 return 0 This file must be saved as checkpropertiesc The main thing to highlight is that to build a C gateway function we need to include the header stack ch In this header we find the prototypes and macros of the main C gateway functions We also need to include sciprinth because we use the sciprint function Scilab Gateway API 3011 To be able to build and link such a C function to Scilab we need to write a Scilab script which will compile this C function and then create a loader script which will link the C function to a Scilab function The builder script This is the buildersce must be run from this directory lines0 ilibname libcheckproperties files checkpropertiesc libs table checkproperties1 scicheckproperties1 chprop2 scicheckproperties2 We must be careful when we choose a scilab function name in case of overloading We Scilab name function must be 8 char max ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags This file must be saved as buildersce This script will tell Scilab which files must be compiled here its checkpropertiesc what will be the name of the shared library here its libcheckproperties and which C symbol will be linked to a Scilab function here we will link the scicheckproperties1 C symbol to the Scilab function checkproperties1 For the other C function we must be careful on the name of the Scilab function we will choose Because this function will be overloading the current overloading process of Scilab works only on Scilab primitives Scilab function wrote in C which have a name which is maximum 8 char wide For this function we will link the scicheckproperties2 C symbol to the Scilab function chprop2 To build this function we just need to to exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce The script loadersce is normally automatically built by buildersce Testing our new function We now write a simple example to test our new functions Scilab Gateway API 3012 checks arguments compatibility checkproperties112343456678990rand55 first argument can have different types chprop2122 chprop2foo overload case deffspchprop2spdispsparse overloaded chprop2sparse123 tests which give an error message with checkproperties1 try checkproperties112343456678990rand55 catch displasterror end try checkproperties112343456678990rand55 catch displasterror end try checkproperties112343456678990rand55 catch displasterror end try checkproperties1123434566789rand55 catch displasterror end try checkproperties112343456678990rand44 catch displasterror end The script must be saved as checkpropertiessce Lets run our scripts and see what is the result exec buildersce Génère un fichier gateway Génère un fichier loader Génère un Makefile Makelib Exécute le makefile Compilation de checkpropertiesc Scilab Gateway API 3013 Construction de la bibliothèque partagée soyez patient exec loadersce Bibliothèque partagée chargée Link done exec checkpropertiessce 1 is a scalar matrix 1 is a string 1 is a sparse trying to overload sparse overloaded checkproperties1 Les paramètres first et third a des dimensions incompatibles 1x4 4x1 checkproperties1 second paramètre devrait être un vecteur ligne checkproperties1 Les paramètres first et third a des dimensions incompatibles 4x1 1x4 checkproperties1 fourth paramètre devrait être un scalaire checkproperties1 Argument numéro 5 na pas les bonnes dimensions 44 55 attendues See Also GetRhsVar CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckDimProp CheckLength CheckSameDims CheckSquare OverLoad ilibbuild Scilab Gateway API 3014 Nome How to create and access a list How to create and access a list using the C gateway functions Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The goal is to get a mtlist to get some elements stored in that this and to send a new mtlist using a function written in C For this we will wrote two C gateway function in which we will retrieve the mtlist and we will create a new mtlist The C function access to a mtlist This example is available in SCImodulescoreexampleprintlist Lets initialize a mlist in Scilab A mlistmytypevar1var2a string1 2 3 4 This mlist is of type mytype typeofAmytype and it has 2 elements Avar1 which is equal to a string Avar2 which is equal to 1 2 3 4 We now create a C function called sciprintlist which will print the elements stored in the list include stackch include sciprinth int sciprintlistchar fname int mlistin nlistin llistin int mtype ntype int mvar1 nvar1 lvar1 int mvar2 nvar2 lvar2 char LabelList NULL CheckRhs11 We accept only 1 parameter GetRhsVar1mmlistinnlistinllistin Get a mlist Get the type and the name of the variables the first element of the mlist GetListRhsVar11SmtypentypeLabelList if strcmpLabelList0mytype0 sciprinterror you must ship a mlist or type mytype return 0 Get the first variable a string GetListRhsVar12cmvar1nvar1lvar1 Scilab Gateway API 3015 sciprintvar1 s cstklvar1 Get the second variable a double matrix GetListRhsVar13dmvar2nvar2lvar2 sciprintvar2 f f f f stklvar20 stklvar21 stklvar22 stklvar23 return 0 To be able to build and link such a C function to scilab we need to write a Scilab script which will compile this C function and then create a loader script which will link the C function to a Scilab function The C file is available in the example directory It is named printlistc The builder script This is the buildersce must be run from this directory lines0 ilibname libprintlist files printlistc libs table printlist sciprintlist ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags programlisting paraThis file must be saved as builderscepara paraThis script will tell Scilab which files must be compiled here its printlistc what will be the name of the shared library here its libprintlist and which C symbol will be linked to a Scilab function here we will link the sciprintlist C symbol to the Scilab function printlistpara paraTo build this function we just need to topara programlisting role CDATA exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce Scilab Gateway API 3016 The script loadersce is normally automatically built by buildersce Lets test our new function exec buildersce exec loadersce A mlistmytypevar1var2a string1 2 3 4 printlistA The C function creation of a mtlist This example is available in SCImodulescoreexamplecreatelist We now write a simple example to test our new function to create a mtlist A createlist dispA First lets write the C function include stackch include stringh int scicreatelistchar fname int mlistout nlistout int mvar1 nvar1 lvar1 llistvar1 int mvar2 nvar2 lvar2 llistvar2 int mmlist nmlist lmlist The labels of our mlist static const char ListLabels mylistvar1var2 First we create the variables using a classical way The size of the Scilab variables mvar1 1 nvar1 strlena string1 a null terminated string mvar2 2 nvar2 2 A 2x2 double matrix mmlist 3 nmlist 1 A mlist with 3 elements Creation of the Scilab variables Avar1 CreateVar1 c mvar1 nvar1 lvar1 Avar2 CreateVar2 d mvar2 nvar2 lvar2 A CreateVar3 m mmlist nmlist lmlist We store values in the create variables The matrix will be stored in Avar2 stklvar20 1 stklvar21 2 stklvar22 3 stklvar23 4 Scilab Gateway API 3017 The string will be stored in Avar1 strncpycstklvar1a string0nvar1 mlistout 3 nlistout 1 now affect the variable to the mlist The labels it corresponds to A mlistmylistvar1var2 CreateListVarFromPtr3 1 S mlistout nlistout ListLabels The value stored in Avar1 it corresponds to A a string CreateListVarFrom3 2 c mvar1 nvar1 llistvar1 lvar1 The value stored in Avar2 it corresponds to A 1 23 4 CreateListVarFrom3 3 d mvar2 nvar2 llistvar2 lvar2 We return only the mlist which has been created at position 3 LhsVar1 3 return 0 Some important comments related to the CreateVarPosmm n l function When called on a mlist only the m parameter is taken in account the n parameter is not used So be careful mlist 3 nlist 1 CreateVar1 m mlist nlist llist creates a mlist with 3 elements but mlist 1 nlist 3 CreateVar1 m mlist nlist llist creates a mlist with only 1 element Another important thing when we create a list element using CreateListVarFrom it is not recommen ded to access the created variable using for example stkllistvar2 because CreateListVarFrom performs type transformation on the list variables The builder script This is the buildersce must be run from this directory lines0 ilibname libcreatelist files createlistc libs table createlist scicreatelist ldflags Scilab Gateway API 3018 cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags This file must be saved as buildersce This script will tell Scilab which files must be compiled here its createlistc what will be the name of the shared library here its libcreatelist and which C symbol will be linked to a Scilab function here we will link the scicreatelist C symbol to the Scilab function createlist To build this function we just need to to exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce The script loadersce is normally automatically built by buildersce Lets test our new function exec buildersce exec loadersce A createlist disptypeofA dispgetfield1A dispAvar1 dispAvar2 See Also GetRhsVar GetListRhsVar CreateVar CreateListVarFrom CreateListVarFromPtr LhsVar stk ilibbuild Scilab Gateway API 3019 Nome How to deal with optional parameters how to deal with optional parameters send to an interface using the C gateway functions Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The goal is to get a set of optional parameters via a C gateway and then to perform some checks in the C function number of optional parameters does an optional parameters exists etc This example is available in the directory coreexamplesoptionalparameters The C function include stackch int ex2cdouble a int ma int na double b int mb int nb int i fori0imanai ai 2ai fori0imbnbi bi 3bi return0 int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 default values if optional arguments are not given v199 and v23 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts Scilab Gateway API 3020 sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername iopos Rhs if opts0position1 iopos opts0position iopos opts0m 1 opts0n 1 opts0type d CreateVaropts0position opts0type opts0m opts0n opts0l stkopts0l 990 if opts1position1 iopos opts1position iopos opts1m 1 opts1n 1 opts1type d CreateVaropts1position opts1type opts1m opts1n opts1l stkopts1l 3 ex2cstkopts0lopts0mopts0n stkopts1lopts1mopts1n return the first argument unchanged then v1 and v2 LhsVar1 1 LhsVar2 opts0position LhsVar3 opts1position return 0 This file must be saved as optionalparametersc The main thing to highlight is that to build a C interface function we need to include the header stack ch In this header we find the prototypes and macros of the main C interface functions We also need to include sciprinth because we use the sciprint function To be able to build and link such a C function to scilab we need to write a Scilab script which will compile this C function and then create a loader script which will link the C function to a Scilab function The builder script This is the buildersce must be run from this directory Scilab Gateway API 3021 lines0 ilibname liboptionalparameters files optionalparametersc libs table optionalparameters scioptionalparameters ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags This file must be saved as buildersce This script will tell Scilab which files must be compiled here its optionalparametersc what will be the name of the shared library here its liboptionalparameters and which C symbol will be linked to a Scilab function here we will link the scioptionalparameters C symbol to the Scilab function optionalparameters To build this function we just need to to exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce The script loadersce is normally automatically built by buildersce Testing our new function We now write a simple example to test our new functions Example with optional argument specified with the argvalue syntax abc ex12cx1 v1 arg1 v2 arg2 arg1 default value 99 arg2 default value 3 only v1 and v2 are recognized as optional argument names the return value are a x1 b 2v2 c 3v2 abc optionalparameterstest dispa a b stringb c stringc abc optionalparameterstestv11020 dispa a b stringb c stringc abc optionalparameterstestv11020v28 dispa a b stringb c stringc Scilab Gateway API 3022 abc optionalparameterstestv28v110 dispa a b stringb c stringc The script must be saved as optionalparameterssce Lets run our scripts and see what is the result exec buildersce Génère un fichier gateway Génère un fichier loader Génère un Makefile Makelib Exécute le makefile Compilation de optionalparametersc Construction de la bibliothèque partagée soyez patient exec loadersce Bibliothèque partagée chargée Link done exec optionalparameterssce number of optional parameters 0 first optional parameters 2 FindOptv1 0 FindOptv2 0 a test b 198 c 9 number of optional parameters 1 first optional parameters 2 FindOptv1 2 FindOptv2 0 parameter 2 is optional v1 a test b 20 c 9 a test b 40 c 9 number of optional parameters 2 first optional parameters 2 FindOptv1 2 FindOptv2 3 parameter 2 is optional v1 parameter 3 is optional v2 a test b 20 c 24 a test b 40 c 24 number of optional parameters 2 first optional parameters 2 FindOptv1 3 FindOptv2 2 parameter 2 is optional v2 parameter 3 is optional v1 a test b 20 c 24 See Also GetRhsVar CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckDimProp CheckLength CheckSameDims CheckSquare OverLoad ilibbuild Scilab Gateway API 3023 Name CheckColumn C interface function which checks if a parameter send to the C function is a column vector or not CheckColumnStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the argument for which we want to perform the check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a column vector or not You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function takes one input parameters and prints the integer correspon ding to the type of the variable sent as parameter in the Scilab console If the test fails we return from the C interface and an adequate error message is printed in the Scilab console include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckColumn1m1n1 Check that first argument is a column vector return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3024 Name CheckDimProp C interface function which checks the comatibility between 2 arguments send to the C function CheckColumnStackPosvar1StackPosvar2expression Parameters StackPosvar1 the position in the Scilab memory of the first parameter for which we want to perform the check input parameter StackPosvar2 the position in the Scilab memory of the second variable for which we want to perform the check input parameter expression a boolean expression which represent the size check we want to perform Description C interface function which checks the compatibility between 2 arguments send to the C function You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 int m2 n2 l2 CheckRhs22 GetRhsVar1 d m1 n1 l1 GetRhsVar2 d m2 n2 l2 Check compatibility beetween arg 1 and arg 2 We want m1n1 n2 CheckDimProp12 m1 n1 n2 return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckLength CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3025 Name CheckDims C interface function which checks if a parameter send to the C function has the required dimensions CheckDimsStackPosmvarnvarmrequirednrequired Parameters StackPos the position in the Scilab memory of the parameter for which we want to know the type input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory input parameter nvar the number of columns of the parameter at position StackPos in the Scilab memory input para meter mrequired the required number of lines input parameter nrequired the required number of columns input parameter Description C interface function which checks if a parameter send to the C function has the required dimensions You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckDims1m1n114 Check that argument is a 1x4 matrix return 0 See Also CheckColumn CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3026 Name CheckLength C interface function which checks the length of a vector send as a parameter to the C function CheckLengthStackPosmvarmrequired Parameters StackPos the position in the Scilab memory of the parameter for which we want to check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory input parameter mrequired the required number of lines input parameter Description C interface function which checks the length of a vector send as a parameter to the C function You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckLength1m1n14 Check that vector has 4 elements return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDim Prop CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3027 Name CheckLhs C macro which checks the number of output arguments present in the calling Scilab function CheckLhsnbminparamsnbmaxparams Parameters nbminparams the minimum number of output arguments which must be present in the calling Scilab function nbmaxparams the maximum number of output arguments which must be present in the calling Scilab function Description C macro which checks the number of output arguments present in the calling Scilab function You must include stackch to benefit from this function If the number of arguments is not between nbminparams and nbmaxparams we quit the C inter face return 0 and an error is returned in the Scilab console Since CheckLhs is doing a return 0 within the gateway function it is important to call this macro before any memory allocation in order to avoid any memory leak WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C gateway function checks for a number of output arguments which must be between 2 and 3 include stackch int scimychecklhschar fname CheckLhs23 return 0 Now some functions testing this interface AB mychecklhs OK 2 output arguments ABC mychecklhs OK 3 output arguments A mychecklhs ERROR 1 output argument ABCD mychecklhs ERROR 4 output arguments See Also CheckRhs Scilab Gateway API 3028 Name CheckRhs C macro which checks the number of input arguments present in the calling Scilab function CheckRhsnbminparamsnbmaxparams Parameters nbminparams The minimum number of input arguments which must be present in the calling Scilab function nbmaxparams the maximum number of input arguments which must be present in the calling Scilab function Description C macro which checks the number of input arguments present in the calling Scilab function You must include stackch to benefit from this function If the number of input arguments is not between nbminparams and nbmaxparams we quit the C interface return 0 and an error is returned in the Scilab console Since CheckRhs is doing a return 0 within the gateway function it is important to call this macro before any memory allocation in order to avoid any memory leak WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C gateway function checks for a number of input arguments which must be bet ween 2 and 3 include stackch int scimycheckrhschar fname CheckRhs23 return 0 Now some functions testing this interface mycheckrhsAB OK 2 output arguments mycheckrhsABC OK 3 output arguments mycheckrhsA ERROR 1 output argument mycheckrhsABCD ERROR 4 output arguments See Also CheckLhs Scilab Gateway API 3029 Name CheckRow C interface function which checks if a parameter send to the C function is a row vector or not CheckRowStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the parameter for which we want to know the type input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a row vector or not You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckRow1m1n1 Check that first argument is a row vector return 0 See Also CheckColumn CheckDims CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3030 Name CheckSameDims C interface function which checks if two parameters send to the C function have the same size CheckSameDimsStackPosvar1StackPosvar2mvar1nvar1mvar2nvar2 Parameters StackPosvar1 the position in the Scilab memory of the first parameter for which we want to perform the check input parameter StackPosvar2 the position in the Scilab memory of the second parameter for which we want to perform the check input parameter mvar1 the number of lines of the parameter at position StackPosvar1 in the Scilab memory nvar1 the number of columns of the parameter at position StackPosvar1 in the Scilab memory mvar2 the number of lines of the parameter at position StackPosvar2 in the Scilab memory nvar2 the number of columns of the parameter at position StackPosvar2 in the Scilab memory Description C interface function which checks if two parameters send to the C function have the same size You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function takes one input parameters and prints the integer correspon ding to the type of the variable sent as parameter in the Scilab console include stackch int scicheckpropertieschar fname int m1 n1 l1 int m2 n2 l2 CheckRhs22 GetRhsVar1 d m1 n1 l1 GetRhsVar2 d m2 n2 l2 CheckSameDims12m1n1m2n2 Check that both vectors have the same size Scilab Gateway API 3031 return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDim Prop CheckLength CheckSquare How to check parameters Scilab Gateway API 3032 Name CheckScalar C interface function which checks if a parameter send to the C function is a scalar or not CheckScalarStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the parameter for which we want to perform the check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a scalar or not You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function takes one input parameters and prints the integer correspon ding to the type of the variable sent as parameter in the Scilab console If the test fails we return from the C interface and an adequate error message is printed in the Scilab console include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckScalar1m1n1 Check that first argument is a scalar return 0 See Also CheckColumn CheckDims CheckRow CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3033 Name CheckSquare C interface function which checks if a parameter send to the C function is a square matrix or not CheckSquareStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the parameter for which we want to perform the check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a square matrix or not You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckSquare1m1n1 Check that first argument is a square matrix return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDim Prop CheckLength CheckSameDims How to check parameters Scilab Gateway API 3034 Name CheckVector C interface function which checks if a parameter send to the C function is a vector column or row or not CheckVectorStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the parameter for which we want to perform the check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a vector column or row or not You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckVector1m1n1 Check that first argument is a vector column or row return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3035 Nome CreateListVarFrom a C interface function which allows to create a new Scilab parameter in a mtlist CreateListVarFromStackPosType mrows ncols lstacklistpos lstackpos Parameters StackPos the rank of the parameter to be created input parameter Type the Scilab type of the parameter to be created input parameter Can be see Scilab C Type for more informations STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the matrix to be created input parameter ncols the number of columns of the matrix to be created input parameter lstacklistpos the position in the Scilab memory of the created variable in the listoutput parameter lstackpos the position in the Scilab memory of the created variable input parameter Description A C interface function which allows to create a new Scilab variable in a mtlist Scilab Gateway API 3036 WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples include stackch include stringh int scicreatelistchar fname int mlistout nlistout int mvar1 nvar1 lvar1 llistvar1 int mvar2 nvar2 lvar2 llistvar2 int mmlist nmlist lmlist The labels of our mlist static const char ListLabels mylistvar1var2 First we create the variables using a classical way The size of the Scilab variables mvar1 1 nvar1 strlena string1 a null terminated string mvar2 2 nvar2 2 A 2x2 double matrix mmlist 3 nmlist 1 A mlist with 3 elements Creation of the Scilab variables Avar1 CreateVar1 c mvar1 nvar1 lvar1 Avar2 CreateVar2 d mvar2 nvar2 lvar2 A CreateVar3 m mmlist nmlist lmlist We store values in the create variables The matrix will be stored in Avar2 stklvar20 1 stklvar21 2 stklvar22 3 stklvar23 4 The string will be stored in Avar1 strncpycstklvar1a string0nvar1 mlistout 3 nlistout 1 now affect the variable to the mlist The labels it corresponds to A mlistmylistvar1var2 CreateListVarFromPtr3 1 S mlistout nlistout ListLabels The value stored in Avar1 it corresponds to A a string CreateListVarFrom3 2 c mvar1 nvar1 llistvar1 lvar1 The value stored in Avar2 it corresponds to A 1 23 4 CreateListVarFrom3 3 d mvar2 nvar2 llistvar2 lvar2 We return only the mlist which has been created at position 3 LhsVar1 3 return 0 Scilab Gateway API 3037 This example is available in SCImodulescoreexamplecreatelist See Also Scilab C Type istk LhsVar CreateVar Scilab Gateway API 3038 Nome CreateListVarFromPtr a C interface function which allows to create a new Scilab parameter from a pointer in a mtlist CreateListVarFromStackPos Type mrows ncols lstacklistpos void Pointer Parameters StackPos the rank of the parameter to be created input parameter Type the Scilab type of the parameter to be created input parameter Can be see Scilab C Type for more informations STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the matrix to be created input parameter ncols the number of columns of the matrix to be created input parameter lstacklistpos the position in the Scilab memory of the created parameter in the list output parameter Pointer the pointer to the data area input parameter Description A C interface function which allows to create a new Scilab parameter from a pointer in a mtlist Scilab Gateway API 3039 WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples include stackch include stringh int scicreatelistchar fname int mlistout nlistout int mvar1 nvar1 lvar1 llistvar1 int mvar2 nvar2 lvar2 llistvar2 int mmlist nmlist lmlist The labels of our mlist static const char ListLabels mylistvar1var2 First we create the variables using a classical way The size of the Scilab variables mvar1 1 nvar1 strlena string1 a null terminated string mvar2 2 nvar2 2 A 2x2 double matrix mmlist 3 nmlist 1 A mlist with 3 elements Creation of the Scilab variables Avar1 CreateVar1 c mvar1 nvar1 lvar1 Avar2 CreateVar2 d mvar2 nvar2 lvar2 A CreateVar3 m mmlist nmlist lmlist We store values in the create variables The matrix will be stored in Avar2 stklvar20 1 stklvar21 2 stklvar22 3 stklvar23 4 The string will be stored in Avar1 strncpycstklvar1a string0nvar1 mlistout 3 nlistout 1 now affect the variable to the mlist The labels it corresponds to A mlistmylistvar1var2 CreateListVarFromPtr3 1 S mlistout nlistout ListLabels The value stored in Avar1 it corresponds to A a string CreateListVarFrom3 2 c mvar1 nvar1 llistvar1 lvar1 The value stored in Avar2 it corresponds to A 1 23 4 CreateListVarFrom3 3 d mvar2 nvar2 llistvar2 lvar2 We return only the mlist which has been created at position 3 LhsVar1 3 return 0 Scilab Gateway API 3040 This example is available in SCImodulescoreexamplecreatelist See Also Scilab C Type istk LhsVar CreateVar Scilab Gateway API 3041 Nome CreateVar a C gateway function which allows to create a new Scilab parameter CreateVarStackPos Type mrows ncols lstackpos Parameters StackPos The rank of the parameter to be created input argument Type The Scilab C Type of the parameter to be created input argument STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the matrix to be created input argument ncols the number of columns of the matrix to be created input argument lstackpos the position in the Scilab memory of the created parameter output argument Description A C gateway function which allows to create a new Scilab parameter WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples Scilab Gateway API 3042 include stackch int scimyoneschar fname int mrow ncol lpos mrow 1 ncol 1 We create a scalar CreateVar1 MATRIXOFINTEGERDATATYPE mrow ncol lpos istklpos 1 LhsVar1 1 return 0 See Also Scilab C Type istk LhsVar Scilab Gateway API 3043 Name FindOpt C gateway function find the position of an optional argument given its name Pos FindOptvarname opts Parameters varname the name of the optional parameter opts a C list of optional parameters typedef struct rhsopts int position stack position 1 if not present char name the name of the variable char type a Scilab type like d representing the type of the variable int mn the size of the variable unsigned long int l a pointer to the Scilab stack rhsopts Pos the rank of the optional parameter if it has been found in the parameters sent to the C function 0 otherwise Description A C gateway function which find the position of an optional argument given its name You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding Scilab Gateway API 3044 nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3045 Name FirstOpt C gateway function which returns the position of the first optional parameter Pos FirstOpt Parameters Pos the position of the first optional parameter Rhs 1 if no optional parameters have been given to the function Description A C gateway function which returns the position of the first optional parameter You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts Scilab Gateway API 3046 if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3047 Nome GetListRhsVar a C gateway function which allows to access a parameter stored in a mtlist trans mitted to a Scilab function GetListRhsVarStackPosListPos Type mrows ncols lstackpos Parameters StackPos the rank of the mtlist to be accessed input parameter ListPos the rank in the list of the parameter to be accessed input parameter Type the Scilab type of the parameter to be accessed input parameter Can be see Scilab C Type for more informations STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the accessed parameter output parameter ncols the number of columns of the accessed parameter output parameter lstackpos the position on the stack of the accessed parameter output parameter Description A C gateway function which allows to access a parameter stored in a mtlist transmitted to a Scilab function Scilab Gateway API 3048 WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples In this example the function has one input parameter It gets a mlist and the prints some informations related to the content of the mlist include stackch include sciprinth int sciprintlistchar fname int mlistin nlistin llistin int mtype ntype int mvar1 nvar1 lvar1 int mvar2 nvar2 lvar2 char LabelList NULL CheckRhs11 We accept only 1 parameter GetRhsVar1mmlistinnlistinllistin Get a mlist Get the type and the name of the variables the first element of the mlist GetListRhsVar11SmtypentypeLabelList if strcmpLabelList0mytype0 sciprinterror you must ship a mlist or type mytype return 0 Get the first variable a string GetListRhsVar12cmvar1nvar1lvar1 sciprintvar1 s cstklvar1 Get the second variable a double matrix GetListRhsVar13dmvar2nvar2lvar2 sciprintvar2 f f f f stklvar20 stklvar21 stklvar22 stklvar23 return 0 This example is available in SCImodulescoreexampleprintlist See Also Scilab C Type istk LhsVar Scilab Gateway API 3049 Nome GetRhsVar a C gateway function which allows to access an argument transmitted to a Scilab func tion GetRhsVarStackPos Type mrows ncols lstackpos Parameters StackPos The rank of the variable to be accessed input argument Type The Scilab C Type of the parameter to be accessed input argument STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the accessed parameter output argument ncols the number of columns of the accessed parameter output argument lstackpos the position in the Scilab memory of the accessed parameter output argument Description A C gateway function which allows to access a argument transmitted to a Scilab function WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Scilab Gateway API 3050 Examples In this example the function has two input arguments the number of columns first argument the number of lines second argument The goal of this function is to created a matrix of integers equal to 1 include stackch include stringh int scimyoneschar fname int mparam1 nparam1 lparam1 int mparam2 nparam2 lparam2 int moutrow noutcol loutpos int i int pOutPos NULL GetRhsVar1 MATRIXOFINTEGERDATATYPE mparam1 nparam1 lparam1 GetRhsVar2 MATRIXOFINTEGERDATATYPE mparam2 nparam2 lparam2 We create a matrix of ints equal to 1 moutrow istklparam1 The first dimension of the matrix to be created is stored in the first input parameter noutcol istklparam2 The second dimension of the matrix to be created is stored in the second input parameter CreateVar3 MATRIXOFINTEGERDATATYPE moutrow noutcol loutpos pOutPos istkloutpos Get a pointer to the area allocated by CreateVar a pointer to an integer fori0imoutrownoutrowi pOutPosi 1 A concise way to write the preceding line of code fori0imoutrownoutrowi istkloutposi 1 LhsVar1 3 We return the 3rd Scilab variable of our gateway return 0 See Also Scilab C Type istk LhsVar Scilab Gateway API 3051 Name GetType C gateway function which returns the type of a parameter in the Scilab memory SciType GetTypeStackPos Parameters StackPos the position on the Scilab memory of the parameter for which we want to know the type input argument SciType the type defined in the scitypes enum which you can find in stackch of the parameter at position StackPos in the Scilab memory Description GetType is a C gateway function which returns the type of a parameter in the Scilab memory You must include stackch to benefit from this function WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples In this example the C gateway function takes one input argument and prints the integer corresponding to the type of the variable sent as argument in the Scilab console include stackch include sciprinth int scimygettypechar fname sciprintThe type of the first argument is d GetType1 return 0 See Also sciprint scitypes Scilab Gateway API 3052 Name IsOpt C gateway function which checks if a parameter is optional and returns the name of the parameter Res IsOptPosbuffername Parameters Pos the position in the Scilab memory of the parameter to be checked input parameter buffername an array of char of size csiz which correspond to the maximum length of a Scilab variable in which the name of the parameter will be copied if the position Pos is optional output parameter Res 1 if Pos has an optional parameter 0 otherwise Description C gateway function which checks if a parameter is optional and returns the name of the parameter You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 Scilab Gateway API 3053 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3054 Name Lhs A C gateway function which provides the number of output arguments present in the calling Scilab function nbparams Lhs Parameters nbparams the number of output arguments present in the calling Scilab function Description Lhs provides a C gateway function which provides the number of output arguments present in the calling Scilab function You must include stackch to benefit from this function Note Lhs means Left Hand Side WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C gateway function can take several output arguments and prints in the Scilab console the integer corresponding to the number of output arguments detected in the calling Scilab function include stackch include sciprinth int scimylhschar fname sciprintThe number of output arguments is d Lhs return 0 See Also sciprint Rhs Scilab Gateway API 3055 Nome LhsVar a C gateway function which specifies which parameters created inside the C gateway will be returned as an output argument into Scilab LhsVarRankPos RankVar Parameters RankPos as integer providing the rank of the output argument RankVar the rank of the parameter created inside the C gateway to be returned as an Scilab output argument Description A C gateway function which specifies which variables created inside the C interface will be returned as an output argumen into Scilab WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples This example takes a matrix of doubles as input and returns the number of lines first output argument the number of rows second output argument We create an intermediate Scilab parameter which will handle an integer but will neither be used nor returned as an output argument TODO insert an example in the Scilab language include stackch int scimysizedoublechar fname int minrow nincol linpos int moutlinesrow noutlinescol loutlinespos int moutcolumnsrow noutcolumnscol loutcolumnspos int mnop nnop lnop GetRhsVar1 MATRIXOFDOUBLEDATATYPE minrow nincol linpos moutlinesrow 1 noutlinescol 1 We create a scalar moutcolumnsrow 1 noutcolumnscol 1 We create a scalar mnop 1 nnop 1 We create a scalar CreateVar2 MATRIXOFINTEGERDATATYPE moutlinesrow noutlinescol loutlinespos CreateVar3 MATRIXOFINTEGERDATATYPE mnop nnop lnop CreateVar4 MATRIXOFINTEGERDATATYPE moutcolumnsrow noutcolumnscol loutcolumnspos istkloutlinespos minrow the outlinespos parameter handles the number of lines of the matrix sent as argument istklnop 1 store a mere value but will neither be used nor returned to Scilab Scilab Gateway API 3056 istkloutcolumnspos nincol the outcolumnspos parameter handles the number of columns of the matrix sent as argument LhsVar1 2 We set the parameter 2 as an output argument LhsVar2 4 We set the parameter 4 as an output argument return 0 See Also Scilab C Type istk CreateVar GetRhsVar Scilab Gateway API 3057 Name NumOpt C gateway function which returns the number of optional parameters sent to a C function Res NumOpt Parameters Res the number of optional parameters detected Description A C gateway function which returns the number of optional parameters sent to a C function You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername Scilab Gateway API 3058 sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3059 Name OverLoad C gateway function which tells Scilab to look for another overloaded function OverLoadStackPos Parameters StackPos the position in the Scilab memory of the parameter for which we want to take into account for the overloading process input argument Description A C gateway function which tells Scilab to look for another overloaded function Scilab then appends to the name of the function a prefix like sp if the parameter taken into account is sparse and look for the overloaded function You must include stackch to benefit from this function Be careful with the Scilab name of the function Indeed the current overloading process of Scilab works only on Scilab primitives Scilab function wrote in C which must have a Scilab name which is maximum 8 char wide WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function takes one input parameters and prints the integer correspon ding to the type of the variable sent as parameter in the Scilab console include stackch include sciprinth int scicheckproperties2char fname int m1n1l1 CheckRhs11 CheckLhs01 switchVarType1 case scimatrix GetRhsVar1 d m1 n1 l1 sciprint1 is a scalar matrix break case scistrings GetRhsVar1 c m1 n1 l1 sciprint1 is a string break case scisparse sciprint1 is a sparse trying to overload OverLoad1 LhsVar1 0 Scilab Gateway API 3060 return 0 programlisting paraThe buildersce script look like thispara programlisting role exampleCDATA This is the buildersce must be run from this directory lines0 ilibname libcheckproperties files checkpropertiesc libs table chprop2 scicheckproperties2 We must be careful when we choose a scilab function name in case of overloading We Scilab name function must be 8 char max ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags And now an example of use of this new function chprop2122 chprop2foo overload case deffspchprop2spdispsparse overloaded chprop2sparse123 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckDimProp CheckLength CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3061 Name Rhs A C gateway function which provides the number of input arguments present in the calling Scilab function nbparams Rhs Parameters nbparams the number of input arguments present in the calling Scilab function Description A C gateway function which provides the number of input arguments present in the calling Scilab function You must include stackch to benefit from this function Note Rhs means Right Hand Side WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function can take several input arguments and prints in the Scilab console the integer corresponding to the number of input arguments detected in the calling Scilab function include stackch include sciprinth int scimyrhschar fname sciprintThe number of input parameters is d Rhs return 0 See Also sciprint Lhs Scilab Gateway API 3062 Name Scierror C gateway function which displays an error message to the user same profil as the printf function and returns an integer value specifying an error level void Scierrorerrorlevelformatvalue1valuen Parameters errorlevel an integer value specifying an error level format a char string Specifies a character string combining literal characters with conversion specifi cations valuei Specifies the data to be converted according to the format parameter returns If the operation is successfull this function returns the number of characters printed not including the trailing 0 used to end output to strings If an error occurred a negative value is returned Description Scierror is a C gateway function which displays an error message to the user same profil as the printf function and returns an integer value specifying an error level You must include Scierrorh to benefit from this function This header is provided in the outputstream module this directory should be included by default Examples In this example the C gateway function prints an error message and returns the error level 133 include stackch include Scierrorh int scimyscierrorchar fname Scierror133An error has occured d 1 return 0 See Also printfconversion printf sciprint Scilab Gateway API 3063 Nome Scilab C Types the C types available in a C gateway Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The stringchar datatype in the Scilab memory STRINGDATATYPE c The stringchar datatype in the Scilab memory MATRIXOFSTRINGDATATYPE S A matrix of double if the size of the matrix is 11 it is a single value MATRIXOFDOUBLEDATATYPE d A matrix of rational if the size of the matrix is 11 it is a single value MATRIXOFRATIONALDATATYPE r A matrix of integer if the size of the matrix is 11 it is a single value MATRIXOFVARIABLESIZEINTEGERDATATYPE I A matrix of little integer little because in reality this int is a complex with the imaginary part set to 0 if the size of the matrix is 11 it is a single value MATRIXOFINTEGERDATATYPE i A matrix of boolean if the size of the matrix is 11 it is a single value MATRIXOFBOOLEANDATATYPE b A matrix of complex if the size of the matrix is 11 it is a single value MATRIXOFCOMPLEXDATATYPE z A sparse matrix if the size of the matrix is 11 it is a single value SPARSEMATRIXDATATYPE s Scilab Gateway API 3064 A list LISTDATATYPE l A typed list TYPEDLISTDATATYPE t A Matrix oriented typed list mlist object are very similar to tlist objects But if M is an mlist for any index i which is not a field name Mi is not the i th field of the list but is interpreted as the i th entry of M seen as a vector This is the only difference between mlist and tlist MATRIXORIENTEDTYPEDLISTDATATYPE m The scilab pointer datatype in the Scilab memory SCILABPOINTERDATATYPE p The scilab graphic handle datatype in the Scilab memory GRAPHICALHANDLEDATATYPE h An external is a function or routine which is used as an argument of some highlevel primitives such as ode optim schur EXTERNALDATATYPE f A matrix of polynomial coeff if the size of the matrix is 11 it is a single value MATRIXOFPOLYNOMIALDATATYPE x See Also mlist list tlist CreateVar GetRhsVar Scilab Gateway API 3065 Name getoptionals C gateway function which initialize the list of optional parameters res getoptionalsfname opts Parameters fname the name passed to the C gateway The name of the calling function of type char input pa rameter opts a C list of optional parameters typedef struct rhsopts int position stack position 1 if not present char name the name of the variable char type a Scilab type like d representing the type of the variable int mn the size of the variable unsigned long int l a pointer to the Scilab stack rhsopts res if no optional parameters has been sent the res 0 Otherwise res 1 Description A C gateway function which initialize the list of optional parameters You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding Scilab Gateway API 3066 nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3067 Nome istk Return a pointer to an integer to access data stored at a given position in the Scilab memory istklstackpos Parameters lstackpos the position in the Scilab memory of the parameter to be accessed input argument Description This C gateway function returns a pointer to an integer to access data stored at a given position in the Scilab memory WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples include stackch int scimyoneschar fname int mrow ncol lpos mrow 1 ncol 1 We create a scalar CreateVar1 MATRIXOFINTEGERDATATYPE mrow ncol lpos istklpos 1 We store the value 1 in the memory allocated for output parameter 1 LhsVar1 1 return 0 See Also Scilab C Type CreateVar LhsVar Scilab Gateway API 3068 Name scitypes a C enumeration which defines the types available for a variable Description A C enumeration which defines the types available for a variable You must include stackch to benefit from this type definition The list of available types is the following 1 scimatrix a matrix of doubles 2 scipoly a polynomials matrix 4 sciboolean a boolean matrix 5 scisparse a sparse matrix 6 scibooleansparse a sparse boolean matrix 7 scimatlabsparse a sparse matlab matrix 8 sciints a matrix of integers 9 scihandles a graphical handle 10 scistrings a matrix of strings 11 sciufunction an uncompiled Scilab function 13 scicfunction a compiled Scilab function 14 scilib a library of Scilab functions 15 scilist a Scilab list 16 scitlist a Scilab tlist 17 scimlist a Scilab mlist 128 scipointer was scilufactpointer before Scilab 52 a pointer Integers or enumeration types can be used to check the type of the variables Using the enumeration type is recommended because of the explicit meaning of the value of the enumeration type If this function is used it is probable that GetType will also be used WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C gateway function takes one argument Through a switch case structure we display the type of the variable sent as a parameter include stackch include sciprinth int scimyscitypesrhschar fname switchGetType1 case scimatrix Scilab Gateway API 3069 sciprintA matrix of doubles break case scipoly sciprintA matrix of polynomials break case sciboolean sciprintA matrix of booleans break case scisparse sciprintA sparse matrix of doubles break case scibooleansparse sciprintA sparse matrix of booleans break case scimatlabsparse sciprintA sparse matlab matrix break case sciints sciprintA matrix of integers break case scihandles sciprintA graphic handle break case scistrings sciprintA matrix of strings break case sciufunction sciprintAn uncompiled Scilab function break case scicfunction sciprintA compiled Scilab function break case scilib sciprintA library of Scilab functions break case scilist sciprintA Scilab list break case scitlist sciprintA Scilab tlist break case scimlist sciprintA Scilab mlist break case scipointer case scilufactpointer Renamed in version 52 sciprintA pointer break default sciprintUnknown type Should never happen return 0 Scilab Gateway API 3070 See Also sciprint GetType Scilab Gateway API 3071 Name sciprint A C gateway function which displays standard messages to the user same profil as the C printf function void sciprintformatvalue1valuen Parameters format a char string Specifies a character string combining literal characters with conversion specifi cations valuei Specifies the data to be converted according to the format parameter s d Description This C gateway function provides the capabilities to display messages to the Scilab user Basically it emulates the C language printf function You must include sciprinth to benefit from this function This header is provided in the outputstream module this directory should be included by default Note that if you want to trigger an error the function Scierror is more appropriate Examples In this example the C gateway function prints several messages illustrating the use of the sciprint function in the Scilab console include stackch include sciprinth int scimysciprintchar fname sciprintprinting an integer d 1 sciprintprinting a double f 21 sciprintprinting a string s test return 0 See Also printfconversion printf Scierror Scilab Gateway API 3072 Nome stk Return a pointer to a double to access data stored at a given position in the Scilab memory stklstackpos Parameters lstackpos the position in the Scilab memory of the variable to be accessed input argument Description This C gateway function returns a pointer to a double to access data stored at a given position in the Scilab memory WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples include stackch int scimyoneschar fname int mrow ncol lpos mrow 1 ncol 1 We create a scalar CreateVar1 MATRIXOFDOUBLEDATATYPE mrow ncol lpos stklpos 10 We store the value 10 in the area allocated by CreateVar LhsVar1 1 We set the parameter 1 created by CreateVar as an output parameter of the gateway function return 0 See Also Scilab C Type CreateVar LhsVar Capítulo 12 listmanagement listmanagement 3074 Name Boolean reading Scilab gateway How to read matrix of boolean in a list Input argument profile SciErr getMatrixOfBooleanInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piBool Named variable profile SciErr readMatrixOfBooleanInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piBool Return address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of boolean in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos listmanagement 3075 int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings listmanagement 3076 iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab listmanagement 3077 return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL listmanagement 3078 double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr listmanagement 3079 printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL listmanagement 3080 ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem listmanagement 3081 return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec listmanagement 3082 case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr listmanagement 3083 printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL listmanagement 3084 ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3085 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3086 Name Boolean writing Scilab gateway How to add matrix of boolean in a list Create from existing data Input argument profile SciErr createMatrixOfBooleanInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piBool Named variable profile SciErr createMatrixOfBooleanInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable piBool Address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocMatrixOfBooleanInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable piParent Address of the parent of the new item iItemPos Position of the new item in the list listmanagement 3087 iRows Number of rows of the new variable iCols Number of columns of the new variable piBool Returns address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of boolean in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3088 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal listmanagement 3089 ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3090 Name Boolean sparse reading Scilab gateway How to read boolean sparse in a list Input argument profile SciErr getBooleanSparseMatrixInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos Named variable profile SciErr readBooleanSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piNbItem Return number of non zero value piNbItemRow Return number of item in each rows size iRows piColPos Return column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read boolean sparse in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint listmanagement 3091 int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse listmanagement 3092 iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3093 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 listmanagement 3094 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3095 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos listmanagement 3096 SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else listmanagement 3097 sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr listmanagement 3098 printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default listmanagement 3099 return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 listmanagement 3100 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr listmanagement 3101 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3102 Name Boolean sparse writing Scilab gateway How to add boolean sparse matrix in a list Input argument profile SciErr createBooleanSparseMatrixInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos Named variable profile SciErr createBooleanSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add boolean sparse matrix in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 listmanagement 3103 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3104 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 listmanagement 3105 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3106 Name Create List Scilab gateway How to get create a list in Scilab memory Input argument profile SciErr createListvoid pvCtx int iVar int iNbItem int piAddress SciErr createMListvoid pvCtx int iVar int iNbItem int piAddress SciErr createTListvoid pvCtx int iVar int iNbItem int piAddress Named variable profile SciErr createNamedListvoid pvCtx char pstName int iNbItem int piAddress SciErr createNamedTListvoid pvCtx char pstName int iNbItem int piAddress SciErr createNamedMListvoid pvCtx char pstName int iNbItem int piAddress Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iNbItem Number of items in the list piAddress Return address of the list SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the address of a list in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 listmanagement 3107 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 listmanagement 3108 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 listmanagement 3109 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3110 Name Double reading Scilab gateway How to read matrix of double in a list Input argument profile SciErr getMatrixOfDoubleInListvoid pvCtx int piParent int iItemPos int piRows int piCols double pdblReal SciErr getComplexMatrixOfDoubleInListvoid pvCtx int piParent int iItemPos int piRows int piCols double pdblReal double pdblImg Named variable profile SciErr readMatrixOfDoubleInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols double pdblReal SciErr readComplexMatrixOfDoubleInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable pdblReal Return address of real part data array size iRows iCols pdblImg Return address of imaginary part data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of double in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint listmanagement 3111 int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse listmanagement 3112 iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3113 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 listmanagement 3114 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3115 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos listmanagement 3116 SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else listmanagement 3117 sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr listmanagement 3118 printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default listmanagement 3119 return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 listmanagement 3120 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr listmanagement 3121 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3122 Name Double writing Scilab gateway How to add matrix of double in a list Create from existing data Input argument profile SciErr createMatrixOfBooleanInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piBool Named variable profile SciErr createMatrixOfBooleanInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable pdblReal Address of real data array size iCols iRows pdblImg Address of imaginary data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocMatrixOfDoubleInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols double pdblReal SciErr allocComplexMatrixOfDoubleInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable piParent Address of the parent of the new item listmanagement 3123 iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable pdblReal Return address of real data array size iCols iRows pdblImg Return address of imaginary data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of double in a list Two types of functions can be used to write in the memory of Scilab Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3124 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 listmanagement 3125 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3126 Name Get child item Scilab gateway How to get the address of a list child SciErr getListItemAddressvoid pvCtx int piAddress int iItemNum int piItemAddress Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the list iItemNum Item number piItemAddress Return address of the item SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the address of a list child Gateway Source int getlistinfoint piAddress void insertindentvoid static int iLocalTab 0 int commonlistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getlistinfopiAddr LhsVar1 0 return 0 int getlistinfoint piAddress SciErr sciErr listmanagement 3127 int i 0 int iRet 0 int iItem 0 get list item number failed if variable is not a kind of list sciErr getListItemNumberpvApiCtx piAddress iItem ifsciErriErr printErrorsciErr 0 sciprintThis variable is not a list return 0 sciprintList d items address 0x08X iItem piAddress fori 0 i iItem i int iType 0 int piAddrChild NULL sciErr getListItemAddresspvApiCtx piAddress i 1 piAddrChild ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddrChild iType ifsciErriErr printErrorsciErr 0 return 0 ifiType scilist iType scitlist iType scimlist insertindent sciprintChild d i 1 iLocalTab iRet getlistinfopiAddrChild iLocalTab ifiRet return 1 else insertindent sciprintChild d address 0x08X i 1 piAddrChild return 0 void insertindentvoid int i 0 fori 0 i iLocalTab i listmanagement 3128 sciprint Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l5 listl1l2l3 l4 listl5 listl5l5 l6 uint16100020003000 l listl1l2l3l6l4l5 commonlistl listmanagement 3129 Name Item Number Scilab gateway How to get the number of items in a list list mlist tlist SciErr getListItemNumbervoid pvCtx int piAddress int piNbItem Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the list piNbItem Return the number of items SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the number of items in a list list mlist tlist Gateway Source int getlistinfoint piAddress void insertindentvoid static int iLocalTab 0 int commonlistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getlistinfopiAddr LhsVar1 0 return 0 int getlistinfoint piAddress SciErr sciErr int i 0 int iRet 0 listmanagement 3130 int iItem 0 get list item number failed if variable is not a kind of list sciErr getListItemNumberpvApiCtx piAddress iItem ifsciErriErr printErrorsciErr 0 sciprintThis variable is not a list return 0 sciprintList d items address 0x08X iItem piAddress fori 0 i iItem i int iType 0 int piAddrChild NULL sciErr getListItemAddresspvApiCtx piAddress i 1 piAddrChild ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddrChild iType ifsciErriErr printErrorsciErr 0 return 0 ifiType scilist iType scitlist iType scimlist insertindent sciprintChild d i 1 iLocalTab iRet getlistinfopiAddrChild iLocalTab ifiRet return 1 else insertindent sciprintChild d address 0x08X i 1 piAddrChild return 0 void insertindentvoid int i 0 fori 0 i iLocalTab i sciprint listmanagement 3131 Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l5 listl1l2l3 l4 listl5 listl5l5 l6 uint16100020003000 l listl1l2l3l6l4l5 commonlistl listmanagement 3132 Name Integer reading Scilab gateway How to read matrix of integer in a list Input argument profile Signed integer SciErr getMatrixOfInteger8InListvoid pvCtx int piParent int iItemPos int piRows int piCols char pcData SciErr getMatrixOfInteger16InListvoid pvCtx int piParent int iItemPos int piRows int piCols short psData SciErr getMatrixOfInteger32InListvoid pvCtx int piParent int iItemPos int piRows int piCols int piData Unsigned integer SciErr getMatrixOfUnsignedInteger8InListvoid pvCtx int piParent int iItemPos int piRows int piCols unsigned char pucData SciErr getMatrixOfUnsignedInteger16InListvoid pvCtx int piParent int iItemPos int piRows int piCols unsigned short pusData SciErr getMatrixOfUnsignedInteger32InListvoid pvCtx int piParent int iItemPos int piRows int piCols unsigned int puiData Named variable profile Signed integer SciErr readMatrixOfIntger8InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols char pcData SciErr readMatrixOfIntger16InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols short psData SciErr readMatrixOfIntger32InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piData Unsigned integer SciErr readMatrixOfUnsignedInteger8InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols unsigned char pucData SciErr readMatrixOfUnsignedInteger16InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols unsigned short pusData SciErr readMatrixOfUnsignedInteger32InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols unsigned int puiData Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable pcData pucData psData pusData piData puiData Return address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number listmanagement 3133 Description This help describes how to read matrix of integer in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 listmanagement 3134 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 listmanagement 3135 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal listmanagement 3136 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi listmanagement 3137 ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3138 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 listmanagement 3139 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos listmanagement 3140 SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 listmanagement 3141 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3142 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3143 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3144 Name Integer writing Scilab gateway How to add matrix of integer in a list Create from existing data Input argument profile Signed integer SciErr createMatrixOfInteger8InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols char pcData SciErr createMatrixOfInteger16InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols short psData SciErr createMatrixOfInteger32InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piData Unsigned integer SciErr createMatrixOfUnsignedInteger8InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned char pucData SciErr createMatrixOfUnsignedInteger16InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned short pusData SciErr createMatrixOfUnsignedInteger32InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned int puiData Named variable profile Signed integer SciErr createMatrixOfInteger8InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols char pcData SciErr createMatrixOfInteger16InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols short psData SciErr createMatrixOfInteger32InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int piData Unsigned integer SciErr createMatrixOfUnsignedInteger8InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols unsigned char pucData SciErr createMatrixOfUnsignedInteger16InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols unsigned short pusData SciErr createMatrixOfUnsignedInteger32InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols unsigned int puiData Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable listmanagement 3145 iCols Number of columns of the new variable pcData8 psData16 piData32 pucData8 pusData16 puiData32 Address of data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile Signed integer SciErr allocMatrixOfInteger8InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols char pcData SciErr allocMatrixOfInteger16InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols short psData SciErr allocMatrixOfInteger32InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piData Unsigned integer SciErr allocMatrixOfUnsignedInteger8InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned char pucData SciErr allocMatrixOfUnsignedInteger16InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned short pusData SciErr allocMatrixOfUnsignedInteger32InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned int puiData Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable pcData8 psData16 piData32 pucData8 pusData16 puiData32 Return address of data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of integer in a list Two types of functions can be used to write in the memory of Scilab listmanagement 3146 Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3147 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr listmanagement 3148 printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3149 Name Pointer reading Scilab gateway How to read pointer in a list Input argument profile SciErr getPointerInListvoid pvCtx int piParent int iItemPos void pvPtr Named variable profile SciErr readPointerInNamedListvoid pvCtx char pstName int piParent int iItemPos void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list pvPtr Return pointer on data SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read pointer in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos listmanagement 3150 int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break listmanagement 3151 case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 listmanagement 3152 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL listmanagement 3153 sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3154 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 listmanagement 3155 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 listmanagement 3156 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData listmanagement 3157 break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3158 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr listmanagement 3159 printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3160 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3161 Name Pointer writing Scilab gateway How to add pointer in a list Input argument profile SciErr createPointerInListvoid pvCtx int iVar int piParent int iItemPos void pvPtr Named variable profile SciErr createPointerInNamedListvoid pvCtx char pstName int piParent int iItemPos void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list pvPtr Address of the pointer SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add pointer in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 listmanagement 3162 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos listmanagement 3163 ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref listmanagement 3164 if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3165 Name Polynomial reading Scilab gateway How to read matrix of polynomial in a list Input argument profile SciErr getMatrixOfPolyInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbCoef double pdblReal SciErr getComplexMatrixOfPolyInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbCoef double pdblReal double pdblImg Named variable profile SciErr readMatrixOfPolyInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbCoef double pdblReal SciErr readComplexMatrixOfPolyInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbCoef double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piNbCoef Return number of coefficient for each polynomial must be allocated pdblReal Address of array of double with imaginary part of coefficient size iCols iRows must be allocated pdblImg Address of array of double with imaginary part of coefficient size iCols iRows must be allocated SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of polynomial in a list Gateway Source static int iTab 0 void insertindentvoid listmanagement 3166 int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos listmanagement 3167 break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild listmanagement 3168 ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 listmanagement 3169 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr listmanagement 3170 printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff listmanagement 3171 return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr listmanagement 3172 sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL listmanagement 3173 ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData listmanagement 3174 break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination listmanagement 3175 sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 listmanagement 3176 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3177 Name Polynomial writing Scilab gateway How to add matrix of polynomial in a list Input argument profile SciErr createMatrixOfPolyInListvoid pvCtx int iVar int piParent int iItemPos char pstVarName int iRows int iCols int piNbCoef double pdblReal SciErr createComplexMatrixOfPolyInListvoid pvCtx int iVar int piParent int iItemPos char pstVarName int iRows int iCols int piNbCoef double pdblReal double pdblImg Named variable profile SciErr createMatrixOfPolyInNamedListvoid pvCtx char pstName int piParent int iItemPos char pstVarName int iRows int iCols int piNbCoef double pdblReal SciErr createComplexMatrixOfPolyInNamedListvoid pvCtx char pstName int piParent int iItemPos char pstVarName int iRows int iCols int piNbCoef double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list pstVarName Variable name in polynomials Scilab5 4 characters max iRows Number of rows of the new variable iCols Number of columns of the new variable piNbCoef Number of coefficient for each polynomial pdblReal Address of array of double with real part of coefficient size iCols iRows pdblImg Address of array of double with imaginary part of coefficient size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of polynomial in a list listmanagement 3178 Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3179 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr listmanagement 3180 printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3181 Name Sparse reading Scilab gateway How to read sparse in a list Input argument profile SciErr getSparseMatrixInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal SciErr getComplexSparseMatrixInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Named variable profile SciErr readSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal SciErr readComplexSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piNbItem Return number of non zero value piNbItemRow Return number of item in each rows size iRows piColPos Return column position for each item size iNbItem pdblReal Return array on real part data size iNbItem pdblImg Return array on imaginary part data size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read sparse in a list listmanagement 3182 Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType listmanagement 3183 case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr listmanagement 3184 printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 listmanagement 3185 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr listmanagement 3186 printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar listmanagement 3187 fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg listmanagement 3188 else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 listmanagement 3189 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData listmanagement 3190 break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr listmanagement 3191 printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 listmanagement 3192 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3193 Name Sparse writing Scilab gateway How to add sparse matrix in a list Create from existing data Input argument profile SciErr createSparseMatrixInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr createComplexSparseMatrixInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Named variable profile SciErr createSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr createComplexSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem pdblReal Address of real data array size iNbItem pdblImg Address of imaginary data array size iNbItem SciErr Error structure where is stored errors messages history and first error number listmanagement 3194 Description This help describes how to add sparse matrix in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr listmanagement 3195 printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 listmanagement 3196 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3197 Name String reading Scilab gateway How to read matrix of string in a list Input argument profile SciErr getMatrixOfStringInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piLength char pstStrings Named variable profile SciErr readMatrixOfStringInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piLength char pstStrings Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piLength Address of array of strings length must be allocated size piRows piCols pstStrings Address of array of char must be allocated size piRows piCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of string in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint listmanagement 3198 int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints listmanagement 3199 iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 listmanagement 3200 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 listmanagement 3201 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else listmanagement 3202 sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 listmanagement 3203 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal listmanagement 3204 insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3205 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 listmanagement 3206 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3207 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr listmanagement 3208 printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3209 Name String writing Scilab gateway How to add matrix of string in a list Input argument profile SciErr createMatrixOfStringInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols char pstStrings Named variable profile SciErr createMatrixOfStringInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols char pstStrings Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable pstStrings Address of array of char size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of string in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 listmanagement 3210 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr listmanagement 3211 printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list listmanagement 3212 dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end 3213 Name apiscilab apiscilab is the Scilab interface to readwrite data fromto Scilab memory Description In the previous versions of Scilab there was no clear or easy way to extend Scilab or to use it as an embedded application Since Scilab 520 these issues have been tackled by API Scilab Its provides a new consistent doc umented and easy way API This API provides functions to readwrite data fromto Scilab memory It provides many advantages Management of all Scilab data types Consistency over all data types Error management Fully documented Fully tested by unitary tests Straight and named access See the callscilab API to variables And it will be maintained over future versions of Scilab Usually this API is used to extend Scilab capabilities but can be used in other contexts Libraires or CC functions Many librairies have been developped on the freeOpen source or proprietary markets This library can be loaded and used in a high level language like Scilab API Scilab provides the capabilities to interact with such libraries Scilab can be used as computing engine from a third party software This feature is called callscilab when Scilab is used from CC code or javasci when used from Java Access to variable is done through their names named variable Note that old APIs stackXh will not be available after Scilab 60 included See Also Compile and run with callscilab Matrix Management Boolean Management Complex Manage ment String Management CallScilab Authors Sylvestre Ledru 3214 Name Boolean reading Scilab gateway How to read matrix of boolean Input argument profile SciErr getMatrixOfBooleanvoid pvCtx int piAddress int piRows int piCols int piBool Named variable profile SciErr readNamedMatrixOfBooleanvoid pvCtx char pstName int piRows int piCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows of the variable piCols Return number of columns of the variable piBool Return address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of boolean Gateway Source int readwritebooleanchar fnameunsigned long fnamelen SciErr sciErr int i first variable info real matrix of double int iRows 0 int iCols 0 int piAddr NULL int piBool NULL check input and output arguments CheckRhs11 CheckLhs11 Boolean reading Scilab gateway 3215 get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 get size and data from Scilab memory sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 Do something with data fori 0 i iRows iCols i piBooli piBooli 0 1 0 sciErr createMatrixOfBooleanpvApiCtx Rhs 1 iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script a t f t f t f t f t aref f t f t f t f t f b readwritebooleana if orb aref then errorfailed end 3216 Name Boolean writing Scilab gateway How to write matrices of boolean Input argument profile SciErr createMatrixOfBooleanvoid pvCtx int iVar int iRows int iCols int piBool Named variable profile SciErr createNamedMatrixOfBooleanvoid pvCtx char pstName int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piRows Return number of rows of the variable piCols Return number of columns of the variable piBool Return address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocMatrixOfBooleanvoid pvCtx int iVar int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable iRows Number of rows of the new variable iCols Numbers of columns of the new variable piBool Returns address of real data array size iCols iRows Boolean writing Scilab gateway 3217 SciErr Error structure where is stored errors messages history and first error number Description This help describes how to write matrix of boolean Gateway Source int readwritebooleanchar fnameunsigned long fnamelen SciErr sciErr int i first variable info real matrix of double int iRows 0 int iCols 0 int piAddr NULL int piBool NULL check input and output arguments CheckRhs11 CheckLhs11 get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 get size and data from Scilab memory sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 Do something with data fori 0 i iRows iCols i piBooli piBooli 0 1 0 sciErr createMatrixOfBooleanpvApiCtx Rhs 1 iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Boolean writing Scilab gateway 3218 Scilab test script a t f t f t f t f t aref f t f t f t f t f b readwritebooleana if orb aref then errorfailed end 3219 Name Boolean sparse reading Scilab gateway How to read boolean sparse in a gateway Input argument profile SciErr getBooleanSparseMatrixvoid pvCtx int piAddress int piRows int piCols int piNbItem int piNbItemRow int piColPos Named variable profile SciErr readNamedBooleanSparseMatrixvoid pvCtx char pstName int piRows int piCols int piNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows of the variable piCols Return number of columns of the variable piNbItem Return number of non zero value piNbItemRow Return number of item in each rows size iRows piColPos Return column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read boolean sparse Gateway Source int readwritebsparsechar fnameunsigned long fnamelen SciErr sciErr int i 0 int j 0 int k 0 first variable info real matrix of double int iRows 0 int iCols 0 int piAddr NULL int iNbItem 0 Boolean sparse read ing Scilab gateway 3220 int piNbItemRow NULL int piColPos NULL int iCol 0 int iNewCol 0 int iNewItem 0 int piNewRow NULL int piNewCol NULL check input and output arguments CheckRhs11 CheckLhs11 get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 get size and data from Scilab memory sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iNbItem piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 Do something with data convert T F and F T iNewItem iRows iCols iNbItem piNewRow intMALLOCsizeofint iRows piNewCol intMALLOCsizeofint iNewItem fori 0 i iRows i piNewRowi iCols piNbItemRowi forj 0 j iCols j int iFind 0 fork 0 k piNbItemRowi k ifpiColPosiCol k j 1 iFind 1 break ifiFind 0 piNewColiNewCol j 1 Boolean sparse read ing Scilab gateway 3221 iCol piNbItemRowi sciErr createBooleanSparseMatrixpvApiCtx Rhs 1 iRows iCols iNewItem piNewRow piNewCol ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script a sparset f t f t f t f t aref sparsef t f t f t f t f b readwritebsparsea if orb aref then errorfailedend 3222 Name Boolean sparse writing Scilab gateway How to add boolean sparse matrix in a gateway Input argument profile SciErr createBooleanSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos Named variable profile SciErr createNamedBooleanSparseMatrixvoid pvCtx char pstName int iRows int iCols int iNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocBooleanSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable iRows Number of rows of the new variable iCols Number of columns of the new variable Boolean sparse writ ing Scilab gateway 3223 iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add boolean sparse matrix in a list Gateway Source int readwritebsparsechar fnameunsigned long fnamelen SciErr sciErr int i 0 int j 0 int k 0 first variable info real matrix of double int iRows 0 int iCols 0 int piAddr NULL int iNbItem 0 int piNbItemRow NULL int piColPos NULL int iCol 0 int iNewCol 0 int iNewItem 0 int piNewRow NULL int piNewCol NULL check input and output arguments CheckRhs11 CheckLhs11 get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 get size and data from Scilab memory sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iNbItem piNbItemRow piColPos ifsciErriErr Boolean sparse writ ing Scilab gateway 3224 printErrorsciErr 0 return 0 Do something with data convert T F and F T iNewItem iRows iCols iNbItem piNewRow intMALLOCsizeofint iRows piNewCol intMALLOCsizeofint iNewItem fori 0 i iRows i piNewRowi iCols piNbItemRowi forj 0 j iCols j int iFind 0 fork 0 k piNbItemRowi k ifpiColPosiCol k j 1 iFind 1 break ifiFind 0 piNewColiNewCol j 1 iCol piNbItemRowi sciErr createBooleanSparseMatrixpvApiCtx Rhs 1 iRows iCols iNewItem piNewRow piNewCol ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script a sparset f t f t f t f t aref sparsef t f t f t f t f b readwritebsparsea if orb aref then errorfailedend 3225 Name Variable Reference Scilab gateway How to get the address of an argument or a variable in a gateway Input argument profile SciErr getVarAddressFromPositionvoid pvCtx int iVar int piAddress Named variable profile SciErr getVarAddressFromNamevoid pvCtx char pstName int piAddress Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position of the argument in the function call pstName Scilab variable name piAddress Return address of the Scilab variable SciErr Error structure where is stored errors messages history and first error number Description This function retrieves the address of an argument in a gateway Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false iBool sciErriErr 0 1 0 Variable Reference Scilab gateway 3226 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed char pstUnsigned unsigned Variable Reference Scilab gateway 3227 char pstSign pstSigned int iPrec 0 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr sciprintd iItem Variable Reference Scilab gateway 3228 return sciErr Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3229 Name Variable dimension Scilab gateway How to get the dimensions of an argument or a variable stored as matrix Input argument profile SciErr getVarDimensionvoid pvCtx int piAddress int piRows int piCols Named variable profile SciErr getNamedVarDimensionvoid pvCtx char pstName int piRows int piCols Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress The address of the variable pstName Scilab variable name piRows Return number of rows piCols Return number of columns SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the dimensions of a variable in a gateway Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint Variable dimension Scilab gateway 3230 1 for true 0 for false iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints Variable dimension Scilab gateway 3231 char pstSigned signed char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr Variable dimension Scilab gateway 3232 return sciErr sciprintd iItem return sciErr Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3233 Name Variable Type Scilab gateway How to get the type of an argument or a variable within a gateway Input argument profile SciErr getVarTypevoid pvCtx int piAddress int piType Named variable profile SciErr getNamedVarTypevoid pvCtx char pstName int piType Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress The address of the variable pstName Scilab variable name piType Scilab type of the variable scimatrix scistrings sciints Note that the list of the different variable types is available as an enum in stackch SciErr Error structure where is stored errors messages history and first error number Description This help describes how to retrieve the Scilab type of a variable in a gateway Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false Variable Type Scilab gateway 3234 iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed Variable Type Scilab gateway 3235 char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr Variable Type Scilab gateway 3236 sciprintd iItem return sciErr Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3237 Name Variable Complexity Scilab gateway How to get the argument or variable complexity Input argument profile int isVarComplexvoid pvCtx int piAddress Named variable profile int isNamedVarComplexvoid pvCtx char pstName Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the variable pstName Scilab variable name Returned value 0 for real variables and 1 for complex variables Description This help describes how to retrieve the variable complexity Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr Variable Complexi ty Scilab gateway 3238 printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 Variable Complexi ty Scilab gateway 3239 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr sciprintd iItem return sciErr Variable Complexi ty Scilab gateway 3240 Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3241 Name Matrix Type Scilab gateway How to know if an argument or a variable is stored as a matrix Input argument profile int isVarMatrixTypevoid pvCtx int piAddress Named variable profile int isNamedVarMatrixTypevoid pvCtx char pstName Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the variable Returned value 1 if the variable is stored as matrix otherwise 0 Description This help describes how to know if a variable is stored as a matrix In some cases exemple list a variable is not stored as a standard Scilab matrix This function pro vides a way to handle both cases Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr Matrix Type Scilab gateway 3242 printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 Matrix Type Scilab gateway 3243 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr sciprintd iItem return sciErr Matrix Type Scilab gateway 3244 Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3245 Name Double reading Scilab gateway How to read matrices of double in a gateway Input argument profile SciErr getMatrixOfDoublevoid pvCtx int piAddress int piRows int piCols double pdblReal SciErr getComplexMatrixOfDoublevoid pvCtx int piAddress int piRows int piCols double pdblReal double pdblImg Named variable profile SciErr readNamedMatrixOfDoublevoid pvCtx char pstName int piRows int piCols double pdblReal SciErr readNamedComplexMatrixOfDoublevoid pvCtx char pstName int piRows int piCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns pdblReal Return address of real data array size iCols iRows pdblImg Return address of imaginary data array size iCols iRows This argument does not exist with getMatrixOfDouble and readNamedMatrixOfDouble SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of doubles can be handled through the Scilab API Gateway Source int readdoublechar fnameunsigned long fnamelen int i first variable info real matrix of double int iType 0 int iRows 0 int iCols 0 int iComplex 0 int piAddr NULL double pdblReal NULL Double reading Scilab gateway 3246 double pdblImg NULL SciErr sciErr check input and output arguments CheckRhs11 CheckLhs11 First variable get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 check type sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr iType scimatrix printErrorsciErr 0 return 0 get complexity iComplex isVarComplexpvApiCtx piAddr check complexity ifiComplex get size and data from Scilab memory sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else get size and data from Scilab memory sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 Do something with data if variable is complex switch real part and imaginary part otherwise multiply by 1 ifiComplex sciErr createComplexMatrixOfDoublepvApiCtx Rhs 1 iRows iCols pdblImg pdblReal else Double reading Scilab gateway 3247 fori 0 i iRows iCols i pdblReali pdblReali 1 sciErr createMatrixOfDoublepvApiCtx Rhs 1 iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script a 0 1 2 3 4 5 6 7 8 9 10 11 b 23i 122i 221i 320i 419i 518i 617i 716i 815i 914i 1013i 1112i 1211i 1310i 149i 158i 167i 176i 185i 194i 203i 212i 221i 23 a2 readdoublea b2 readdoubleb if ora2 a 1 then errorfailed end if orb2 imagb realb i then errorfailed end 3248 Name Double writing Scilab gateway How to write matrices of doubles in a gateway Create from existing data Input argument profile SciErr createMatrixOfDoublevoid pvCtx int iVar int iRows int iCols double pdblReal SciErr createComplexMatrixOfDoublevoid pvCtx int iVar int iRows int iCols double pdblReal double pdblImg Named variable profile SciErr createNamedMatrixOfDoublevoid pvCtx char pstName int iRows int iCols double pdblReal SciErr createNamedComplexMatrixOfDoublevoid pvCtx char pstName int iRows int iCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Numbers of columns of the new variable pdblReal Address of real data array size iCols iRows pdblImg Address of imaginary data array size iCols iRows This argument does not exist with cre ateMatrixOfDouble and createNamedMatrixOfDouble SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocMatrixOfDoublevoid pvCtx int iVar int iRows int iCols double pdblReal SciErr allocComplexMatrixOfDoublevoid pvCtx int iVar int iRows int iCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable Double writing Scilab gateway 3249 iRows Number of rows of the new variable iCols Numbers of columns of the new variable pdblReal Returns address of real data array size iCols iRows pdblImg Returns address of imaginary data array size iCols iRows This argument does not exist with allocMatrixOfDouble SciErr Error structure where is stored errors messages history and first error number Gateway Source int writedoublechar fnameunsigned long fnamelen SciErr sciErr int ij first variable info real matrix of double 3 x 4 int iRows1 3 int iCols1 4 double pdblReal1 NULL second variable info complex matrix of double 4 x 6 int iRows2 4 int iCols2 6 double pdblReal2 NULL double pdblImg2 NULL First variable alloc array of data in OS memory pdblReal1 doublemallocsizeofdouble iRows1 iCols1 fill array with incremental values 0 1 2 3 4 5 6 7 8 9 10 11 fori 0 i iRows1 i forj 0 j iCols1 j pdblReal1i iRows1 j i iCols1 j can be written in a single loop fori 0 i iRows1 iCols1 i pdblReal1i i Double writing Scilab gateway 3250 create a variable from a existing data array sciErr createMatrixOfDoublepvApiCtx Rhs 1 iRows1 iCols1 pdblReal1 ifsciErriErr printErrorsciErr 0 return 0 after creation we can free memory freepdblReal1 Second variable reserve space in scilab memory and fill it sciErr allocComplexMatrixOfDoublepvApiCtx Rhs 2 iRows2 iCols2 pdblReal2 pdblImg2 ifsciErriErr printErrorsciErr 0 return 0 fill array with incremental values for real part and decremental for imaginary part 23i 122i 221i 320i 419i 518i 617i 716i 815i 914i 1013i 1112i 1211i 1310i 149i 158i 167i 176i 185i 194i 203i 212i 221i 23 fori 0 i iRows2 i forj 0 j iCols2 j pdblReal2i iRows2 j i iCols2 j pdblImg2 i iRows2 j iRows2 iCols2 1 i iCols2 j can be written in a single loop fori 0 i iRows2 iCols2 i pdblReal2i i pdblImg2 i iRows2 iCols2 1 i DO NOT FREE MEMORY in this case its the Scilab memory assign allocated variables to Lhs position LhsVar1 Rhs 1 LhsVar2 Rhs 2 return 0 Scilab test script aref 0 1 2 3 4 5 6 7 8 9 10 11 Double writing Scilab gateway 3251 bref 23i 122i 221i 320i 419i 518i 617i 716i 815i 914i 1013i 1112i 1211i 1310i 149i 158i 167i 176i 185i 194i 203i 212i 221i 23 ab writedouble if ora aref then errorfailedend if orb bref then errorfailedend 3252 Name Integer Precision Scilab gateway How to get precision of an integer matrix SciErr getMatrixOfIntegerPrecisionvoid pvCtx int piAddress int piPrecision SciErr getNamedMatrixOfIntegerPrecisionvoid pvCtx char pstName int piPrecision Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the variable pstName Name of the variable for named functions piPrecision Return precision of an integer variable SCIINT8 SCIUINT8 SCIINT16 SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get precision of an integer matrix Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr printErrorsciErr 0 Integer Precision Scilab gateway 3253 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec Integer Precision Scilab gateway 3254 ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr sciprintd iItem return sciErr Integer Precision Scilab gateway 3255 Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3256 Name Integer reading Scilab gateway How to read matrices of integer in a gateway Input argument profile Signed integer SciErr getMatrixOfInteger8void pvCtx int piAddress int piRows int piCols char pcData8 SciErr getMatrixOfInteger16void pvCtx int piAddress int piRows int piCols short psData16 SciErr getMatrixOfInteger32void pvCtx int piAddress int piRows int piCols int piData32 Unsigned integer SciErr getMatrixOfUnsignedInteger8void pvCtx int piAddress int piRows int piCols unsigned char pucData8 SciErr getMatrixOfUnsignedInteger16void pvCtx int piAddress int piRows int piCols unsigned short pusData16 SciErr getMatrixOfUnsignedInteger32void pvCtx int piAddress int piRows int piCols unsigned int puiData32 Named variable profile Signed integer SciErr readNamedMatrixOfInteger8void pvCtx char pstName int piRows int piCols char pcData8 SciErr readNamedMatrixOfInteger16void pvCtx char pstName int piRows int piCols short psData16 SciErr readNamedMatrixOfInteger32void pvCtx char pstName int piRows int piCols int piData32 Unsigned integer SciErr readNamedMatrixOfUnsignedInteger8void pvCtx char pstName int piRows int piCols unsigned char pucData8 SciErr readNamedMatrixOfUnsignedInteger16void pvCtx char pstName int piRows int piCols unsigned short pusData16 SciErr readNamedMatrixOfUnsignedInteger32void pvCtx char pstName int piRows int piCols unsigned int puiData32 Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns pcData8 pucData8 psData16 pusData16 piData32 puiData32 Returns address of array size piRows piCols SciErr Error structure where is stored errors messages history and first error number Integer reading Scilab gateway 3257 Description This help describes how matrices of integer can be handled through the Scilab API Gateway Source void createoutputint iCoeff int iSize int iRows int iCols void pvDataIn int readintegerchar fnameunsigned long fnamelen SciErr sciErr output variable info int iRows8 0 int iCols8 0 int iRows16 0 int iCols16 0 int iRows32 0 int iCols32 0 int iRowsu8 0 int iColsu8 0 int iRowsu16 0 int iColsu16 0 int iRowsu32 0 int iColsu32 0 int iPrec 0 int piAddr8 NULL int piAddr16 NULL int piAddr32 NULL int piAddru8 NULL int piAddru16 NULL int piAddru32 NULL char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL char pcDataOut NULL short psDataOut NULL int piDataOut NULL unsigned char pucDataOut NULL unsigned short pusDataOut NULL unsigned int puiDataOut NULL check inputouput arguments count CheckRhs66 CheckLhs66 get varialbe address sciErr getVarAddressFromPositionpvApiCtx 1 piAddr8 ifsciErriErr Integer reading Scilab gateway 3258 printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 2 piAddru8 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 3 piAddr16 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 4 piAddru16 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 5 piAddr32 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 6 piAddru32 ifsciErriErr printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr8 iPrec ifsciErriErr iPrec SCIINT8 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru8 iPrec ifsciErriErr iPrec SCIUINT8 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr16 iPrec ifsciErriErr iPrec SCIINT16 Integer reading Scilab gateway 3259 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru16 iPrec ifsciErriErr iPrec SCIUINT16 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr32 iPrec ifsciErriErr iPrec SCIINT32 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru32 iPrec ifsciErriErr iPrec SCIUINT32 printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger8pvApiCtx piAddr8 iRows8 iCols8 pcData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddru8 iRowsu8 iColsu8 pucData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger16pvApiCtx piAddr16 iRows16 iCols16 psData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddru16 iRowsu16 iColsu16 pusData ifsciErriErr printErrorsciErr 0 Integer reading Scilab gateway 3260 return 0 retrieve dimensions and data sciErr getMatrixOfInteger32pvApiCtx piAddr32 iRows32 iCols32 piData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddru32 iRowsu32 iColsu32 puiData ifsciErriErr printErrorsciErr 0 return 0 alloc and fill new variable pcDataOut charcreateoutput2 1 iRows8 iCols8 voidpcData pucDataOut unsigned charcreateoutput4 1 iRowsu8 iColsu8 voidpucData psDataOut shortcreateoutput8 2 iRows16 iCols16 voidpsData pusDataOut unsigned shortcreateoutput16 2 iRowsu16 iColsu16 voidpusData piDataOut intcreateoutput32 4 iRows32 iCols32 voidpiData puiDataOut unsigned intcreateoutput64 4 iRowsu32 iColsu32 voidpuiData create new variable sciErr createMatrixOfInteger8pvApiCtx Rhs 1 iRows8 iCols8 pcDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger8pvApiCtx Rhs 2 iRowsu8 iColsu8 pucDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfInteger16pvApiCtx Rhs 3 iRows16 iCols16 psDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger16pvApiCtx Rhs 4 iRowsu16 iColsu16 pusDataOut ifsciErriErr printErrorsciErr 0 return 0 Integer reading Scilab gateway 3261 create new variable sciErr createMatrixOfInteger32pvApiCtx Rhs 5 iRows32 iCols32 piDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger32pvApiCtx Rhs 6 iRowsu32 iColsu32 puiDataOut ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 Rhs 1 LhsVar2 Rhs 2 LhsVar3 Rhs 3 LhsVar4 Rhs 4 LhsVar5 Rhs 5 LhsVar6 Rhs 6 return 0 void createoutputint iCoeff int iSize int iRows int iCols void pvDataIn int i 0 void pvDataOut voidmallociSize iRows iCols fori 0 i iRows iCols i int iVal 0 memcpyiVal charpvDataIn i iSize iSize iVal iCoeff memcpycharpvDataOut i iSize iVal iSize return pvDataOut Scilab test script a8 int8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au8 uint8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a16 int16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Integer reading Scilab gateway 3262 au16 uint16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a32 int32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au32 uint32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 c8 cu8 c16 cu16 c32 cu32 readintegera8 au8 a16 au16 a32 au32 if orc8 a8 2 then errorfailed end if orcu8 au8 4 then errorfailed end if orc16 a16 8 then errorfailed end if orcu16 au16 16 then errorfailed end if orc32 a32 32 then errorfailed end if orcu32 au32 64 then errorfailed end 3263 Name Integer writing Scilab gateway How to write matrices of integers in a gateway Create from existing data Input argument profile Signed integer SciErr createMatrixOfInteger8void pvCtx int iVar int iRows int iCols char pcData8 SciErr createMatrixOfInteger16void pvCtx int iVar int iRows int iCols short psData16 SciErr createMatrixOfInteger32void pvCtx int iVar int iRows int iCols int piData32 Unsigned integer SciErr createMatrixOfUnsignedInteger8void pvCtx int iVar int iRows int iCols unsigned char pucData8 SciErr createMatrixOfUnsignedInteger16void pvCtx int iVar int iRows int iCols unsigned short pusData16 SciErr createMatrixOfUnsignedInteger32void pvCtx int iVar int iRows int iCols unsigned int puiData32 Named variable profile Signed integer SciErr createNamedMatrixOfInteger8void pvCtx char pstName int iRows int iCols char pcData8 SciErr createNamedMatrixOfInteger16void pvCtx char pstName int iRows int iCols short psData16 SciErr createNamedMatrixOfInteger32void pvCtx char pstName int iRows int iCols int piData32 Unsigned integer SciErr createNamedMatrixOfUnsignedInteger8void pvCtx char pstName int iRows int iCols unsigned char pucData8 SciErr createNamedMatrixOfUnsignedInteger16void pvCtx char pstName int iRows int iCols unsigned short pusData16 SciErr createNamedMatrixOfUnsignedInteger32void pvCtx char pstName int iRows int iCols unsigned int puiData32 Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Numbers of columns of the new variable pcData8 psData16 piData32 pucData8 pusData16 puiData32 Address of data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Integer writing Scilab gateway 3264 Input argument profile Signed integer SciErr allocMatrixOfInteger8void pvCtx int iVar int iRows int iCols char pcData8 SciErr allocMatrixOfInteger16void pvCtx int iVar int iRows int iCols short psData16 SciErr allocMatrixOfInteger32void pvCtx int iVar int iRows int iCols int piData32 Unsigned integer SciErr allocMatrixOfUnsignedInteger8void pvCtx int iVar int iRows int iCols unsigned char pucData8 SciErr allocMatrixOfUnsignedInteger16void pvCtx int iVar int iRows int iCols unsigned short pusData16 SciErr allocMatrixOfUnsignedInteger32void pvCtx int iVar int iRows int iCols unsigned int puiData32 Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable iRows Number of rows of the new variable iCols Numbers of columns of the new variable pcData8 psData16 piData32 pucData8 pusData16 puiData32 Returns address of data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of integers can be handled through the Scilab API Two types of functions can be used to write in the memory of Scilab Gateway Source void createoutputint iCoeff int iSize int iRows int iCols void pvDataIn int readintegerchar fnameunsigned long fnamelen SciErr sciErr output variable info int iRows8 0 int iCols8 0 int iRows16 0 int iCols16 0 int iRows32 0 int iCols32 0 int iRowsu8 0 int iColsu8 0 Integer writing Scilab gateway 3265 int iRowsu16 0 int iColsu16 0 int iRowsu32 0 int iColsu32 0 int iPrec 0 int piAddr8 NULL int piAddr16 NULL int piAddr32 NULL int piAddru8 NULL int piAddru16 NULL int piAddru32 NULL char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL char pcDataOut NULL short psDataOut NULL int piDataOut NULL unsigned char pucDataOut NULL unsigned short pusDataOut NULL unsigned int puiDataOut NULL check inputouput arguments count CheckRhs66 CheckLhs66 get varialbe address sciErr getVarAddressFromPositionpvApiCtx 1 piAddr8 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 2 piAddru8 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 3 piAddr16 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 4 piAddru16 ifsciErriErr printErrorsciErr 0 return 0 Integer writing Scilab gateway 3266 sciErr getVarAddressFromPositionpvApiCtx 5 piAddr32 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 6 piAddru32 ifsciErriErr printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr8 iPrec ifsciErriErr iPrec SCIINT8 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru8 iPrec ifsciErriErr iPrec SCIUINT8 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr16 iPrec ifsciErriErr iPrec SCIINT16 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru16 iPrec ifsciErriErr iPrec SCIUINT16 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr32 iPrec ifsciErriErr iPrec SCIINT32 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru32 iPrec Integer writing Scilab gateway 3267 ifsciErriErr iPrec SCIUINT32 printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger8pvApiCtx piAddr8 iRows8 iCols8 pcData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddru8 iRowsu8 iColsu8 pucData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger16pvApiCtx piAddr16 iRows16 iCols16 psData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddru16 iRowsu16 iColsu16 pusData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger32pvApiCtx piAddr32 iRows32 iCols32 piData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddru32 iRowsu32 iColsu32 puiData ifsciErriErr printErrorsciErr 0 return 0 alloc and fill new variable pcDataOut charcreateoutput2 1 iRows8 iCols8 voidpcData pucDataOut unsigned charcreateoutput4 1 iRowsu8 iColsu8 voidpucData psDataOut shortcreateoutput8 2 iRows16 iCols16 voidpsData Integer writing Scilab gateway 3268 pusDataOut unsigned shortcreateoutput16 2 iRowsu16 iColsu16 voidpusData piDataOut intcreateoutput32 4 iRows32 iCols32 voidpiData puiDataOut unsigned intcreateoutput64 4 iRowsu32 iColsu32 voidpuiData create new variable sciErr createMatrixOfInteger8pvApiCtx Rhs 1 iRows8 iCols8 pcDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger8pvApiCtx Rhs 2 iRowsu8 iColsu8 pucDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfInteger16pvApiCtx Rhs 3 iRows16 iCols16 psDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger16pvApiCtx Rhs 4 iRowsu16 iColsu16 pusDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfInteger32pvApiCtx Rhs 5 iRows32 iCols32 piDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger32pvApiCtx Rhs 6 iRowsu32 iColsu32 puiDataOut ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 Rhs 1 LhsVar2 Rhs 2 LhsVar3 Rhs 3 LhsVar4 Rhs 4 LhsVar5 Rhs 5 Integer writing Scilab gateway 3269 LhsVar6 Rhs 6 return 0 void createoutputint iCoeff int iSize int iRows int iCols void pvDataIn int i 0 void pvDataOut voidmallociSize iRows iCols fori 0 i iRows iCols i int iVal 0 memcpyiVal charpvDataIn i iSize iSize iVal iCoeff memcpycharpvDataOut i iSize iVal iSize return pvDataOut Scilab test script a8 int8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au8 uint8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a16 int16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au16 uint16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a32 int32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au32 uint32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 c8 cu8 c16 cu16 c32 cu32 readintegera8 au8 a16 au16 a32 au32 if orc8 a8 2 then errorfailed end if orcu8 au8 4 then errorfailed end if orc16 a16 8 then errorfailed end if orcu16 au16 16 then errorfailed end if orc32 a32 32 then errorfailed end if orcu32 au32 64 then errorfailed end 3270 Name Pointer reading Scilab gateway How to read pointer in a gateway Input argument profile SciErr createNamedPointervoid pvCtx char pstName void pvPtr Named variable profile SciErr readNamedPointervoid pvCtx char pstName void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pvPtr Return address of pointer SciErr Error structure where is stored errors messages history and first error number Description This help describes how pointer can be handled through the Scilab API Gateway Source int readpointerchar fnameunsigned long fnamelen SciErr sciErr CheckRhs01 CheckLhs11 ifRhs 0 create mode double pdblData doublemallocsizeofdouble 2 2 pdblData0 1 pdblData1 3 pdblData2 2 pdblData3 4 sciErr createPointerpvApiCtx Rhs 1 voidpdblData else ifRhs 1 read mode int iType 0 int piAddr NULL void pvPtr NULL double pdblData NULL sciErr getVarAddressFromPositionpvApiCtx 1 piAddr Pointer reading Scilab gateway 3271 ifsciErriErr printErrorsciErr 0 return 0 sciErr getPointerpvApiCtx piAddr pvPtr ifsciErriErr printErrorsciErr 0 return 0 pdblData doublepvPtr sciErr createMatrixOfDoublepvApiCtx Rhs 1 2 2 pdblData else return 0 ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script bref 1234 a readpointer b readpointera if orb bref then errorfailed end 3272 Name Pointer writing Scilab gateway How to write pointer in a gateway Create from existing data Input argument profile SciErr getPointervoid pvCtx int piAddress void pvPtr Named variable profile SciErr createNamedPointervoid pvCtx char pstName void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pvPtr Address of pointer SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory SciErr allocPointervoid pvCtx int iVar void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pvPtr Return address of pointer SciErr Error structure where is stored errors messages history and first error number Description This help describes how pointer can be handled through the Scilab API Two types of functions can be used to write in the memory of Scilab Gateway Source int readpointerchar fnameunsigned long fnamelen SciErr sciErr Pointer writing Scilab gateway 3273 CheckRhs01 CheckLhs11 ifRhs 0 create mode double pdblData doublemallocsizeofdouble 2 2 pdblData0 1 pdblData1 3 pdblData2 2 pdblData3 4 sciErr createPointerpvApiCtx Rhs 1 voidpdblData else ifRhs 1 read mode int iType 0 int piAddr NULL void pvPtr NULL double pdblData NULL sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr getPointerpvApiCtx piAddr pvPtr ifsciErriErr printErrorsciErr 0 return 0 pdblData doublepvPtr sciErr createMatrixOfDoublepvApiCtx Rhs 1 2 2 pdblData else return 0 ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script Pointer writing Scilab gateway 3274 bref 1234 a readpointer b readpointera if orb bref then errorfailed end 3275 Name Polynomial Symbolic Variable Scilab gateway How to get the symbolic variable name Input argument profile SciErr getPolyVariableNamevoid pvCtx int piAddress char pstVarName int piVarNameLen Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the variable pstVarName Return the symbolic varaible name piVarNameLen Return the length of pstVarName SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the symbolic variable name Gateway Source int readpolychar fnameunsigned long fnamelen SciErr sciErr int ij variable info int iRows 0 int iCols 0 int iVarLen 0 int piAddr NULL int piNbCoef NULL double pdblReal NULL double pdblImg NULL char pstVarname NULL check input and output arguments CheckRhs11 CheckLhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 ifisVarComplexpvApiCtx piAddr FALSE Polynomial Symbolic Vari able Scilab gateway 3276 Error return 0 get variable name length sciErr getPolyVariableNamepvApiCtx piAddr NULL iVarLen ifsciErriErr printErrorsciErr 0 return 0 alloc buff to receive variable name pstVarname charmallocsizeofchar iVarLen 11 for null termination get variable name sciErr getPolyVariableNamepvApiCtx piAddr pstVarname iVarLen ifsciErriErr printErrorsciErr 0 return 0 First call retrieve dimmension sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL NULL ifsciErriErr printErrorsciErr 0 return 0 alloc array of coefficient piNbCoef intmallocsizeofint iRows iCols Second call retrieve coefficient sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piNbCoef NULL NULL ifsciErriErr printErrorsciErr 0 return 0 alloc arrays of data pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piNbCoefi pdblImgi doublemallocsizeofdouble piNbCoefi Third call retrieve data sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piNbCoef pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 Polynomial Symbolic Vari able Scilab gateway 3277 Do something with Data Invert polynomials in the matrix and invert coefficients fori 0 i iRows iCols 2 i int iPos1 iRows iCols 1 i double pdblSave NULL int iNbCoefSave 0 switch array of coefficient pdblSave pdblReali pdblReali pdblRealiPos1 pdblRealiPos1 pdblSave pdblSave pdblImgi pdblImgi pdblImgiPos1 pdblImgiPos1 pdblSave switch number of coefficient iNbCoefSave piNbCoefi piNbCoefi piNbCoefiPos1 piNbCoefiPos1 iNbCoefSave switch coefficient fori 0 i iRows iCols i forj 0 j piNbCoefi 2 j int iPos2 piNbCoefi 1 j double dblVal pdblRealij pdblRealij pdblRealiiPos2 pdblRealiiPos2 dblVal dblVal pdblImgij pdblImgij pdblImgiiPos2 pdblImgiiPos2 dblVal sciErr createComplexMatrixOfPolypvApiCtx Rhs 1 pstVarname iRows iCols piNbCoef pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 free OS memory freepstVarname freepiNbCoef fori 0 i iRows iCols i freepdblReali freepdblImgi Polynomial Symbolic Vari able Scilab gateway 3278 freepdblReal freepdblImg assign allocated variables to Lhs position LhsVar1 Rhs 1 return 0 Scilab test script coeff1 29i22i16i11i7i30231712831i24i18i13i9i322519141033i26i20i15i034272100028i0003635i0000 4i2ii221653023i17i6i00241800025i19i000262000027i21i00028000000 11742112i8i5i3i013960014i10i000150000000000000000000 x poly0 x p1 1 p2 2 x 3 i p3 4 x2 5 i x 6 p4 7 x3 8 i x2 9 x 10 i p5 11 x4 12 i x3 13 x2 14 i x 15 p6 16 x5 17 i x4 18 x3 19 i x2 20 x 21 i p7 22 x6 23 i x5 24 x4 25 i x3 26 x2 27 i x 28 p8 i p9 2 i x 3 p10 4 i x2 5 x 6 i p11 7 i x3 8 x2 9 i x 10 p12 11 i x4 12 x3 13 i x2 14 x 15 i p13 16 i x5 17 x4 18 i x3 19 x2 20 i x 21 p14 22 i x6 23 x5 24 i x4 25 x3 26 i x2 27 x 28 i p15 29 i x7 30 x6 31 i x5 32 x4 33 i x3 34 x2 35 i 36 p p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p1 readpolyp coeff2 coeffp1 if orcoeff2 coeff1 then errorfailed end 3279 Name Polynomial reading Scilab gateway How to read matrices of polynomials in a gateway Input argument profile SciErr getMatrixOfPolyvoid pvCtx int piAddress int piRows int piCols int piNbCoef double pdblReal SciErr getComplexMatrixOfPolyvoid pvCtx int piAddress int piRows int piCols int piNbCoef double pdblReal double pdblImg Named variable profile SciErr readNamedMatrixOfPolyvoid pvCtx char pstName int piRows int piCols int piNbCoef double pdblReal SciErr readNamedComplexMatrixOfPolyvoid pvCtx char pstName int piRows int piCols int piNbCoef double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns piNbCoef Return number of coefficient for each polynomial must be allocated pdblReal Address of array of double with imaginary part of coefficient size iCols iRows must be allocated pdblImg Address of array of double with imaginary part of coefficient size iCols iRows must be allocated SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of polynomials can be handled through the Scilab API Gateway Source int readpolychar fnameunsigned long fnamelen SciErr sciErr int ij variable info int iRows 0 int iCols 0 Polynomial reading Scilab gateway 3280 int iVarLen 0 int piAddr NULL int piNbCoef NULL double pdblReal NULL double pdblImg NULL char pstVarname NULL check input and output arguments CheckRhs11 CheckLhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 ifisVarComplexpvApiCtx piAddr FALSE Error return 0 get variable name length sciErr getPolyVariableNamepvApiCtx piAddr NULL iVarLen ifsciErriErr printErrorsciErr 0 return 0 alloc buff to receive variable name pstVarname charmallocsizeofchar iVarLen 11 for null termination get variable name sciErr getPolyVariableNamepvApiCtx piAddr pstVarname iVarLen ifsciErriErr printErrorsciErr 0 return 0 First call retrieve dimmension sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL NULL ifsciErriErr printErrorsciErr 0 return 0 alloc array of coefficient piNbCoef intmallocsizeofint iRows iCols Second call retrieve coefficient sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piNbCoef NULL NULL ifsciErriErr printErrorsciErr 0 return 0 Polynomial reading Scilab gateway 3281 alloc arrays of data pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piNbCoefi pdblImgi doublemallocsizeofdouble piNbCoefi Third call retrieve data sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piNbCoef pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 Do something with Data Invert polynomials in the matrix and invert coefficients fori 0 i iRows iCols 2 i int iPos1 iRows iCols 1 i double pdblSave NULL int iNbCoefSave 0 switch array of coefficient pdblSave pdblReali pdblReali pdblRealiPos1 pdblRealiPos1 pdblSave pdblSave pdblImgi pdblImgi pdblImgiPos1 pdblImgiPos1 pdblSave switch number of coefficient iNbCoefSave piNbCoefi piNbCoefi piNbCoefiPos1 piNbCoefiPos1 iNbCoefSave switch coefficient fori 0 i iRows iCols i forj 0 j piNbCoefi 2 j int iPos2 piNbCoefi 1 j double dblVal pdblRealij pdblRealij pdblRealiiPos2 pdblRealiiPos2 dblVal dblVal pdblImgij pdblImgij pdblImgiiPos2 pdblImgiiPos2 dblVal Polynomial reading Scilab gateway 3282 sciErr createComplexMatrixOfPolypvApiCtx Rhs 1 pstVarname iRows iCols piNbCoef pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 free OS memory freepstVarname freepiNbCoef fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg assign allocated variables to Lhs position LhsVar1 Rhs 1 return 0 Scilab test script coeff1 29i22i16i11i7i30231712831i24i18i13i9i322519141033i26i20i15i034272100028i0003635i0000 4i2ii221653023i17i6i00241800025i19i000262000027i21i00028000000 11742112i8i5i3i013960014i10i000150000000000000000000 x poly0 x p1 1 p2 2 x 3 i p3 4 x2 5 i x 6 p4 7 x3 8 i x2 9 x 10 i p5 11 x4 12 i x3 13 x2 14 i x 15 p6 16 x5 17 i x4 18 x3 19 i x2 20 x 21 i p7 22 x6 23 i x5 24 x4 25 i x3 26 x2 27 i x 28 p8 i p9 2 i x 3 p10 4 i x2 5 x 6 i p11 7 i x3 8 x2 9 i x 10 p12 11 i x4 12 x3 13 i x2 14 x 15 i p13 16 i x5 17 x4 18 i x3 19 x2 20 i x 21 p14 22 i x6 23 x5 24 i x4 25 x3 26 i x2 27 x 28 i p15 29 i x7 30 x6 31 i x5 32 x4 33 i x3 34 x2 35 i 36 p p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p1 readpolyp coeff2 coeffp1 if orcoeff2 coeff1 then errorfailed end Polynomial reading Scilab gateway 3283 3284 Name Polynomial writing Scilab gateway How to write matrices of polynomials in a gateway Input argument profile SciErr createMatrixOfPolyvoid pvCtx int iVar char pstVarName int iRows int iCols int piNbCoef double pdblReal SciErr createMatrixOfPolyvoid pvCtx int iVar char pstVarName int iRows int iCols int piNbCoef double pdblReal Named variable profile SciErr createNamedMatrixOfPolyvoid pvCtx char pstName char pstVarName int iRows int iCols int piNbCoef double pdblReal SciErr createNamedComplexMatrixOfPolyvoid pvCtx char pstName char pstVarName int iRows int iCols int piNbCoef double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions pstVarName Variable name in polynomials Scilab5 4 characters max iRows Number of rows of the new variable iCols Numbers of columns of the new variable piNbCoef Number of coefficient for each polynomial pdblReal Address of array of double with real part of coefficient size iCols iRows pdblImg Address of array of double with imaginary part of coefficient size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of polynomials can be handled through the Scilab API Gateway Source int writepolychar fnameunsigned long fnamelen SciErr sciErr Polynomial writing Scilab gateway 3285 output variable info polinomial matrix 2 x 4 x 2 x2 4x 5 4x3 14x2 18 2x3 12x2 64 1 8x5 32x3 int iRows 2 int iCols 3 varname x char pstVarName2 x coeficient array int piNbCoef6 243146 data array double pdblReal6 0 double pdblPoly02 21 double pdblPoly14 640122 double pdblPoly23 541 double pdblPoly31 1 double pdblPoly44 180144 double pdblPoly56 0003208 pdblReal0 pdblPoly0 pdblReal1 pdblPoly1 pdblReal2 pdblPoly2 pdblReal3 pdblPoly3 pdblReal4 pdblPoly4 pdblReal5 pdblPoly5 sciErr createMatrixOfPolypvApiCtx Rhs 1 pstVarName iRows iCols piNbCoef pdblReal ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 Rhs 1 return 0 Scilab test script pref 2 5 18 1 4 0 0 1 14 0 0 4 0 0 0 0 0 064 1 0 0 0 0 12 0 0 2 0 32 0 0 0 0 0 8 l list a writepoly p coeffa if orp pref then errorfailed end 3286 Name Sparse matrix reading Scilab gateway How to read sparse matric in a gateway Input argument profile SciErr getSparseMatrixvoid pvCtx int piAddress int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal SciErr getComplexSparseMatrixvoid pvCtx int piAddress int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Named variable profile SciErr readNamedSparseMatrixvoid pvCtx char pstName int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal SciErr readNamedComplexSparseMatrixvoid pvCtx char pstName int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns piNbItem Return number of non zero value piNbItemRow Return number of item in each rows size iRows piColPos Return column position for each item size iNbItem pdblReal Return address of real data array size iCols iRows pdblImg Return address of imaginary data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how sparse matrix can be handled through the Scilab API Gateway Source int readsparsechar fnameunsigned long fnamelen SciErr sciErr Sparse matrix read ing Scilab gateway 3287 int ijk int piAddr NULL int iRows 0 int iCols 0 int iNbItem 0 int piNbItemRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iNbItem piNbItemRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iNbItem piNbItemRow piColPos pdblReal ifsciErriErr printErrorsciErr 0 return 0 sciprintSparse d items iNbItem k 0 fori 0 i iRows i forj 0 j piNbItemRowi j sciprintdd f i1 piColPosk pdblRealk ifisVarComplexpvApiCtx piAddr sciprint fi pdblImgk sciprint k assign allocated variables to Lhs position LhsVar1 0 return 0 Sparse matrix read ing Scilab gateway 3288 Scilab test script spsparse12453101 2i2 3i3 4i readsparsesp 3289 Name Sparse writing Scilab gateway How to write sparse matrix in a gateway Create from existing data Input argument profile SciErr createSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr createComplexSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Named variable profile SciErr createNamedSparseMatrixvoid pvCtx char pstName int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr createNamedComplexSparseMatrixvoid pvCtx char pstName int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem pdblReal Address of real data array size iNbItem pdblImg Address of imaginary data array size iNbItem This argument does not exist with createSparseMatrix and createNamedSparseMatrix SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr allocComplexSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Sparse writing Scilab gateway 3290 Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Return address of number of item in each rows size iRows piColPos Return address of column position for each item size iNbItem pdblReal Address of real data array size iNbItem pdblImg Address of imaginary data array size iNbItem This argument does not exist with allocSparseMatrix SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add sparse matrix Two types of functions can be used to write in the memory of Scilab Gateway Source int writesparsechar fnameunsigned long fnamelen SciErr sciErr int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int iNbItem 4 sciErr createComplexSparseMatrixpvApiCtx Rhs 1 3 10 iNbItem piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 Sparse writing Scilab gateway 3291 LhsVar1 1 return 0 Scilab test script spref sparse1824273214i23i32i4i 310 sp writesparse if orsp spref then errorfailed end 3292 Name String reading Scilab gateway How to read matrices of strings in a gateway Input argument profile SciErr getMatrixOfStringvoid pvCtx int piAddress int piRows int piCols int piLength char pstStrings SciErr getMatrixOfWideStringvoid pvCtx int piAddress int piRows int piCols int piLength wchart pwstStrings Named variable profile SciErr createNamedMatrixOfStringvoid pvCtx char pstName int iRows int iCols char pstStrings SciErr createNamedMatrixOfWideStringvoid pvCtx char pstName int iRows int iCols wchart pwstStrings Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns piLength Address of array of strings length must be allocated size piRows piCols pstStrings Address of array of char must be allocated size piRows piCols pwstStrings Address of array of wchart must be allocated size piRows piCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of strings can be handled through the Scilab API Gateway Source int readstringchar fnameunsigned long fnamelen SciErr sciErr int ij int iLen 0 variable info int iRows 0 int iCols 0 int piAddr NULL String reading Scilab gateway 3293 int piLen NULL char pstData NULL output variable int iRowsOut 1 int iColsOut 1 char pstOut NULL check input and output arguments CheckRhs11 CheckLhs11 get variable address sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 fisrt call to retrieve dimensions sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols second call to retrieve length of each string sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination third call to retrieve data sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 computer length of all strings fori 0 i iRows iCols i iLen piLeni alloc output variable pstOut charmallocsizeofchar iLen iRows iCols String reading Scilab gateway 3294 initialize string to 0x00 memsetpstOut 0x00 sizeofchar iLen iRows iCols concat input strings in output string fori 0 i iRows i forj 0 j iCols j int iCurLen strlenpstOut ifiCurLen strcatpstOut strcpypstOut strlenpstOut pstDataj iRows i create new variable sciErr createMatrixOfStringpvApiCtx Rhs 1 iRowsOut iColsOut pstOut ifsciErriErr printErrorsciErr 0 return 0 free memory freepiLen fori 0 i iRows iCols i freepstDatai freepstData freepstOut LhsVar1 Rhs 1 return 0 Scilab test script aref may the puffin be with you a may the puffin bewithyou b readstringa if aref b then errorfailed end 3295 Name String writing Scilab gateway How to write matrices of string in a gateway Input argument profile SciErr createMatrixOfStringvoid pvCtx int iVar int iRows int iCols char pstStrings SciErr createMatrixOfWideStringvoid pvCtx int iVar int iRows int iCols wchart pwstStrings Named variable profile SciErr createNamedMatrixOfStringvoid pvCtx char pstName int iRows int iCols char pstStrings SciErr createNamedMatrixOfWideStringvoid pvCtx char pstName int iRows int iCols wchart pwstStrings Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Numbers of columns of the new variable pstStrings Address of array of char size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of strings can be handled through the Scilab API Gateway Source int writestringchar fnameunsigned long fnamelen SciErr sciErr variable info matrix of string 2 x 3 int iRows 2 int iCols 3 char pstData NULL data to put in the new variable char string11 may char string21 be String writing Scilab gateway 3296 char string12 the char string22 with char string13 puffin char string23 you alloc new array pstData charmallocsizeofchar iRows iCols copy data address to the main array pstData0 string11 pstData1 string21 pstData2 string12 pstData3 string22 pstData4 string13 pstData5 string23 create the variable sciErr createMatrixOfStringpvApiCtx Rhs 1 iRows iCols pstData ifsciErriErr printErrorsciErr 0 return 0 free container freepstData assign allocated variables to Lhs position LhsVar1 Rhs 1 return 0 Scilab test script aref may the puffin be with you b a writestring for i1sizear for j1sizeac b b aij b b end end if b aref then errorfailed end Parte LVIII Gerenciamento de ajuda online 3298 Name addhelpchapter adiciona uma entrada na lista de ajudas addhelpchaptertitlepathmode Parâmetros title string o título da ajuda path string o endereço do diretório contendo os arquivos de ajuda mode booleano T se o diretório pertence à lista de módulos do Scilab F em caso contrário tool boxes O valor padrão é F Descrição Esta função adiciona uma nova entrada na lista de ajudas Os arquivos do capítulo de ajuda devem estar localizados em um único diretório Se o dado título title já existir na lista de ajudas associado com o mesmo endereço nada é feito A função verifica se o diretório existe Ver Também help adddemo Autor Serge Steer INRIA 3299 Name apropos procura por palavraschave na ajuda do Scilab aproposkey aproposregexp Parâmetros key string Fornece a seqüência de caracteres a ser encontrada regexp string Fornece a expressão regular a ser encontrada apenas com Scilab Browser Descrição aproposkey procura por arquivos de ajuda Scilab contendo a palavrachave key na seção de descrições breves aproposregexp procura por arquivos de ajuda Scilab contendo a expressão regular regexp na seção de descrições breves Exemplos aproposode apropos ode apropos list of apropos sinhyperbolic apropos ab procura por ajuda começando com os dois caracteres ab apropos quadraticsolver Ver Também help man 3300 Name foo descrição breve de foo y foox Parâmetros x o que puder ser x y o que puder ser y Descrição Um primeiro parárgrafo que explica o que a função foo computa Se quiser enfatizar um parâmetro então você utiliza o seguinte tag x se quiser enfatizar parte do texto encerreo nestes tags e então utilize estes para obter uma fonte em negrito e finalmente para um estilo em máquina de escrever Um segundo parágrafo Aqui está um exemplo de um link para outra página man first parágrafo simples second toto é o foo francês Exemplos deffyfooxyx define a função foo como a função identidade foototo Ver Também man apropos Autor B P 3301 Name help comando de ajuda online helpkey help Parâmetros key string Fornece a página de ajuda a ser encontrada Descrição help sem argumentos fornece a página de hipertextos dos capítulos de ajuda helpkey exibe o arquivo de ajuda Scilab associado ao dado key Se nenhum arquivo for encon trado helpkey chama automaticamente aproposkey Ver man para mais explicações sobre como escrever novas páginas Ver Também apropos man 3302 Name helpfromsci Geração de arquivos de ajuda e de arquivos de demonstração a partir da seção de comentários de cabeçalho de um arquivofonte sci helpfromsci gera um modelo de função vazio helpfromscifunnamehelpdir gera helpdirfunnamexml a partir de funnamesci helpfromscidirnamehelpdir processa dirnamesci e cria helpdirxml helpfromscidirnamehelpdirhelpdir como acima mas também cria o arquivo de demonstração helpdirdemsce helptxtdemotxthelpfromscifunname retorna funnamexml e funnamedemsce como duas matrizes de texto Parâmetros funname o nome de um único arquivo sci a ser processado dirname nome do diretório onde todos os arquivos sci serão processados helpdir endereço opcional onde o arquivo de ajuda xml será criado demodir endereço opcional onde os arquivos de demonstração demsce serão criados baseados nos códigos da seção Examples helptxt retorna o código da ajuda XML se helpdir for vazio ou o endereço para o novo arquivo xml demotxt retorna o código de demonstração se demodir for vazio ou o endereço para o novo arquivo demsc Descrição helpfromsci é uma versão revisada da função helpskeleton Seu objetivo é gerar arquivos de aju da xml baseados na seção de comentários de cabeçalho dos arquivosfontes sci Opcionalmente os arquivos de demonstração demsce podem ser gerados baseados nos códigos da seção Examples na seção de cometários de cabeçalho dos arquivos sci Para que helpfromsci formate o arquivo xml propriamente os a seção de comentários de cabeçalho deve concordar com algumas regras simples de formatação A primeira linha de comentário seguinte à definição de função deve conter uma descrição breve da função Os comentários restantes são formatados de acordo com os seguintes cabeçalhos opcionais Call ing Sequence Parameters Description Examples See also Used functions Authors e Bibliography As seguintes diretrizes devem ser seguidas ao se escrever os comentários de código fonte Calling Sequence um exemplo por linha Parameters separe o nome do parâmetro e a descrição por um Mantenha a descrição de cada parâmetro na mesma linha Description a formatação do texto pode ser feita utilizando comandos XML Adicionar uma linha de comentário vazia na seção Description é interpretado como começo de um novo parágrafo helpfromsci 3303 See also liste um nome de função por linha Authors escreva um autor em cada linha após o cabeçalho Authors Use para separar os autores de qualquer informação adicional Bibliography escreva uma referência por linha seguindo o cabeçalho References Exemplos helpfromsci abrindo um modelo de códigofonte vazio no editor salve este modelo como testfunsci no diretório corrente antes de executar os próximos comandos do exemplo helpfromscitestfun retornando o esqueleto xml como um string de texto helpfromscitestfun criando o arquivo de ajuda xml no diretório corrente criando ambos os arquivos de ajuda e demonstração no diretório corrente helpfromscitestfun de um diretório raiz de um toolbox uma seqüência de chamamento típica seria helpfromscimacroshelpptBRdemos este comando processaria todos os arquivos sci no diretório de macros e utilizaria a seção de comentários de cabeçalho para atualizar as ajudas xml no diretório helpenUS e reconstruiria os arquivos demsce no diretório demos Ver Também help helpskeleton xmltohtml Autor T Pettersen torbjornpettersenbroadparkno 3304 Name helpskeleton constrói o esqueleto do arquivo de ajuda xml associado à função Scilab txt helpskeletonfunname path language Parâmetros funname string o nome da função path string o endereço onde se criará o arquivo se for requerido Se este argumento não for fornecido o esqueleto é retornado como um string language string com valor possível frFR ou enUS o padrão é enUS txt o código xml ou o endereço do arquivo xml completo Descrição txt helpskeletonfunname gera um vetor de strings contendo o esqueleto do código XML descrevendo a ajuda da função funname fullpath helpskeletonfunnamedirpath gera o código XML descrevendo a aju da da função funname em um arquivo nomeado funnamexml no diretório especificado pelo endereço dirpath Neste caso a função retorna o endereço do arquivo Exemplos function yzfooabyabz1endfunction phelpskeletonfooTMPDIR if isdefeditor funptreditor0 then editorp end Ver Também help Autor Serge Steer INRIA 3305 Name makeindex cria um novo arquivo de índice para ajuda online makeindex Descrição A ajuda online lê primeiro o arquivo indexhtml que contém a lista dos capítulos Este arquivo vem com o Scilab e está no diretório SCIDIRmanlanguage ver man É possível modificar este arquivo de índice enquanto se adiciona interativamente novos arquivos Para isto modifique a variável helps e então utilize a função makeindex Ver Também helps man 3306 Name man Descrição do formato do arquivo de ajuda XML Descrição Os arquivosfontes da ajuda Scilab são escritos em formato XML Arquivosfontes com extensão xml podem ser encontrados nos diretórios SCIDIRman language O nome do arquivo é geralmente associado à palavrachave correspondente a um nome de função na maioria dos casos que descreve Breves palavras sobre XML Um arquivo XML lembra um arquivo HTML mas possui uma sintaxe tanto mais rígida quanto mais livre Livre porque você pode construir os seus próprios tags marcação o conjunto de tags junto com suas regras deve ser descrito em algum lugar geralmente em outro arquivo SCIDIRman manrevdtd para o Scilab e rígida porque uma vez que os tags e regras são definidas as quais são chamadas Definição de Tipo de Documento Document Type Definition DTD você deve re speitálas em particular para todos os tags MYTAG abertos deve corresponder um tag fechado MYTAG O DTD manrevdtd é escrito em SGML e precisa a exata sintaxe requerida por uma página de ajuda XML do Scilab Então se você conhece esta linguagem você pode ler este arquivo O seguinte exemplo anotado veja a próxima seção mostra algumas possibilidades oferecidas por este DTD e pode ser suficiente para escrever páginas de ajuda simples Uma vez que a página XML é escrita e está em conformidade com o DTD ela pode ser transformada em um HTML para ser lida por algum navegador de internet ou pelo navegador tcltk do Scilab ver a seção escolha do navegador nesta página A tradução XML HTML é controlada por um conjunto de regras escritas no arquivo XML SCIDIRmanlanguagehtmlxsl Estas regras estão correntemente mais ou menos restritas para se adequarem aos recursos do navegador tcltk do Scilab que pode exibir corretamente apenas HTML básico Se você utilizar um navegador de HTML e quiser melhorar a aparência terá que modificar este arquivo Como escrever uma página de ajuda XML do Scilab simples a maneira lazzy Caso se deseje escrever um arquivo XML associado a uma nova função Scilab podese utilizar a função helpskeleton para produzir o esqueleto do arquivo XML Na maior parte dos casos o usuário não precisará saber a sintaxe XML Como escrever uma página de ajuda XML do Scilab simples um exemplo Aqui está um exemplo simples de uma página de ajuda XML que descreve uma função do Scilab hipotética chamada foo No seguinte o arquivo XML é exibido em uma fonte de máquina deescrever e recortado em várias partes cada parte precedida por algumas explicações as sociadas O arquivo XML inteiro fooxml está no diretório SCIDIRmanengutili ty e o resultado pode ser exibido clicandose em foo você pode encontrar outros exemplos no diretório SCIDIRexamplesmanexamplesxml Finalmente note que alguns pares de tags TAG TAG foram renomeados aqui ATAG ATAG Isto porque alguns scripts do Scilab que realizam trabalhos sobre ou a partir dos arquivos XML não verificam se um tag está dentro de uma entrada VERBATIM As primeiras três linhas do arquivo são mandatórias a segunda precisa o endereço para o arquivo DTD e a terceira formada pelo tag MAN inicia a descrição hierárquica o arquivo deve terminar man 3307 com o tag MAN As quatro entradas seguintes LANGUAGE TITLE TYPE e DATE também são mandatórias nesta ordem o texto correspondente a TYPE sendo geralmente função do Scilab na maior parte dos casos mas pode ser simplesmente palavrachave do Scilab ou tipo de dados do Scilab dependendo do que explica a página de ajuda DOCTYPE MAN SYSTEM SCIDIRmanmanrevdtd MAN LANGUAGEengLANGUAGE TITLEfooTITLE TYPEfunção do ScilabTYPE DATELastChangedDateDATE A primeira destas duas entradas seguintes SHORTDESCRIPTION é mandatória e importante des de que as palavras do texto da descrição curta short description são utilizadas pelo comando apro pos para buscar páginas de ajuda a partir de uma palavrachave a descrição curta é utilizada para construir o arquivo whatishtml correspondente ao seu toolbox e o comando apropos key word faz uma pesquisa em todos os arquivos whatis e propõe os links para cada página onde a palavra keyword se encontra em sua descrição curta na verdade os tags reais associados são SHORTDESCRIPTION e SHORTDESCRIPTION e não ASHORTDESCRIPTION e ASHORTDESCRIPTION A próxima entrada CALLINGSEQUENCE deve ser utilizada ao se descrever uma função mas não é estritamente mandatória Se a sua função possui várias seqüências de chamamento utilize várias entradas CALLINGSEQUENCEITEM ASHORTDESCRIPTION namefoodescrição curta de fooASHORTDESCRIPTION CALLINGSEQUENCE CALLINGSEQUENCEITEMy fooxCALLINGSEQUENCEITEM CALLINGSEQUENCE A entrada seguinte PARAM não é estritamente mandatória mas é a boa para descrever cada parâmetro de entrada e saída no caso de uma função PARAM PARAMINDENT PARAMITEM PARAMNAMExPARAMNAME PARAMDESCRIPTION SP o que pode ser xSP PARAMDESCRIPTION PARAMITEM PARAMITEM PARAMNAMEyPARAMNAME PARAMDESCRIPTION SP o que pode ser ySP PARAMDESCRIPTION PARAMITEM PARAMINDENT PARAM A entrada DESCRIPTION é talvez a mais significativa mas não é estritamente mandatória e pode ser mais sofisticada que neste exemplo por exemplo você pode ter subentradas DESCRIPTIONITEM Aqui você vê como escrever vários parágrafos cada um encerrado pelos tags P e P como enfatizar uma variável ou um nome de função encerrandoos por tags VERB e VERB como enfatizar uma parte o texto EM ou BD e TT para colocar em man 3308 fonte de máquina de escrever e finalmente como colocar um link para outra página de ajuda na verdade os tags associados são LINK e LINK e não ALINK e ALINK DESCRIPTION P Um primeiro parágrafo explica o que a função foo computa Se você deseja enfatizar um nome de parâmetro você pode utilizar o segunte tag VERBxVERB se você desejar enfatizar parte do texto EMencerrea nestes tagsEM e use estes BDpara uma fonte em negritoBD e finalmente TTpara um estilo em máquina de escreverTT P P Um segundo parágrafo Aqui vai um exemplo de um link para outra página ALINKmanALINK P DESCRIPTION Aqui está como escrever a sua própria entrada por exemplo para escrever observações eou notas sobre a sua maravilhosa função SECTION labelNotes P Aqui está uma lista de notas P ITEM labelfirstSPblablablaSPITEM ITEM labelsecondSPtoto é o francês de fooSPITEM SECTION Uma entrada importante é EXAMPLE que é reservada para mostrar usos no Scilab da sua função comece com exemplos simples Note que você deve fechar esta entrada com EXAMPLE e não como aqui com EXAMPLE mais uma vez este é um truque ruim para evitar problemas de interpretação EXAMPLECDATA deffyfooxyx definindo a função foo como a função identidade foototo EXAMPLE Esta última parte explica como colocar links para outras páginas de ajuda relacionadas como já foi dito antes os bons tags são LINK e LINK e não ALINK e ALINK e finalmente como revelar o seu nome se você quiser utilize uma entrada AUTHORITEM por autor Talvez seja uma boa idéia colocar um endereço de email se você procura por relatos de bugs SEEALSO SEEALSOITEM ALINKmanALINK SEEALSOITEM SEEALSOITEM ALINKaproposALINK SEEALSOITEM SEEALSO AUTHOR AUTHORITEMB PAUTHORITEM AUTHOR MAN man 3309 Como criar um capítulo de ajuda Crie um diretório e escreva um conjunto de arquivos XML construídos como descrito acima Então inicie o Scilab e execute xmltohtmldir onde é um dir string fornecendo o endereço do diretório ver xmltohtml para mais detalhes Como fazer o Scilab reconhecer um novo capítulo de ajuda Isto pode ser feito através da função addhelpchapter Exemplos function yfooabcya2bcendfunction pathhelpskeletonfooTMPDIR if isdefeditor funptreditor0 then editorpath end Ver Também apropos help helpskeleton 3310 Name manedit editando item do manual maneditmanitem Parâmetros manitem string geralmente o nome de uma função Descrição editmanitem abre o arquivo xml associado a manitem no editor Se não há arquivo xml associado a manitem e manitem é o nome de uma função Scilab o xpad abre com o esqueleto do arquivo xml produzido por helpskeleton Este arquivo está localizado em TMPDIR Exemplos maneditmanedit function xyzfoo123ab xabyabzab endfunction manedit foo123 Ver Também help helpskeleton 3311 Name helps variável definindo o endereço dos diretórios de ajuda Descrição A variável global helps é uma matriz N x 2 de strings A késima linha de helps helpsk representa o késimo capítulo do manual e é feita de dois strings helpsk1 é o nome de endereço absoluto de um diretório helpsk2 é um título para este diretório Por exemplo para k2 nós temos o capítulo de gráficos helps2 A variável helps é definida no arquivo de inicialização do Scilab SCIscilabstart Para adicionar um novo diretório de ajuda o usuário deve adicionar uma linha a helps Uma linha para cada diretório Por exemplo helpshelps PathOfMyHelpDirMyTitle habilita o navegador de ajuda do Scilab a procurar por itens do manual de ajuda no diretório com endereço PathOfMyHelpDir MyTitle é então o título do novo capítulo de ajuda Um diretório válido deve conter 1 Um conjunto de arquivoshtml ex item1html item2html etc Os arquivos html são geralmente construídos de arquivos XML 2 Um arquivo whatishtml que deve conter um formato especial Cada linha de whatis deve ser como segue BRA HREFitemhtmlitemA rápida descrição item é o item da ajuda ie o comando help item exibe o conteúdo do arquivo itemhtml O comando apropos keyword retorna as linhas de todos os arquivos whatishtml nos quais a palavrachave keyword aparece Em plataformas Linux o Scilab provê um Makefile para transformar páginas xml pages em páginas html ver SCIDIRexamplesmanexamples Ver Também apropos help man 3312 Name xmltohtml converte arquivos de ajuda xml do Scilab para formato HTML xmltohtmldirs titles dirlanguage defaultlanguage Parâmetros dirs vetor de strings um conjunto de endereços de diretórios para os quais os manuais html devem ser gerados ou titles vetor de strings títulos associados a endereços de diretórios ou dirlanguage vetor de strings idiomas associados a endereços de diretórios ou defaultlanguage vetor de strings idiomas padrões associados aos endereços de diretórios ou Se um arquivo XML estiver faltando em dirlanguage ele é copiado de defaultlanguage Descrição Converte arquivos de ajuda Scilab contidos em um conjunto de diretórios para formato HTML Exemplos example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Construindo a ajuda em francês myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR myfrenchhtmldir xmltohtmlmyfrenchhelpdirmyfrenchhelptitlefrFR Construindo a ajuda em inglês myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 enUS myenglishhtmldir xmltohtmlmyenglishhelpdirmyenglishhelptitleenUS xmltohtml 3313 Construindo a ajuda em chinês mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW mychinesehtmldir xmltohtmlmychinesehelpdirmychinesehelptitlezhTW Ver Também help addhelpchapter 3314 Name xmltojar converte arquivos de ajuda xml do Scilab para formato javaHelp xmltojardirs titles dirlanguage defaultlanguage Parâmetros dirs vetor de strings um conjunto de endereços de diretórios para os quais os manuais html devem ser gerados ou titles vetor de strings títulos associados a endereços de diretórios ou dirlanguage vetor de strings idiomas associados a endereços de diretórios ou defaultlanguage vetor de strings idiomas padrões associados aos endereços de diretórios ou Se um arquivo XML estiver faltando em dirlanguage ele é copiado de defaultlanguage Descrição Converte arquivos de ajuda Scilab contidos em um conjunto de diretórios para formato jar Exemplos example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Construindo a ajuda em francês myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR xmltojarmyfrenchhelpdirmyfrenchhelptitlefrFR Construindo a ajuda em inglês myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 enUS xmltojarmyenglishhelpdirmyenglishhelptitleenUS xmltojar 3315 Construindo a ajuda em chinês mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW xmltojarmychinesehelpdirmychinesehelptitlezhTW Adicionando capítulos de ajuda em francês inglês e chinês if getlanguage frFR then addhelpchaptermyfrenchhelptitlemymodulepathjar elseif getlanguage zhTW then addhelpchaptermychinesehelptitlemymodulepathjar else addhelpchaptermyenglishhelptitlemymodulepathjar end Ver o resultado no navegador de ajuda help Deletando capítulos de ajuda em francês e inglês if getlanguage frFR then delhelpchaptermyfrenchhelptitle else delhelpchaptermyenglishhelptitle end Ver Também help addhelpchapter 3316 Name xmltopdf converte arquivos de ajuda xml do Scilab para formato PDF xmltopdfdirs titles dirlanguage defaultlanguage Parâmetros dirs vetor de strings um conjunto de endereços de diretórios para os quais os manuais pdf devem ser gerados ou titles vetor de strings títulos associados a endereços de diretórios ou dirlanguage vetor de strings idiomas associados a endereços de diretórios ou defaultlanguage vetor de strings idiomas padrões associados aos endereços de diretórios ou Se um arquivo XML estiver faltando em dirlanguage ele é copiado de defaultlanguage Descrição Converte arquivos de ajuda Scilab contidos em um conjunto de diretórios para formato PDF Exemplos example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Construindo a ajuda em francês myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR myfrenchpdf xmltopdfmyfrenchhelpdirmyfrenchhelptitlefrFR Construindo a ajuda em inglês myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 enUS myenglishpdf xmltopdfmyenglishhelpdirmyenglishhelptitleenUS xmltopdf 3317 Construindo a ajuda em chinês mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW mychinesepdf xmltopdfmychinesehelpdirmychinesehelptitlezhTW Ver Também help addhelpchapter 3318 Name xmltops converte arquivos de ajuda xml do Scilab para formato Postscript xmltopsdirs titles dirlanguage defaultlanguage Parâmetros dirs vetor de strings um conjunto de endereços de diretórios para os quais os manuais postscript devem ser gerados ou titles vetor de strings títulos associados a endereços de diretórios ou dirlanguage vetor de strings idiomas associados a endereços de diretórios ou defaultlanguage vetor de strings idiomas padrões associados aos endereços de diretórios ou Se um arquivo XML estiver faltando em dirlanguage ele é copiado de defaultlanguage Descrição Converte arquivos de ajuda Scilab contidos em um conjunto de diretórios para formato PS Exemplos example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Construindo a ajuda em francês myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR myfrenchps xmltopsmyfrenchhelpdirmyfrenchhelptitlefrFR Construindo a ajuda em inglês myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 ENUS myenglishps xmltopsmyenglishhelpdirmyenglishhelptitleenUS xmltops 3319 Construindo a ajuda em chinês mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW mychineseps xmltopsmychinesehelpdirmychinesehelptitlezhTW Ver Também help addhelpchapter 3320 Name delhelpchapter Delete an entry in the helps list delhelpchaptertitlemode Parameters title String array Help chapters title mode A boolean if TRUE the chapter is considered as belongs to a internal modules otherwise the chapter is added as external module Its an optional input argument and its default value is F Description This function deletes an entry in the helps list See Also help addhelpchapter 3321 Name xmltochm converts xml Scilab help files to Microsoft Compressed HTML format Windows xmltochmdirs titles dirlanguage defaultlanguage Parameters dirs vector of strings a set of directory paths for which html manuals are to be generated or titles vector of strings titles associated to directory paths or dirlanguage vector of strings languages associated to directory paths or defaultlanguage vector of strings default languages associated to directory paths or If an XML file is missing in the dirlanguage its copied from the defaultlanguage Description converts xml Scilab help files contained in a set of directories into chm files Microsoft HTML Help Downloads Windows httpmsdnmicrosoftcomenusli braryms669985VS85aspx Examples example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Build the french help myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR res xmltochmmyfrenchhelpdirmyfrenchhelptitlefrFR if MSDOS then dosstart res end xmltochm 3322 Build the english help myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 enUS res xmltochmmyenglishhelpdirmyenglishhelptitleenUS if MSDOS then dosstart res end Build the chinese help mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW res xmltochmmychinesehelpdirmychinesehelptitlezhTW if MSDOS then dosstart res end See Also help addhelpchapter
Envie sua pergunta para a IA e receba a resposta na hora
Recomendado para você
47
Scilab Manual for Digital Signal Processing
Sinais e Sistemas
UNINTER
170
Fundamentos de SCILAB
Sinais e Sistemas
UNINTER
1
Atividade Prática em Sinais e Sistemas - Exemplo 1
Sinais e Sistemas
UNINTER
1
Exercício Escolar de Sinais e Sistemas
Sinais e Sistemas
UPE
55
Princípios de Telecomunicações - Aulas 2 e 3
Sinais e Sistemas
CEFET/RJ
4
Exercício Resolvido-2023-2
Sinais e Sistemas
UTFPR
14
Lista Laplace Resolvida e Anotações com Resolução-2023 1
Sinais e Sistemas
UTFPR
1
Referências Bibliográficas
Sinais e Sistemas
CEFET/RJ
3
Lista Final-2023-1
Sinais e Sistemas
UTFPR
1
Atividade de Acompanhamento Filtros Digitais 2023 1
Sinais e Sistemas
UTFPR
Texto de pré-visualização
Manual Scilab Manual Scilab iii Índice I Scilab 1 abort 2 adddemo 3 ans 4 argn 5 backslash 6 banner 7 boolean 8 brackets 9 break 10 case 11 clear 12 clearfun 13 clearglobal 14 colon 15 comma 16 comments 17 comp 18 comparison 19 continue 21 debug 22 delbpt 23 dispbpt 24 do 25 dot 26 edit 27 else 28 elseif 29 empty 30 end 31 equal 32 errcatch 33 errclear 34 error 35 errortable 36 evstr 45 exists 46 exit 47 external 48 extraction 49 for 52 format 53 funcprot 55 funptr 56 getdebuginfo 57 getmd5 58 getmemory 59 getmodules 60 getos 61 getscilabmode 62 getshell 63 getvariablesonstack 64 getversion 65 global 66 gstacksize 67 Manual Scilab iv hat 68 ieee 69 if then else 70 insertion 71 intppty 75 invcoeff 76 iserror 77 isglobal 78 lasterror 79 left 80 less 81 macr2lst 82 macr2tree 84 matrices 85 matrix 86 mode 87 mtlbmode 88 names 89 newfun 90 null 91 parents 92 pause 94 percent 95 perl 96 plus 97 poly 98 power 99 predef 100 quit 101 quote 102 rational 103 readgateway 104 resume 105 return 106 sciargs 107 scilab 108 select 110 semicolon 111 setbpt 112 sethomedirectory 113 slash 114 stacksize 115 star 116 startup 117 symbols 118 testmatrix 119 then 120 tilda 121 try 122 type 123 typename 124 user 125 varn 126 ver 127 warning 128 what 129 where 130 whereami 131 Manual Scilab v while 132 who 133 whouser 134 whos 135 withatlas 136 withgtk 137 withjavasci 138 withmacrossource 139 withmodule 140 withpvm 141 withtexmacs 142 withtk 143 II Equações Diferenciais 144 dae 145 daeoptions 150 dasrt 152 dassl 156 feval 161 impl 162 int2d 164 int3d 166 intc 169 integrate 170 intg 172 intl 174 ode 175 odediscrete 180 odeoptionaloutput 181 oderoot 183 odedc 185 odeoptions 188 bvode 189 III Funções Elementares 203 abs 204 acos 205 acosd 206 acosh 207 acoshm 208 acosm 209 acot 210 acotd 211 acoth 212 acsc 213 acscd 214 acsch 215 adj2sp 216 amell 217 and 218 asec 219 asecd 220 asech 221 asin 222 asind 223 asinh 224 asinhm 225 asinm 226 atan 227 atand 229 Manual Scilab vi atanh 230 atanhm 231 atanm 232 base2dec 233 bin2dec 234 binomial 235 bitand 237 bitor 238 bloc2exp 239 bloc2ss 242 cat 245 ceil 246 cell2mat 247 cellstr 248 char 249 conj 251 cos 252 cosd 253 cosh 254 coshm 255 cosm 256 cotd 257 cotg 258 coth 259 cothm 260 csc 261 cscd 262 csch 263 cumprod 264 cumsum 265 dec2bin 266 dec2hex 267 dec2oct 268 delip 269 diag 270 diff 271 double 272 dsearch 273 eval 275 exp 276 eye 277 factor 278 fix 279 flipdim 280 floor 281 frexp 282 gsort 283 hex2dec 285 imag 286 imult 287 ind2sub 288 int 289 intersect 290 inttrap 292 isdef 293 isempty 294 isequal 295 isequalbitwise 296 Manual Scilab vii isinf 297 isnan 298 isreal 299 kron 300 lexsort 301 linspace 302 log 303 log10 304 log1p 305 log2 306 logm 307 logspace 308 lstsize 309 max 310 maxi 311 meshgrid 312 min 313 mini 314 minus 315 modulo 316 ndgrid 317 ndims 319 nearfloat 320 nextpow2 321 norm 322 not 323 numberproperties 324 oct2dec 326 ones 327 or 328 pen2ea 329 perms 330 permute 331 pertrans 332 primes 333 prod 334 rand 335 rat 337 real 338 resizematrix 339 round 340 sec 341 secd 342 sech 343 setdiff 344 sign 345 signm 346 sin 347 sinc 348 sind 349 sinh 350 sinhm 351 sinm 352 size 353 solve 355 sort 356 sp2adj 358 speye 359 Manual Scilab viii spones 360 sprand 361 spzeros 362 sqrt 363 sqrtm 364 squarewave 365 ssrand 366 sub2ind 368 sum 369 sysconv 370 sysdiag 372 syslin 373 tan 375 tand 376 tanh 377 tanhm 378 tanm 379 toeplitz 380 trfmod 381 trianfml 382 tril 383 trisolve 384 triu 385 typeof 386 union 388 unique 389 vectorfind 391 zeros 392 393 csgn 394 isvector 395 396 IV Funções 397 addprofiling 398 bytecode 399 bytecodewalk 400 deff 401 exec 402 execstr 404 fun2string 406 function 407 functions 409 genlib 411 getfunctionpath 412 getd 413 headcomments 414 lib 415 librarieslist 417 library 418 libraryinfo 419 listfunctions 420 macro 421 macrovar 422 plotprofile 423 profile 424 recompilefunction 425 removeprofiling 426 resetprofiling 427 Manual Scilab ix showprofile 428 varargin 429 varargout 430 whereis 431 getf 432 V Arquivos funções de EntradaSaída 434 chdir 435 fileinfo 436 getabsolutefilepath 438 getrelativefilename 439 newest 440 sscanf 441 basename 442 copyfile 443 createdir 444 deletefile 445 dir 446 dirname 447 dispfiles 448 fileext 449 fileparts 450 filesep 451 findfiles 452 fprintf 453 fprintfMat 454 fscanf 455 fscanfMat 456 fullfile 457 fullpath 458 getdrives 459 getlongpathname 460 getshortpathname 461 io 462 isdir 463 isfile 464 listfiles 465 listvarinfile 466 ls 467 maxfiles 468 mclearerr 469 mclose 470 mdelete 471 meof 472 merror 473 mfprintf 474 mscanf 475 mget 478 mgetl 480 mgetstr 481 mkdir 482 mopen 483 movefile 486 mput 487 mputl 489 mputstr 490 mseek 491 mtell 492 pathconvert 493 Manual Scilab x pathsep 494 pwd 495 removedir 496 rmdir 497 saveformat 498 scanf 501 scanfconversion 502 VI Biblioteca de Gráficos 504 GlobalProperty 505 Graphics 509 LineSpec 515 Matplot 517 Matplot1 520 Matplotproperties 522 Sfgrayplot 524 Sgrayplot 526 addcolor 529 alufunctions 530 arcproperties 531 autumncolormap 533 axesproperties 534 axisproperties 542 bar 545 barh 547 barhomogenize 549 bonecolormap 551 captions 552 champ 554 champ1 556 champproperties 558 clearpixmap 560 clf 561 color 563 colorlist 564 colorbar 585 colordef 587 colormap 588 Compoundproperties 589 contour 590 contour2d 593 contour2di 595 contourf 597 coolcolormap 599 coppercolormap 600 copy 601 delete 602 dragrect 603 draw 604 drawaxis 605 drawlater 607 drawnow 609 editcurv 610 errbar 611 eval3d 612 eval3dp 613 event handler functions 614 fac3d 617 fchamp 618 Manual Scilab xi fcontour 620 fcontour2d 621 fec 622 fecproperties 625 fgrayplot 627 figureproperties 628 fplot2d 631 fplot3d 632 fplot3d1 633 gca 634 gce 635 gcf 636 gda 637 gdf 639 ged 640 genfac3d 641 geom3d 642 get 643 getfigurehandle 645 getcolor 646 getfont 647 getlinestyle 648 getmark 649 getsymbol 650 glue 651 graduate 652 graphicsentities 653 graphicsfonts 656 graycolormap 658 grayplot 659 grayplotproperties 660 graypolarplot 662 havewindow 664 hist3d 665 histplot 666 hotcolormap 668 hsv2rgb 669 hsvcolormap 671 ishandlevalid 672 isoview 673 jetcolormap 674 labelproperties 675 legend 677 legendproperties 679 legends 682 locate 684 mesh 685 milkdrop 687 move 688 name2rgb 689 newaxes 690 nf3d 691 objecteditor 692 oceancolormap 697 oldplot 698 param3d 699 param3d1 701 param3dproperties 704 Manual Scilab xii paramfplot2d 706 pie 707 pinkcolormap 708 plot 709 plot2d 714 plot2d1 719 plot2d2 721 plot2d3 722 plot2d4 723 plot2doldversion 724 plot3d 728 plot3d1 737 plot3d2 740 plot3d3 743 plotframe 746 plzr 748 polarplot 749 polylineproperties 751 rainbowcolormap 755 rectangleproperties 756 relocatehandle 759 replot 760 rgb2name 761 rotate 762 rotateaxes 763 rubberbox 764 sca 765 scaling 766 scf 767 sd2sci 768 sda 769 sdf 770 secto3d 771 segsproperties 772 set 775 seteventhandler 777 showpixmap 778 showwindow 779 springcolormap 780 square 781 stringbox 782 subplot 784 summercolormap 785 surf 786 surfaceproperties 790 swaphandles 794 textproperties 796 title 799 titlepage 801 twinkle 802 unglue 803 unzoom 804 whitecolormap 805 winsid 806 wintercolormap 807 xarc 808 xarcs 809 xarrows 810 Manual Scilab xiii xbasc 811 xbasr 812 xchange 813 xclear 814 xclick 815 xdel 817 xfarc 818 xfarcs 819 xfpoly 820 xfpolys 821 xfrect 823 xget 824 xgetech 826 xgetmouse 828 xgraduate 830 xgrid 831 xinfo 832 xlfont 833 xload 835 xname 836 xnumb 837 xpause 838 xpoly 839 xpolys 840 xrect 841 xrects 842 xrpoly 843 xsave 844 xsegs 845 xselect 846 xset 847 xsetech 850 xsetm 852 xstring 853 xstringb 854 xstringl 855 xtitle 856 zoomrect 857 Math rendering in Scilab graphics 859 VII Gráficos exportando e imprimindo 861 driver 862 xend 863 xinit 864 xs2bmp 865 xs2emf 866 xs2eps 867 xs2fig 868 xs2gif 869 xs2jpg 870 xs2pdf 871 xs2png 872 xs2ppm 873 xs2ps 874 xs2svg 875 VIII Booleanos 876 bool2s 877 find 878 IX CACSD 879 Manual Scilab xiv black 880 bode 882 chart 884 evans 886 gainplot 887 mcircle 888 nyquist 889 routht 891 sgrid 892 zgrid 893 abcd 894 abinv 895 arhnk 899 arl2 900 arma 902 arma2p 904 armac 905 armax 906 armax1 908 arsimul 910 augment 911 balreal 913 bilin 914 bstap 915 cainv 916 calfrq 918 canon 919 ccontrg 921 cls2dls 922 colinout 923 colregul 924 contfrm 925 contmat 926 contr 927 contrss 929 copfac 930 csim 931 ctrgram 933 dbphi 934 dcf 935 ddp 936 des2ss 938 des2tf 939 dhinf 940 dhnorm 943 dscr 944 dsimul 945 dtility 946 dtsi 947 equil 948 equil1 949 feedback 950 findABCD 951 findAC 954 findBD 956 findBDK 960 findR 963 findx0BD 966 Manual Scilab xv flts 969 fourplan 972 frep2tf 973 freq 975 freson 976 fspecg 977 fstabst 978 gmargin 980 gamitg 981 gcare 982 gfare 983 gfrancis 984 gtild 986 h2norm 988 hcl 989 hinf 990 hinfst 991 hnorm 992 hankelsv 993 hinf 994 imrep2ss 997 inistate 998 invsyslin 1000 kpure 1001 krac2 1002 lcf 1003 leqr 1004 lft 1006 lin 1008 linf 1010 linfn 1011 linmeq 1012 lqe 1016 lqg 1018 lqg2stan 1019 lqgltr 1021 lqr 1022 ltitr 1024 macglov 1025 markp2ss 1026 minreal 1027 minss 1028 mucomp 1029 narsimul 1030 nehari 1031 noisegen 1032 obsgram 1033 obscont 1034 observer 1036 obsvmat 1038 obsvss 1039 pmargin 1040 parrot 1041 pfss 1042 phasemag 1043 ppol 1044 prbsa 1045 projsl 1046 Manual Scilab xvi reglin 1047 repfreq 1048 ricdesc 1050 ricc 1052 riccati 1054 rowinout 1055 rowregul 1056 rtitr 1057 sensi 1060 showmargins 1061 sident 1062 sm2des 1066 sm2ss 1067 sorder 1068 specfact 1072 ss2des 1073 ss2ss 1074 ss2tf 1076 stility 1077 stabil 1079 svplot 1080 sysfact 1082 syssize 1083 tf2des 1084 tf2ss 1085 timeid 1086 trzeros 1088 uiobserver 1090 unobs 1092 zeropen 1093 X Estruturas de Dados 1094 cell 1095 definedfields 1097 getfield 1098 hypermat 1099 hypermatrices 1100 iscell 1101 iscellstr 1102 isstruct 1103 list 1104 lsslist 1106 lstcat 1107 mlist 1108 rlist 1110 setfield 1111 struct 1112 tlist 1113 fieldnames 1114 isfield 1115 XI Shell 1116 clc 1117 lines 1118 prompt 1119 tohome 1120 XII Console 1121 console 1122 XIII Complementação 1123 completion 1124 Manual Scilab xvii XIV Gerenciador de histórico 1126 addhistory 1127 displayhistory 1128 gethistory 1129 gethistoryfile 1130 historymanager 1131 historysize 1132 loadhistory 1133 removelinehistory 1134 resethistory 1135 saveafterncommands 1136 saveconsecutivecommands 1137 savehistory 1138 sethistoryfile 1139 XV IGU 1140 1 Tree 1142 uiConcatTree 1143 uiCreateNode 1144 uiCreateTree 1145 uiDeleteNode 1146 uiDisplayTree 1148 uiDumpTree 1149 uiEqualsTree 1150 uiFindNode 1151 uiGetChildrenNode 1153 uiGetNodePosition 1154 uiGetParentNode 1155 uiInsertNode 1156 about 1158 addmenu 1159 clipboard 1161 close 1162 delmenu 1163 exportUI 1164 figure 1165 findobj 1167 gcbo 1168 getcallbackobject 1169 getinstalledlookandfeels 1170 getlookandfeel 1171 getvalue 1172 messagebox 1174 printfigure 1176 printsetupbox 1177 progressionbar 1178 rootproperties 1179 setlookandfeel 1180 setmenu 1182 toolbar 1183 toprint 1184 uicontrol 1186 uigetcolor 1191 uigetdir 1193 uigetfile 1194 uigetfont 1196 uimenu 1197 uiputfile 1199 unsetmenu 1200 Manual Scilab xviii usecanvas 1201 waitbar 1204 xchoices 1205 xchoose 1206 xchoosemodeless 1207 xdialog 1208 xmatrix 1209 xmdialog 1210 xmessagemodeless 1211 XVI Link Dinâmicoincremental 1212 call 1213 Gmake 1216 VCtoLCCLib 1217 addinter 1218 clink 1221 chooselcccompiler 1222 configurelcc 1223 configureifort 1224 configuremsvc 1225 dllinfo 1226 findlcccompiler 1227 findmsifortcompiler 1228 findmsvccompiler 1229 fort 1230 getdynlibext 1232 haveacompiler 1233 ilibbuild 1234 ilibcompile 1242 ilibforlink 1243 ilibgenMake 1245 ilibgencleaner 1247 ilibgengateway 1248 ilibgenloader 1250 ilibmexbuild 1251 ilibverbose 1252 link 1254 ulink 1256 withlcc 1257 XVII Inteiros 1258 iconvert 1259 int8 1260 inttype 1261 XVIII Interpolação 1262 bsplin3val 1263 cshep2d 1265 evalcshep2d 1267 interp 1269 interp1 1272 interp2d 1274 interp3d 1276 interpln 1278 intsplin 1279 linearinterpn 1280 lsqsplin 1284 smooth 1286 splin 1287 splin2d 1290 splin3d 1293 Manual Scilab xix XIX Funções de EntradaSaída 1295 file 1296 getenv 1299 getio 1300 getpid 1301 getscilabkeywords 1302 halt 1303 host 1304 input 1305 load 1306 oldload 1307 oldsave 1308 read 1309 read4b 1311 readb 1312 readc 1313 save 1314 setenv 1316 unix 1317 unixg 1318 unixs 1319 unixw 1320 unixx 1321 writb 1322 write 1323 write4b 1324 XX Funções de Saída 1325 disp 1326 print 1327 printf 1328 printfconversion 1329 sprintf 1332 ssprint 1333 diary 1334 mprintf 1337 msprintf 1338 prettyprint 1339 XXI Intersci 1341 intersci 1342 XXII JVM 1343 javaclasspath 1344 javalibrarypath 1345 jrepath 1346 systemgetproperty 1347 systemsetproperty 1350 withembeddedjre 1351 XXIII Álgebra Linear 1352 aff2ab 1353 balanc 1355 bdiag 1356 chfact 1357 chol 1358 chsolve 1359 classmarkov 1360 cmblin 1361 coff 1362 colcomp 1363 companion 1364 Manual Scilab xx cond 1365 det 1366 eigenmarkov 1367 ereduc 1368 expm 1369 fstair 1370 fullrf 1372 fullrfk 1373 genmarkov 1374 givens 1375 glever 1376 gschur 1377 gspec 1378 hess 1379 householder 1380 iminv 1381 inv 1382 kernel 1383 kroneck 1384 linsolve 1386 lsq 1388 lu 1390 lyap 1391 nlev 1392 orth 1393 pbig 1394 pencan 1395 penlaur 1396 pinv 1397 polar 1398 proj 1399 projspec 1400 psmall 1401 qr 1402 quaskro 1404 randpencil 1406 range 1407 rank 1408 rankqr 1409 rcond 1411 rowcomp 1412 rowshuff 1414 rref 1415 schur 1416 spaninter 1420 spanplus 1421 spantwo 1422 spec 1424 sqroot 1427 squeeze 1428 sva 1429 svd 1430 sylv 1431 trace 1432 XXIV Localização 1433 dgettext 1434 getdefaultlanguage 1435 getlanguage 1436 Manual Scilab xxi gettext 1437 LANGUAGE 1438 setdefaultlanguage 1439 setlanguage 1440 XXV Otimização e Simulação 1441 2 Neldermead 1443 fminsearch 1444 neldermead 1453 overview 1474 nmplot 1478 optimget 1489 optimplotfunccount 1491 optimplotfval 1492 optimplotx 1493 optimset 1494 3 Optimization base 1498 optimbase 1499 4 Optimization simplex 1513 optimsimplex 1514 NDcost 1530 aplat 1533 datafit 1534 derivative 1537 fitdat 1541 fsolve 1543 karmarkar 1546 leastsq 1547 list2vec 1553 lmisolver 1554 lmitool 1556 lsqrsolve 1557 numdiff 1560 optim 1562 qld 1576 qpsolve 1579 qpsolve 1582 quapro 1585 readmps 1586 recons 1590 semidef 1591 vec2list 1594 XXVI Sobrecarga 1595 overloading 1596 XXVII Polinômios 1598 bezout 1599 clean 1600 cmndred 1601 coeff 1602 coffg 1603 colcompr 1604 degree 1605 denom 1606 derivat 1607 determ 1608 detr 1609 diophant 1610 factors 1611 gcd 1613 Manual Scilab xxii hermit 1614 horner 1615 hrmt 1616 htrianr 1617 invr 1618 lcm 1619 lcmdiag 1620 ldiv 1621 numer 1622 pdiv 1623 pol2des 1624 pol2str 1625 polfact 1626 residu 1627 roots 1628 rowcompr 1629 sfact 1630 simp 1631 simpmode 1632 sylm 1633 systmat 1634 XXVIII Processamento de Sinais 1635 5 How to 1637 How to design an elliptic filter 1638 Signal 1646 analpf 1650 bilt 1652 buttmag 1654 casc 1655 cepstrum 1656 cheb1mag 1657 cheb2mag 1658 chepol 1659 convol 1660 corr 1662 cspect 1665 czt 1668 detrend 1670 dft 1672 ell1mag 1673 eqfir 1674 eqiir 1675 faurre 1676 ffilt 1677 fft 1678 fft2 1680 fftshift 1682 filtsinc 1684 filter 1685 findfreq 1686 findm 1687 frfit 1688 frmag 1689 fsfirlin 1690 group 1692 hank 1693 hilb 1694 hilbert 1695 Manual Scilab xxiii iir 1696 iirgroup 1697 iirlp 1698 intdec 1699 jmat 1700 kalm 1701 lattn 1702 lattp 1703 lev 1704 levin 1705 lindquist 1708 mese 1709 mfft 1710 mrfit 1711 asn 1712 k 1713 sn 1714 phc 1715 pspect 1717 remez 1720 remezb 1722 rpem 1724 sincd 1726 srfaur 1727 srkf 1729 sskf 1730 syredi 1731 system 1733 trans 1734 wfir 1736 wiener 1737 wigner 1738 window 1739 yulewalk 1741 zpbutt 1742 zpch1 1743 zpch2 1744 zpell 1745 XXIX Matrizes Esparsas 1746 full 1747 ludel 1748 lufact 1749 luget 1751 lusolve 1752 mtlbsparse 1753 nnz 1754 sparse 1755 spchol 1756 spcompack 1757 spget 1759 gmres 1760 pcg 1762 qmr 1766 XXX Funções Especiais 1768 besseli 1769 beta 1772 calerf 1774 dlgamma 1775 Manual Scilab xxiv erf 1776 erfc 1777 erfcx 1778 erfinv 1779 gamma 1780 gammaln 1781 legendre 1782 oldbesseli 1785 XXXI Cadeias de Caracteres Strings 1788 ascii 1789 blanks 1790 code2str 1791 convstr 1792 emptystr 1793 grep 1794 isalphanum 1795 isascii 1796 isdigit 1797 isletter 1798 isnum 1799 justify 1800 length 1801 part 1802 regexp 1803 sci2exp 1804 str2code 1805 strcat 1806 strchr 1807 strcmp 1808 strcmpi 1809 strcspn 1810 strindex 1811 string 1813 strings 1814 stripblanks 1815 strncpy 1816 strrchr 1817 strrev 1818 strsplit 1819 strspn 1820 strstr 1821 strsubst 1822 strtod 1823 strtok 1824 tokenpos 1825 tokens 1826 tree2code 1827 XXXII Cálculos Formais 1828 addf 1829 ldivf 1830 mulf 1831 rdivf 1832 subf 1833 XXXIII Data e Hora 1834 date 1835 etime 1836 getdate 1837 tic 1839 Manual Scilab xxv toc 1840 calendar 1841 clock 1842 datenum 1843 datevec 1845 eomday 1846 now 1847 realtimeinit 1848 sleep 1849 timer 1850 weekday 1851 XXXIV Estatística 1852 cdfbet 1853 cdfbin 1854 cdfchi 1855 cdfchn 1856 cdff 1857 cdffnc 1858 cdfgam 1859 cdfnbn 1860 cdfnor 1861 cdfpoi 1862 cdft 1863 center 1864 wcenter 1865 cmoment 1866 correl 1867 covar 1868 ftest 1869 ftuneq 1870 geomean 1871 harmean 1872 iqr 1873 labostat 1874 mad 1875 mean 1876 meanf 1877 median 1878 moment 1879 msd 1880 mvvacov 1881 nancumsum 1882 nand2mean 1883 nanmax 1884 nanmean 1885 nanmeanf 1886 nanmedian 1887 nanmin 1888 nanstdev 1889 nansum 1890 nfreq 1891 pca 1892 perctl 1893 princomp 1894 quart 1896 regress 1897 sample 1898 samplef 1899 Manual Scilab xxvi samwr 1901 showpca 1902 stdeviation 1903 stdevf 1904 strange 1905 tabul 1906 thrownan 1908 trimmean 1909 variance 1911 variancef 1912 XXXV ARnoldi PACKage 1913 dnaupd 1914 dneupd 1922 dsaupd 1929 dsaupd 1937 znaupd 1942 zneupd 1950 XXXVI Funções de Compatibilidade 1956 asciimat 1957 firstnonsingleton 1958 makecell 1959 mstr2sci 1960 mtlb0 1961 mtlba 1962 mtlball 1963 mtlbany 1964 mtlbaxis 1965 mtlbbeta 1966 mtlbbox 1967 mtlbclose 1968 mtlbcolordef 1969 mtlbconv 1970 mtlbcumprod 1971 mtlbcumsum 1972 mtlbdec2hex 1973 mtlbdelete 1974 mtlbdiag 1975 mtlbdiff 1976 mtlbdir 1977 mtlbdouble 1978 mtlbe 1979 mtlbecho 1980 mtlbeval 1981 mtlbexist 1982 mtlbeye 1983 mtlbfalse 1984 mtlbfft 1985 mtlbfftshift 1986 mtlbfind 1987 mtlbfindstr 1988 mtlbfliplr 1989 mtlbfopen 1990 mtlbformat 1991 mtlbfprintf 1992 mtlbfread 1993 mtlbfscanf 1994 mtlbfull 1995 mtlbfwrite 1996 Manual Scilab xxvii mtlbgrid 1997 mtlbhold 1998 mtlbi 1999 mtlbifft 2000 mtlbimp 2001 mtlbint16 2002 mtlbint32 2003 mtlbint8 2004 mtlbis 2005 mtlbisa 2006 mtlbisfield 2007 mtlbisletter 2008 mtlbisspace 2009 mtlbl 2010 mtlblegendre 2011 mtlblinspace 2012 mtlblogic 2013 mtlblogical 2014 mtlblower 2015 mtlbmax 2016 mtlbmin 2017 mtlbmore 2018 mtlbnum2str 2019 mtlbones 2020 mtlbplot 2021 mtlbprod 2022 mtlbrand 2023 mtlbrandn 2024 mtlbrcond 2025 mtlbrealmax 2026 mtlbrealmin 2027 mtlbrepmat 2028 mtlbs 2029 mtlbsetstr 2030 mtlbsize 2031 mtlbsort 2032 mtlbstrcmp 2033 mtlbstrcmpi 2034 mtlbstrfind 2035 mtlbstrrep 2036 mtlbsum 2037 mtlbt 2038 mtlbtoeplitz 2039 mtlbtril 2040 mtlbtriu 2041 mtlbtrue 2042 mtlbuint16 2043 mtlbuint32 2044 mtlbuint8 2045 mtlbupper 2046 mtlbvar 2047 mtlbzeros 2049 XXXVII Interface Java 2050 javasciSciBoolean 2051 javasciSciBooleanArray 2053 javasciSciComplex 2055 javasciSciComplexArray 2057 javasciSciDouble 2060 Manual Scilab xxviii javasciSciDoubleArray 2062 javasciSciInteger 2064 javasciSciIntegerArray 2065 javasciSciString 2066 javasciSciStringArray 2068 javasciScilab 2070 Compile and run with javasci 2072 javasci 2074 javasci FAQ 2075 XXXVIII Interface Maple 2076 sci2map 2077 XXXIX Dicas de Conversão de Matlab para Scilab 2078 AboutM2SCItools 2079 Contents 2081 Cste 2082 Equal 2083 Funcall 2084 Infer 2085 MatlabScilabcharacterstrings 2086 Operation 2087 Type 2088 Variable 2089 getcontentsinfer 2090 m2scideclare 2091 matfile2sci 2093 mfile2sci 2094 scifiles 2097 translatepaths 2099 XL Interfaces com TclTk 2100 ScilabEval 2101 TCLCreateSlave 2103 TCLDeleteInterp 2104 TCLEvalFile 2105 TCLEvalStr 2107 TCLExistArray 2109 TCLExistInterp 2110 TCLExistVar 2111 TCLGetVar 2112 TCLGetVersion 2114 TCLSetVar 2115 TCLUnsetVar 2117 TCLUpVar 2118 browsevar 2119 config 2120 editvar 2121 tkgetdir 2122 tksavefile 2123 winclose 2124 winlist 2125 XLI Texmacs 2126 pol2tex 2127 texprint 2128 XLII Manipulação de Arquivos de Som 2129 analyze 2130 auread 2131 auwrite 2132 beep 2133 lin2mu 2134 Manual Scilab xxix loadwave 2135 mapsound 2136 mu2lin 2137 playsnd 2138 savewave 2139 sound 2140 soundsec 2141 wavread 2142 wavwrite 2143 XLIII Randlib 2144 grand 2145 XLIV Ferramentas de Desenvolvimento 2151 benchrun 2152 tbxbuildcleaner 2154 tbxbuildgateway 2155 tbxbuildgatewayclean 2156 tbxbuildgatewayloader 2157 tbxbuildhelp 2158 tbxbuildhelploader 2159 tbxbuildloader 2160 tbxbuildmacros 2161 tbxbuildsrc 2162 tbxbuildergateway 2164 tbxbuildergatewaylang 2165 tbxbuilderhelp 2166 tbxbuilderhelplang 2167 tbxbuildermacros 2168 tbxbuildersrc 2169 tbxbuildersrclang 2170 testrun 2171 XLV Ferramentas de Demonstração 2175 demobegin 2176 demochoose 2177 democompiler 2178 demoend 2179 demofilechoice 2180 demofunctionchoice 2181 demomdialog 2182 demomessage 2183 demorun 2184 XLVI Planilhas 2185 readxls 2186 xlsopen 2187 xlsread 2189 excel2sci 2191 readcsv 2192 writecsv 2193 XLVII callscilab API 2194 Boolean management 2195 Complex management 2197 DisableInteractiveMode 2199 Double management 2200 GetLastJob 2202 ScilabHaveAGraph 2203 SendScilabJob 2204 SendScilabJobs 2205 StartScilab 2206 String management 2207 Manual Scilab xxx TerminateScilab 2209 callscilab 2210 Compile and run with Call Scilab 2212 creadbmat obsolete 2215 creadchain obsolete 2217 creadcmat obsolete 2219 creadmat obsolete 2221 cwritebmat obsolete 2223 cwritechain obsolete 2225 cwritecmat obsolete 2227 cwritemat obsolete 2229 fromc 2231 fromjava 2232 XLVIII FFTW 2233 fftw 2234 fftwflags 2236 fftwforgetwisdom 2238 getfftwwisdom 2239 setfftwwisdom 2240 XLIX Interfaces com UMFPACK 2241 PlotSparse 2242 ReadHBSparse 2243 cond2sp 2245 condestsp 2247 rafiter 2249 reswithprec 2251 taucschdel 2252 taucschfact 2253 taucschget 2255 taucschinfo 2257 taucschsolve 2258 taucslicense 2259 umflicense 2260 umfludel 2261 umflufact 2262 umfluget 2264 umfluinfo 2266 umflusolve 2268 umfpack 2269 L Algoritmos Genéticos 2271 codinggabinary 2272 codinggaidentity 2273 crossovergabinary 2274 crossovergadefault 2275 initgadefault 2277 mutationgabinary 2278 mutationgadefault 2279 optimga 2280 optimmoga 2282 optimnsga 2284 optimnsga2 2286 paretofilter 2288 selectiongaelitist 2289 selectiongarandom 2291 LI Arrefecimento Simulado 2293 computeinitialtemp 2294 neighfunccsa 2295 neighfuncdefault 2296 Manual Scilab xxxi neighfuncfsa 2297 neighfuncvfsa 2298 optimsa 2299 templawcsa 2301 templawdefault 2303 templawfsa 2304 templawhuang 2306 templawvfsa 2308 LII Parâmetros 2310 addparam 2311 getparam 2312 initparam 2313 isparam 2314 listparam 2315 removeparam 2316 setparam 2317 LIII Atoms 2318 Getting started 2319 Functions Summary 2321 atomsAutoloadAdd 2322 atomsAutoloadDel 2324 atomsAutoloadList 2326 atomsDepTreeShow 2327 atomsGetInstalled 2328 atomsGetLoaded 2330 atomsInstall 2331 atomsIsInstalled 2334 atomsIsLoaded 2336 atomsList 2338 atomsLoad 2339 atomsRemove 2340 atomsRepositoryAdd 2342 atomsRepositoryDel 2343 atomsRepositoryList 2344 atomsSearch 2345 atomsSetConfig 2346 atomsShow 2348 atomsSystemUpdate 2349 atomsUpdate 2350 LIV EntradaSaída de Arquivos Matlab Binários 2352 loadmatfile 2353 matfileclose 2354 matfilelistvar 2355 matfileopen 2356 matfilevarreadnext 2357 matfilevarwrite 2358 savematfile 2359 LV xcos 2361 6 Batch functions 2363 lincos 2364 scicos 2365 scicossimulate 2366 scicosim 2368 steadycos 2370 7 palettes 2372 1 Annotations palette 2372 2 Commonly used blocks palette 2375 3 Continuous time systems palette 2383 Manual Scilab xxxii 4 Demonstrations blocks palette 2408 5 Discontinuities palette 2425 6 Discrete time systems palette 2438 7 Electrical palette 2455 8 Event handling palette 2513 9 Implicit palette 2559 10 Integer palette 2564 11 Lookup tables palette 2595 12 Math operations palette 2602 13 Matrix operation palette 2649 14 Port Subsystem palette 2712 15 Signal processing palette 2719 16 Signal routing palette 2724 17 Sinks palette 2760 18 Sources palette 2815 19 Thermohydraulics palette 2868 20 User defined functions palette 2882 21 Zero crossing detection palette 2908 8 Programming xcos Blocks 2918 1 C Computational Functions 2918 2 Scilab Computational Functions 2932 3 Utilities Functions 2936 9 Scilab Data Structures 2947 1 Blocks 2947 2 CompilationSimulation 2958 3 Diagram 2966 4 Links 2971 10 Scilab Utilities Functions 2974 buildouttb 2975 createpalette 2976 getscicosversion 2977 scicosdebug 2978 var2vec 2979 vec2var 2980 xcos 2982 Menuentries 2983 LVI scilab editor 2993 editerror 2994 Editor 2995 LVII API Scilab 2999 11 Scilab Gateway API 3001 1 How to 3001 CheckColumn 3023 CheckDimProp 3024 CheckDims 3025 CheckLength 3026 CheckLhs 3027 CheckRhs 3028 CheckRow 3029 CheckSameDims 3030 CheckScalar 3032 CheckSquare 3033 CheckVector 3034 CreateListVarFrom 3035 CreateListVarFromPtr 3038 CreateVar 3041 FindOpt 3043 FirstOpt 3045 Manual Scilab xxxiii GetListRhsVar 3047 GetRhsVar 3049 GetType 3051 IsOpt 3052 Lhs 3054 LhsVar 3055 NumOpt 3057 OverLoad 3059 Rhs 3061 Scierror 3062 Scilab C Types 3063 getoptionals 3065 istk 3067 scitypes 3068 sciprint 3071 stk 3072 12 listmanagement 3073 Boolean reading Scilab gateway 3074 Boolean writing Scilab gateway 3086 Boolean sparse reading Scilab gateway 3090 Boolean sparse writing Scilab gateway 3102 Create List Scilab gateway 3106 Double reading Scilab gateway 3110 Double writing Scilab gateway 3122 Get child item Scilab gateway 3126 Item Number Scilab gateway 3129 Integer reading Scilab gateway 3132 Integer writing Scilab gateway 3144 Pointer reading Scilab gateway 3149 Pointer writing Scilab gateway 3161 Polynomial reading Scilab gateway 3165 Polynomial writing Scilab gateway 3177 Sparse reading Scilab gateway 3181 Sparse writing Scilab gateway 3193 String reading Scilab gateway 3197 String writing Scilab gateway 3209 apiscilab 3213 Boolean reading Scilab gateway 3214 Boolean writing Scilab gateway 3216 Boolean sparse reading Scilab gateway 3219 Boolean sparse writing Scilab gateway 3222 Variable Reference Scilab gateway 3225 Variable dimension Scilab gateway 3229 Variable Type Scilab gateway 3233 Variable Complexity Scilab gateway 3237 Matrix Type Scilab gateway 3241 Double reading Scilab gateway 3245 Double writing Scilab gateway 3248 Integer Precision Scilab gateway 3252 Integer reading Scilab gateway 3256 Integer writing Scilab gateway 3263 Pointer reading Scilab gateway 3270 Pointer writing Scilab gateway 3272 Polynomial Symbolic Variable Scilab gateway 3275 Polynomial reading Scilab gateway 3279 Polynomial writing Scilab gateway 3284 Sparse matrix reading Scilab gateway 3286 Sparse writing Scilab gateway 3289 Manual Scilab xxxiv String reading Scilab gateway 3292 String writing Scilab gateway 3295 LVIII Gerenciamento de ajuda online 3297 addhelpchapter 3298 apropos 3299 foo 3300 help 3301 helpfromsci 3302 helpskeleton 3304 makeindex 3305 man 3306 manedit 3310 helps 3311 xmltohtml 3312 xmltojar 3314 xmltopdf 3316 xmltops 3318 delhelpchapter 3320 xmltochm 3321 Parte I Scilab 2 Name abort Interrupção de avaliação Descrição abort interrompe a avaliação corrente e retrona ao prompt de comando Dentro de um nível de pause abort retorna ao prompt de nível 0 Ver Também quit pause break 3 Name adddemo adiciona uma entrada na lista de demonstrações adddemotitlepath Parâmetros title string o título da demonstração path string o endereço do script scilab associado à demonstração Descrição Esta função adiciona uma nova entrada na lista de demonstrações A demonstração deve ser executada por um arquivo script do Scilab Se o dado título já existir title na lista de demonstrações associada ao mesmo arquivo nada é feito Esta função checa se o arquivo existe Exemplos criando um simples script de demonstração pathTMPDIRfoosce mputldisp Hellopath adddemoMy first demopath a demonstração pode agora ser executada através do menu Demos Ver também addhelpchapter Autor Serge Steer INRIA 4 Name ans resposta Descrição ans significa resposta A variável ans é criada automaticamente quando expressões não são atribuídas ans contém a última expressão nãoatribuída 5 Name argn número de argumentos na chamada de uma função lhs rhs argn lhsargn1 rhsargn2 Descrição Esta função é usada dentro da definição de uma função Ela fornece os números de parâmetros de entrada rhs e saída lhs passados à função quando esta é chamada Geralmente é usada em definições de funções para lidar com parâmetros opcionais Ver Também function varargin 6 Name backslash divisão matricial direitaesquerda xAb Descrição denota a divisão matricial direitaesquerda xAb é a solução para Axb Se A é quadrada e nãosingular xAb unicamente definida é equivalente a xinvAb mas as computações são menos custosas Se A não é quadrada x é uma solução de mínimo quadrado ie normAxb é mínima norma euclidiana Se A é de posto coluna cheio a solução de mínimo quadrado xAb é unicamente definida há um único x que minimiza normAxb Se Anão é de posto coluna cheio então a solução de mínimo quadrado não é única e xAb em geral não é a solução com norma mínima a solução com norma mínima é xpinvAb AB é a matriz com entrada ij igual a AijBij Se A ou Bé um escalar AB é equivalente a AonesBB ou ABonesA AB é um operador sem significado predefinido Pode ser usado para definir um novo operador ver overloading com a mesma precedência que ou Exemplos Arand32b111 xAb ypinvAb xy Arand23b11 xAb ypinvAb xy Axb Ayb Arand31rand12 b111 xAb ypinvAb Axb Ayb Arand21rand13 b11 xAb ypinvAb Axb Ayb A benchmark of several linear solvers Adescrrefmtype ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa b 0onessizeA11 tic res umfpackAb printf time needed to solve the system with umfpack 3f toc tic res linsolveAb printf time needed to solve the system with linsolve 3f toc tic res Ab printf time needed to solve the system with the backslash operator 3f toc Ver Também slash inv pinv percent ieee linsolve umfpack 7 Name banner exibe banner do Scilab Windows banner Descrição Exibe banner do Scilab Exemplos clcbanner Autor Allan CORNET 8 Name boolean objetos Scilab variáveis booleanas e operadores e Descrição Uma variável booleana é T para true verdadeiro ou F for false para falsefalso Es tas variáveis podem ser usadas para definir matrizes de valores booleanos com a sintaxe usual Ma trizes de valores booleanos podem ser manipuladas como matrizes ordinárias para extraçãoinserção de elementos e concatenação Note que outras operações usuais etc não são definidas para matrizes de valores booleanos Três operadores especiais são definidos para estas matrizes b é a negação elemento a elemento de b matriz b1b2 é o and e lógico elemento a elemento de b1 e b2 matrizes b1b2 é o or ou lógico elemento a elemento de b1 e b2 matrizes Variáveis booleanas podem ser usadas para se indexar vetores ou matrizes Por exemplo aTFT retorna a submatriz feita das linhas 1 e 3 de a Matrizes esparsas de valores booleanos são suportadas Exemplos 1213 121 a15 aagt2 Ver Também matrices or and not 9 Name brackets colchetes esquerdo e direito a11a12a21a22 s1s2func Parâmetros a11a12 qualquer matriz de reais polinômios razões de polinômios lista syslin com dimensões apropriadas s1s2 qualquer nome de variável possível Descrição Colchetes esquerdo e direito são usados para notar concatenação de vetores e matrizes Estes símbolos também são usados para denotar lado esquerdo múltiplo para a chamada de uma função Dentro de colchetes de concatenação espaços vazios ou vírgulas significam concatenação de colu nas e pontosevírgulas ou retronos de carro significa concatenação de linhas Nota para evitar confusões é melhor utilizar vírgulas ao invés de espaços vazios para separar colunas Dentro de lados esquerdos múltiplos os nomes das variáveis de vem ser separados por vírgulas Exemplos 69964 sqrt1 0 1 i 2 i 3 this isa stringvector spoly0s1s2s tf2ss1stf2ss2s usschurrand33 Ver Também comma semicolon 10 Name break palavrachave para interromper um laço loop significa interromper neste ponto Descrição Dentro de um laço for ou while loop o comando break força o fim do laço Exemplos k0 while 11 kk1 if k gt 100 then breakend end Ver Também while if for abort return 11 Name case palavrachave usada na estrutura select significa caso Descrição Palavra chave usada na estrutura select case Usea do seguinte modo select expressão0 case expressão1 then instruções1 case expressão2 then instruções2 case expressãon then instruçõesn else instruções end Ver Também select while end for 12 Name clear cancela variáveis clear a Descrição Este comando cancela variáveis que não estão protegidas Ele remove as variáveis nomeadas do am biente Por si só clear cancela todas as variáveis exceto as protegidas por predef Logo os dois comandos predef0 e clear removem todas as variáveis Normalmente variáveis protegidas são bibliotecas padrões e variáveis com o prefixo Note a sintaxe particular clear a e não cleara Note também que a não cancela a mas define a como uma matriz vazia Ver Também predef who 13 Name clearfun remove função primitiva retclearfunname Descrição clearfunname remove a primitiva name do conjunto de primitivas funções builtin clearfun retorna t ou f Esta função permite renomear uma primitiva uma primitiva Scilab pode ser substituída por uma função definida pelo usuário Para usuários experientes Ver Também newfun funptr 14 Name clearglobal cancela variáveis globais clearglobal clearglobal nam1 namn clearglobalnam1 namn Parâmetros nam1 namn nomes de variáveis válidos Descrição clearglobal cancela todas as variáveis globais clearglobal nam1 namn cancela as variáveis globais dadas por seus nomes Note que clearglobal limpa apenas as variáveis globais as cópias locais destas variáveis não são destruídas Exemplos global a b c a1b2c3 whoglobal clearglobal b whoglobal Ver Também global who 15 Name colon operador dois pontos Descrição Colon symbol can be used to form implicit vectors see also linspace logspace jk é o vetor j j1k vazio se jk jdk é o vetor j jd jmd A notação de dois pontos também pode ser usada para retirar linhas colunas e elementos selecionados de vetores e matrizes ver também extractioninsertion A é o vetor de todos os elementos de A considerados como uma única coluna Aj é a jésima coluna de A Ajk é AjAj1Ak Ajk é AjAj1Ak Aw preenche a matriz A com entradas de w tomados coluna a coluna se w é uma matriz Ver Também matrix for linspace logspace 16 Name comma separador de colunas instruções e argumentos Descrição Vírgulas são usadas para separar parâmetros em funções ou para separar entradas em vetores linhas Espaços vazios podem ser usados para separar entradas em um vetor linha mas é preferível que se use vírgulas Também é usada para separar instruções do Scilab Use para que o resultado não seja exibido na tela Exemplos a123456 a1b1c2 Ver Também semicolon brackets 17 Name comments comentários Descrição Uma seqüência de duas barras fora de uma definição de string marca o início de um comentário As barras tanto quanto o restante dos caracteres até o fim das linhas não são interpretados Dentro de uma função as primeiras linhas de comentário até a primeira instrução ou linha vazia podem ser usadas para fornecer o conteúdo padrão para a documentação de ajuda da função help da função Exemplos g981 a gravidade textab function ymyfunctionx myfunction computa yx21 x deve ser um vetor ou uma matriz yx21 endfunction help myfunction 18 Name comp compilação de função Scilab compfunction opt Parâmetros function uma função scilab nãocompilada tipo 11 opt flag com valor 0 padrão 1 ou 2 Descrição compfunction compila a função function Funções compiladas e interpretadas são equiva lentes mas geralmente as compiladas são mais rápidas As funções fornecidas nas bibliotecas padrões são compiladas A definição online bem como a sintaxe curta dos comandos exec e deff geram funções compiladas Então comp tem que ser usado apenas em casos bem particulares Para se produzir uma função não compilada devese usar exec ou deff com a opção n O valor opt2 faz com que a função seja compilada para definição de perfil Note que ago ra é possível adicionar a instrução de definição de perfil após a compilação utilizando a função addprofiling A opção obsoleta opt1 era específica para propósitos de análise de códigos e agora é ignorada ie tratada como opt0 Note na compilação a função original é modificada e nenhum objeto novo é criado Ver Também type deff exec function addprofiling profile 19 Name comparison comparação operadores relacionais ab ab ou ab ab ab ab ab Parâmetros a qualquer tipo de variável para comparações de igualdade ab ab ab e restrita a arrays de pontos flutuantes reais e inteiros para comparações relacionadas à ordem ab ab abab b qualquer tipo de variável para comparações de igualdade ab ab a b e restrita a arrays de ponto flutuantes reais e inteiros para comparações relacionadas à ordem ab ab abab Descrição Duas classes de operadores devem ser distinguidas Comparações de igualdade e desigualdade ab ab ou de modo equivalente ab Estes operadores se aplicam a quaisquer tipos de operandos Comparações de ordem ab ab abab Estes operadores se aplicam apenas a arrays de pontos flutuantes reais e inteiros A semântica dos operadores de comparação também depende dos tipos de operandos Com variáveis arrays como arrays de pontos flutuantes ou inteiros arrays lógicos arrays de strings arrays de polinômios ou razões de polinômios arrays de manipuladores listas o seguinte se aplica Se a e b são avaliados como arrays do mesmo tipo e dimensões idênticas a comparação é realizada elemento a elemento e o resultado é um array de booleanos da comparação Se a e b são avaliados como arrays do mesmo tipo mas a ou b é um array 1 por 1 o elemento é comparado com cada elemento do outro array O resultado é um array de booleanos com o tamanho do operando nãoescalar Em outros casos o resultado é o booleano f Se os tipos de dados dos operandos são diferentes mas compatíveis como pontos flutuantes e inteiros uma conversão de tipo é realizada antes da comparação Com outros tipos de operandos como function libraries o resultado é t se os objetos são idênticos e f em outros casos Comparação de igualdade entre operandos com tipos de dados incompatíveis retorna f comparison 20 Exemplos comparações elemento a elemento 153 154 151 4 2 3 0 1 list123list133 comparações objeto a objeto 11043 foo3 1 list1231 isequallist1231 isequal1101 comparação com conversão de tipo int3211 int32115 int3215int83 ppoly0sc p0 ppoly1sc0 Ver Também less boolean isequal 21 Name continue Palavrachave para passar o controle para a próxima iteração de um laço loop significa continuar Descrição Dentro de um laço for ou while o comando continue passa o contole para a próxima iteração do laço no qual aparece pulando quaisquer sentenças restantes entre esta instrução e a instrução end do laço Exemplos for k110Kkif kgt2ampklt8 then continuedisphelloendkend for j12 x for k110if kgtj1ampklt8 then continueendxxkend x end Ver Também while for break return Autor Serge Steer INRIA 22 Name debug nivel de depuração debugging debugging level debuglevelint levelintdebug Parâmetros levelint inteiro de 0 a 4 Descrição Para os valores 0 1 2 3 ou 4 de levelint define vários níveis de depuração Isto é voltado para o analisador sintático não para scripts Scilab Para usuários mais experientes do Scilab 23 Name delbpt deleta pontos de parada breakpoints delbptmacroname linenumb Parâmetros macroname string linenumb escalar inteiro ou vetor de inteiros Descrição Deleta o ponto de parada na linha linenumb na função macroname linenumb pode ser um vetor linha ou coluna de inteiros ou um único escalar Se linenumb for omitido todos os pontos de parada da função macroname são deletados Se ambos macroname e linenumb são omitidos todos os pontos de parada em todas as funções são deletados Exemplos setbptfoo1setbptfoo10delbptfoo10dispbpt delbptfoo1dispbpt setbptfoo14setbptfoo19setbptfoo26setbptfoo38dispbpt delbptfoo2dispbpt delbptdispbpt delbptfoo1256dispbpt Ver Também setbpt dispbpt pause resume 24 Name dispbpt exibe breakpoints pontos de parada dispbpt Descrição dispbpt exibe todos os breakpoints ativos inseridos nas funções Ver Também setbpt delbpt pause resume 25 Name do palavrachave de linguagem para laços loops significa faça Descrição Pode ser usado dentro de instruções for ou while para separar a definição de variável do laço e o conjunto de instruções do mesmo Ver Também for while 26 Name dot símbolo de ponto 12333 ab 123 456 Descrição É usado para marcar pontos vírgulas decimais em números 325 e 0001 op usado em conjunto com outros símbolos de operadores forma outros operadores Operações multiplicativas elemento a elemento são obtidas utilizandose ou Por exemplo C A B é a matriz com elementos cij aijbij O produto de Kronecker é notado por Note que quando o ponto segue um número é sempre parte deste 2x é avaliado como 20x e 2 x há um espaço entre 2 e é avaliado como 2x Marca de continuação Dois ou mais pontos ao fim de uma linha ou seguidos por um comentário indicam que a próxima linha será uma continuação Linhas de continuação são manipuladas por um processador que constrói uma linha lógica longa de uma dada seqüência de linhas de continuação Então marcas de continuação podem ser usadas para cortar uma linha em qualquer ponto Exemplos ponto decimal 1345 usado como parte de um operador x1 2 3x2 x um espaço é requerido entre 2 e o ponto usado como marcas de continuação T123primeiro elemento 456 segundo elemento a aqui eu começo um grande string mas não quero continuar aqui e aqui eu continuo y12 45 Ver Também star hat slash backslash 27 Name edit edição de funções editfunctionname Parameters functionname string Descrição Se functionname for o nome de uma função Scilab definida editfunctionname tente abrir o arquivo associado functionnamesci Se functionname for o nome de uma função Scilab indefinida edit cria o arquivo functionnamesci no diretório TMPDIR Exemplos editedit abre o editor com o texto dessa função editmyfunction abre o editor para uma nova função Ver Também manedit 28 Name else palavrachave usada na estrutura ifthenelse significa senão Descrição Usado com if Ver Também if 29 Name elseif palavrachave usada na estrutura ifthenelse significa senão se Descrição Ver ifthenelse 30 Name empty matriz vazia Descrição denota a matriz vazia É definida de modo único e possui 0 linha e 0 coluna ie size 00 As seguintes convenções convenientes foram feitas A A A A A A A A inv detcondrcond1 rank0 Funções de matrizes retornam ou produzem uma mensagem de erro quando não há resposta óbvia Sistemas lineares vazios listas syslin podem ter várias linhas ou colunas Exemplos spoly0s A s s1 A A Arand22 AAA1 sizeAA svd wssrand222 wrw sizewr w1ss2tfwr sizew1 Ver Também matrices poly string boolean rational syslin 31 Name end Palavrachave end significa fim Descrição Usado no fim de estruturas de laço ou condicionais for while if select devem ser terminados por end Ver Também for while if select 32 Name equal atribuição ou comparação sinal de igualdade Descrição Atribuição o sinal de igualdade é usado para denotar a atribuição de valores a variáveleis A sintaxe pode ser aexpr onde a é um nome de variável e expr uma expressão do Scilab cuja avaliação conduz a um único resultado abexpr onde ab são nomes de variáveis e expr uma expressão do Scilab cuja avaliação conduz a tantos resultados quanto o número de variáveis dadas Comparação o sinal de igualdade também é usado em operadores de comparação ab denota comparação de igualdade entre os valores das expressões a e b ab denota comparação de desigualdade entre os valores das expressões a e b ab e ab denotam comparações de ordem entre os valores de a e b Ver comparison para detalhes semânticos Exemplos a sin32 M 21338576676906388 us schurM 110 4 12 Ver Também less great boolean isequal comparison 33 Name errcatch Armadilha para erros errcatchn action option errcatch Parâmetros n inteiro action option strings Descrição errcatch fornece uma ação manipulador de erros quando um erro do tipo n ocorre n tem o seguinte significado Se n0 n é o número do erro a ser apanhado Se n0 todos os erros devem ser apanhados action é um dos seguintes strings pause uma pausa é executada quando se apanha o erro Esta opção é útil para propósitos de depuramento Use whereami para obter informações sobre o contexto corrente continue a próxima instrução na função ou em arquivos executáveis é executada a instrução corrente é ignorada É possível verificar se um erro ocorreu utilizando a função iserror function Não se esqueça de apagar o erro utilizando a função errclear o quanto antes Esta função é útil para recuperação de erros Em muitos casos o uso de errcatchncontinue pode ser substituído pelo uso da função execstr ou da estrutura de controle try control structure kill modo padrão todas as funções intermediárias são canceladas e o Scilab retorna ao prompt de nível 0 stop interrompe a sessão do Scilab corrente útil quando o Scilab é chamado por um programa externo option é o string nomessage para cancelar mensagens de erro Para retornar ao modo padrão entre errcatch1kill ou de modo semelhante errcatch1errcatch é um equivalente obsoleto a errcatch1 As ações de errcatch se aplicm ao contexto corrente de avaliação function exec pause e a todos os subníveis Uma segunda chamada a errcatch em um subnível esconde a inicial para este sub nível Se uma segunda chamada a errcatch é feita no mesmo nível o efeito da primeira é removido Quando chamado no contexto de uma função do Scilab ou em exec o errcatch é automaticamente reiniciado quando a função retorna Ver Também try errclear iserror whereami execstr 34 Name errclear limpeza de erros errclearn Descrição Limpa a ação manipulador de erros conectada ao erro de tipo n Se n é positivo é o número do erro limpo caso contrário todos os erros são limpos caso padrão Ver Também errcatch iserror lasterror 35 Name error mensagens de erro errormessage n errorn errornpos Parâmetros message um string A mensagem de erro a ser exibida n um inteiro O número associado à mensagem de erro pos um inteiro Um parâmetro para a mensagem de erro Descrição error permite escrever uma mensagem de erro e manipular o erro Por padrão error interrompe a execução corrente e retorna ao nível de prompt Este padrão pode ser modificado utilizandose as funções errcatch ou execstrerrcatch errormessage imprime o string contido em message O número associado à mensagem de erro é 10000 errormessagen imprime o string contido em message O número associado à mensagem de erro é dado por n Este número deve ser maior que 10000 errorn imprime a mensagem de erro predefinda associada ao número de erro n Algumas mensagens de erro predefinidas requerem um parâmetro ver errortable Neste caso o argumento pos deve ser usado errornpos para fornecer o valor do parâmetro Em outros casos o parâmetro é ignorado Ver errortable para uma lista das mensagens de erro e seus números associados Exemplos errormy error message error43 error523 Ver Também warning errcatch execstr lasterror 36 Name errortable tabela de mensagens de erros Description Esta página fornece a tabela e mensagens de erros predefinidas e seus números associados Algumas dessas mensagens de erro são utilizadas pelo próprio Scilab para erros de parser ou erros de builtins específicos Algumas outras são de uso mais geral e podem ser utilizadas por funções do Scilab As com asteríscos são aquelas para as quais a sintaxe errornpos é manipulada 1 Incorrect assignment atribuição incorreta 2 Invalid factor fator inválido 3 Waiting for right parenthesis esperava parêntese direito 4 Undefined variable s variável indefinida s 5 Inconsistent columnrow dimensions dimensões de colunalinha inconsistentes 6 Inconsistent rowcolumn dimensions dimensões de linhacoluna inconsistentes 7 Dot cannot be used as modifier for this operator ponto não pode ser usado como modificador para ste operador 8 Inconsistent addition adição inconsistente 9 Inconsistent subtraction subtração inconsistente 10 Inconsistent multiplication multiplicação inconsistente 11 Inconsistent right division divisão esquerdadireita inconsistente 12 Inconsistent left division divisão direitaesquerda inconsistente 13 Redefining permanent variable redefinição de variável permanente 14 Eye variable undefined in this context variável eye identidade indefinida neste contexto 15 Submatrix incorrectly defined submatriz definida incorretamente 16 Incorrect command comando incorreto 17 Stack size exceeded Use stacksize function to increase it tamanho de pilha excedido Use a função stacksize para aumentálo 18 Too many variables muitas variáveis 19 Problem is singular o problema é singular 20 Wrong type for argument d Square matrix expected tipo errado para o argumento d esperava matriz quadrada 21 Invalid index índice inválido 22 Recursion problems Sorry problemas de recursão Perdão 23 Matrix norms available are 1 2 inf and fro normas de matriz disponíveis são 12inf e fro 24 Convergence problem problema de convergência 25 Bad call to primitive s chamada ruim à primitiva s errortable 37 26 Too complex recursion recursion tables are full recursão muito complexa as tabelas de recursão estão cheias 27 Division by zero divisão por zero 28 Empty function função vazia 29 Matrix is not positive definite a matriz não é positiva definida 30 Invalid exponent expoente inválido 31 Incorrect string string incorreto 32 Singularity of log or tan function singularidade da função log ou tan 33 Too many muitos 34 Incorrect control intruction syntax sintaxe incorreta de instrução de controle 35 Syntax error in an ifa while or a select instruction erro de sintaxe em uma instrução if while ou select 36 Wrong input argument d argumento de entradad incorreto 37 Incorrect function at line d função incorreta na linha d 38 Wrong file name nome de arquivo incorreto 39 Incorrect number of arguments número incorreto de argumentos 40 Waiting for end of command esperava fim do comando 41 Incompatible output argument argumento de saída incompatível 42 Incompatible input argument argumento de entrada incompatível 43 Not implemented in scilab não implementado no Scilab 44 Wrong argument d argumento d incorreto 45 Null matrix argument d matriz nula argumento número d 46 Incorrect syntax sintaxe incorreta 47 End or else is missing faltando end ou else 48 Input line longer than buffer size d linha de entrada maior que tamanho de buffer d 49 Incorrect file or format arquivo ou formato incorreto 50 Subroutine not found s subrotina não encontrada s 52 Wrong type for argument d Real matrix expected tipo errado para o argumento d esper ava matriz de reais 53 Wrong type for input argument d Real or complex matrix expected tipo errado para o argumento d esperava matriz de reais ou de complexos 54 Wrong type for input argument d Polynomial expected tipo errado para o argumento d esperava polinômio 55 Wrong type for argument d String expected tipo errado para o argumento d esperava string errortable 38 56 Wrong type for argument d List expected tipo errado para o argumento d esperava lista 57 Problem with comparison symbol problema com símbolo de comparação 58 Function has no input argument a função não tem argumento de entrada 59 Function has no output a função não tem saída 60 Wrong size for argument Incompatible dimensions tamanho errado para o argumento dimensões incompatíveis 61 Direct access file give format arquivo de acesso direto fornecer formato 62 End of file at line d fim do arquivo na linha d 63 d graphic terminal d terminais gráficos 64 Integration fails falha de integração 65 d logical unit already used d unidade lógica já utilizada 66 No more logical units available não há mais unidades lógicas disponíveis 67 Unknown file format formato de arquivo desconhecido 68 Fatal error Your variables have been saved in the file s 69 Floating point exception exceção de ponto flutuante 70 Too many arguments in fort max 30 muitos argumentos em fort máximo de 30 71 This variable is not valid in fort esta variável não é válida em fort 72 s is not valid in this context s não é válido neste contexto 73 Error while linking erro no linking 74 Leading coefficient is zero coeficiente regente é 0 75 Too high degree max 100 grau muito alto no máximo 100 76 For xval with typevald is not implemented in Scilab para xval com typevald não há implementação no Scilab 77 s wrong number of rhs arguments s número incorreto de argumentos do lado direito 78 s wrong number of lhs arguments s número incorreto de argumentos do lado esquerdo 79 Indexing not allowed for output arguments of resume indexação não permitida para argumentos de saída de resume 80 Incorrect function argument ns função incorreta argumento n s 81 s Wrong type for argument d Real or complex matrix expected s tipo errado para o argumento d esperava matriz de reais ou de complexos 82 s Wrong type for argument d Real matrix expected s tipo errado para o argumento d esperava matriz de reais 83 s Wrong type for argument d Real vector expected s tipo errado para o argumento d esperava vetor de reais 84 s Wrong type for argument d Scalar expected s tipo errado para o argumento d esperava escalar errortable 39 85 Host does not answer host não responde 86 Uncontrollable system sistema incontrolável 87 Unobservable system sistema inobservável 88 sfact singular or asymmetric problem sfact problema singular ou assimétrico 89 Wrong size for argument d tamanho errado para o argumento d 90 Wrong type for argument d Transfer matrix expected tipo errado para o argumento d esperava matriz de transferência 91 Wrong type for argument d In state space form expected tipo errado para o argumento d esperava em forma de espaço de estados 92 Wrong type for argument d Rational matrix expected tipo errado para o argumento d esperava matriz de razões de polinômios 93 Wrong type for argument d In continuous time expected tipo errado para o argumento d esperava em tempo contínuo 94 Wrong type for argument d In discrete time expected tipo errado para o argumento d esperava em tempo discreto 95 Wrong type for argument d SISO expected tipo errado para o argumento d esperava SISO 96 Time domain of dth argument is not defined domínio de tempo do désimo argumento não está definido 97 Wrong type for argument d A system in state space or transfer matrix form expected tipo er rado para o argumento d esperava um sistema em espaço de estados ou uma matriz de transferência 98 Variable returned by scilab argument function is incorrect variável retornada pela função argu mento do Scilab está incorreta 99 Elements of dth argument must be in increasing order elementos do désimo argumento devem estar em ordem crescente 100 The elements of dth argument are not in strictly decreasing order os elementos do d ésimo argumento não estão em ordem estritamente crescente 101 Last element of dth argument first o último elemento do désimo argumento não é igual ao primeiro 102 Variable or function s is not in file s variável ou função s não está no arquivo s 103 Variable s is not a valid rational function variável s não é uma função racional válida 104 Variable s is not a valid state space representation variável s não é uma representação de espaço de estados válida 105 Undefined fonction função indefinida 106 Function name already used nome de função já utilizado 107 Too many functions are defined maximum d muitas fuñções estão definidas número máximo d 108 Too complex for scilab may be a too long control instruction muito complexo para o Scilab pode ser uma instrução de controle muito longa 109 Too large cant be displayed muito grande não pode ser exibido errortable 40 110 s was a function when compiled but is now a primitive s era uma função quando compilada mas agora é uma primitiva 111 Trying to redefine function s tentando redefinir a função s 112 Cannot allocate more memory não pode alocar mais memória 113 Too large string string muito grande 114 Too many linked entry points muitos pontos de entradas linkados 115 Stack problem detected within a loop problema de empilhamento detectado dentro de um laço 116 Wrong value for argument d valor errado para o argumento d 117 List element number d is Undefined elemento número d da lista é indefinido 118 Wrong type for argument d Named variable not an expression expected tipo errado para o argumento d esperava variável nomeada não uma expressão 119 Indices for nonzero elements must be given by a 2 column matrix índices para elementos não nulos devem ser fornecidos por uma matriz de duas colunas 121 Incompatible indices for nonzero elements índices incompatíveis para elementos nãonulas 122 Logical unit number should be larger than d número de unidade lógica deve ser maior que d 123 Function not bounded from below função não limitada por baixo 124 Problem may be unbounded too high distance between two consecutive iterations o problema pode ser ilimitado distância muito alta entre duas iterações consecutivas 126 Inconsistent constraints restrições inconsistentes 127 No feasible solution não há solução viável 128 Degenerate starting point ponto de partida degenerado 129 No feasible point has been found nenhum ponto viável foi encontrado 130 Optimization fails back to initial point a otimização falhou de volta ao ponto inicial 131 optim stop requested by simulator ind 0 optim parada requerida pelo simulador ind0 132 optim incorrect input parameters optim parâmetros de entrada incorretos 133 Too small memory memória muito pequena 134 optim problem with initial constants in simul optim problema com constantes iniciais em simul 135 optim bounds and initial guess are incompatible optim limites e palpite inicial são incompatíveis 136 optim this method is NOT implemented optim este método NÃO é implementado 137 NO hot restart available in this method NÃO há recomeço rápido disponível neste método 138 optim incorrect stopping parameters optim parâmetros de parada incorretos 139 optim incorrect bounds optim limites incorretos 140 Variable s must be a list variável s deve ser uma lista errortable 41 141 Incorrect function argument nd função incorreta argumento n d 142 Hot restart dimension of working table argument nd recomeço rápido dimensão da mesa de trabalho argumento nd 143 optim df0 must be positive optim df0 deve ser positivo 144 Undefined operation for the given operands operação indefinida para os dados operandos 201 s Wrong type for argument d Real or complex matrix expected s tipo errado para o argumento d esperava matriz de reais ou complexos 202 s Wrong type for argument d Real matrix expected s tipo errado para o argumento d esperava matriz de reais 203 s Wrong type for argument d Real vector expected s tipo errado para o argumento d esperava vetor de reais 204 s Wrong type for argument d Scalar expected s tipo errado para o argumento d esperava escalar 205 s Wrong size for argument d dd expected s tamanho errado para o argumento d esperava dd 206 s Wrong size for argument d d expected s tamanho errado para o argumento d esperava d 207 s Wrong type for argument d Matrix of strings expected s tipo errado para o argumento d esperava matriz de strings 208 s Wrong type for argument d Boolean matrix expected s tipo errado para o argumento d esperava matriz de booleanos 209 s Wrong type for argument d Matrix expected s tipo errado para o argumento d esperava matriz 210 s Wrong type for argument d List expected s tipo errado para o argumento d esperava lista 211 s Wrong type for argument d Function or string external function expected s tipo errado para o argumento d esperava função ou string função externa 212 s Wrong type for argument d Polynomial expected s tipo errado para o argumento d esperava polinômio 213 s Wrong type for argument d Working integer matrix expected s tipo errado para o argumento d esperava matriz de inteiros operante 214 Argument d of s wrong type argument expecting a vector Argumento d de s tipo de argumento errado esperava um vetor 215 dth argument type must be boolean désimo argumento deve ser booleano 216 Wrong type for argument d Boolean or scalar expected s tipo errado para o argumento d esperava booleano ou escalar 217 Wrong type for argument d Sparse matrix of scalars expected s tipo errado para o argumento d esperava matriz esparsa de escalares 218 Wrong type for argument d Handle to sparse lu factors expected s tipo errado para o argumento d esperava manipulador para fatores lu esparsos errortable 42 219 Wrong type argument d Sparse or full scalar matrix expected s tipo errado para o argu mento d esperava matriz de escalares esparsa ou completa 220 Null variable cannot be used here variável nula não pode ser usada aqui 221 A sparse matrix entry is defined with two differents values uma entrada da matriz esparsa é definida com dois valores diferentes 222 s not yet implemented for full input parameter s ainda não foi implementado para parâmetro de entrada completa 223 It is not possible to redefine the s primitive this way see clearfun não é possível redefinir a primitiva s desta forma ver clearfun 224 Type data base is full banco de dados de tipos está cheio 225 This data type is already defined este tipo de dado já foi definido 226 Inequality comparison with empty matrix comparação de desigualdade com matriz vazia 227 Missing index faltando índice 228 Reference to the cleared global variable s referência à variável global limpa s 229 Operands of and operations must not contain NaN of Inf operandos de e não devem conter NaN ou Inf 230 semidef fails semidef falhou 231 Wrong type for first input argument Single string expected tipo errado para o primeiro argu mento de entrada esperava string único 232 Entry name not found nome de entrada não encontrado 233 Maximum number of dynamic interfaces reached número máximo de interfaces dinâmicas alcançado 234 link expecting more than one argument link experava mais que um argumento 235 link problem with one of the entry point link problema com um dos pontos de entrada 236 link the shared archive was not loaded link o arquivo compartilhado não foi carregado 237 link Only one entry point allowed On this operating system link apenas um ponto de entrada permitido neste sistema operacional 238 link First argument cannot be a number primeiro argumento não pode ser um número 239 You cannot link more functions maxentry reached você não pode mais linkar funções número máximo de entradas alcançado 240 File s already exists or directory write access denied arquivo s já existe ou o acesso à escrita de diretório foi negado 241 File s does not exist or read access denied arquivo s não existe ou o acesso à leitura foi negado 242 Binary direct access files must be opened by file arquivos binários de acesso direto devem ser abertos por file 243 C file logical unit not allowed here unidade lógica do arquivo C não permitida aqui errortable 43 244 Fortran file logical unit not allowed here unidade lógica do arquivo FORTRAN não permitida aqui 245 No input file associated to logical unit d nenhum arquivo de entrada associado à unidade lógica d 246 Function not defined for given argument types função não definida para os tipos de argumentos fornecidos 247 Wrong value for argument d the lu handle is no more valid valor errado para o argumento d o manipulador lu não é mais válido 248 Wrong value for argument d Valid variable name expected valor errado para o argumento d esperava nome de variável válido 249 Wrong value for argument d Empty string expected valor errado para o argumento d esperava string vazio 250 Recursive extraction is not valid in this context extração recursiva não é válida neste contexto 251 bvode ipar dimensioned at least 11 bvode ipar dimensionado em pelo menos 11 252 bvode ltol must be of size ipar4 bvode ltol deve ser de tamanho ipar4 253 bvode fixpnt must be of size ipar11 bvode fixpnt deve ser de tamanho ipar11 254 bvode ncomp must be less than 20 bvode ncomp deve ser menor do que 20 255 bvode m must be of size ncomp bvode m deve ser de tamanho ncomp 256 bvode summ must be less than 40 bvode summ deve ser menor do que 40 257 bvode summ must be less than 40 bvode summ deve ser menor do que 40 258 bvode input data error bvode erro de dado de entrada 259 bvode no of subintervals exceeds storage bvode número de subintervalos excede o armazena mento 260 bvode Th colocation matrix is singular bvode a matriz de colocação é singular 261 Interface property table is full tabela de propriedades de interface está cheia 262 Too many global variablesmax number is d muitas variáveis globais O máximo é d 263 Error while writing in filedisk full or deleted file erro ao escrever em um arquivo disco cheio ou arquivo deletado 264 Wrong value for argument d Must not contain NaN or Inf valor errado para o argumento d não deve conter NaN ou Inf 265 A and B must have equal number of rows A e B devem ter o mesmo número de linhas 266 A and B must have equal number of columns A e B devem ter o mesmo número de colunas 267 A and B must have equal dimensions A e B devem ter dimensões iguais 268 Invalid return value for function passed in argd valor de retorno inválido para função pas sado no argumento d 269 Wrong value for argument d eigenvalues must have negative real parts valor errado para o argumento d autovalores devem ter partes reais negativas errortable 44 270 Wrong value for argument d eigenvalues modulus must be less than one valor errado para o argumento d módulos dos autovalores não devem ser menores que 1 271 Size varying argument aeye arg d not allowed here argumento de variação de tamanho aeye arg d não permitido aqui 272 endfunction is missing está faltando endfunction 273 Instruction left hand side waiting for a dot or a left parenthesis lado esquerdo da instrução esperava por um ponto ou parêntese esquerdo 274 Instruction left hand side waiting for a name lado esquerdo da instrução esperava um nome 275 varargout keyword cannot be used here palavrachave varargout não pode ser usada aqui 276 Missing operator comma or semicolon faltando operador vírgula ou pontoevírgula 277 Too many commands defined muitos comandos definidos 278 s Input arguments should have the same formal variable name s argumentos de entrada devem ter o mesmo nome de variável formal Ver Também warning errcatch execstr lasterror 45 Name evstr avaliação de expressões HevstrZ HierrevstrZ Parâmetros Z matriz de strings M ou listMSubexp M matriz de strings Subexp vetor de strings H matriz ierr inteiro indicador de erro Descrição Retorna o resultado da avaliação da matriz de strings M Cada elemento da matriz deve definir uma expressão Scilab válida Se a avaliação de M levar a um erro a versão de valor de único retorno HevstrM levanta erro de modo usual A versão de dois valores de retorno HierrevstrM por outro lado não produz erro mas retorna o número de erro em ierr Se Z é uma lista Subexp é um vetor de strings que define subexpressões que são avaliadas antes da avaliação de M Estas subexpressões devem ser referidas como k em M onde k é o índice da subexpressão em Subexp evstra1 não é válido use execstr ao invés Exemplos a1 b2 Zab evstrZ a1 b2 Zlist112a1b1 evstrZ Ver Também execstr 46 Name exists verifica existência de variáveis existsname where Parâmetros name string where um caractere opcional com possíveis valores l local n nolocal and a all O valor padrão é all Descrição existsname retorna 1 se a variável chamada name existe e 0 em caso contrário Aviso uma função que utiliza exists pode retornar um resultado que depende do ambiente existsnamelocal retorna 1 se a variável chamada name existe no ambiente local da função corrente e 0 em caso contrário existsnamenolocal retorna 1 se a variável chamada name existe em qualquer nível do ambiente de chamamento incluindo o nível principal do shell do Scilab da função corrente e 0 em caso contrário Aviso a função exists não verifica se a variável existe no espaço de nomes global Exemplos defffoox dispexistsa12existsa12local dispexistsxexistsxlocal foo1 a12foo1 function level1 function level2 dispexistsaall dispexistsalocal dispexistsanolocal endfunction level2 endfunction function go a1 level1 endfunction go Ver Também isdef isglobal whereis type typeof macrovar 47 Name exit termina a sessão Scilab corrente Descrição Termina a sessão Scilab corrente Ver Também quit abort break return resume 48 Name external objeto Scilab função ou rotina externa Descrição Função ou rotina externa para uso com comandos específicos Uma external é uma função ou rotina que é usada como argumento em algumas primitivas de alto nível tais como ode optim schur A seqüência de chamamento da external função ou rotina é imposta pela primitiva de alto nível que configura os argumentos da external Por exemplo a função externa costfunc é um argumento da primitiva optim Sua seqüência de chama mento deve ser fgindcostfuncxind e optim a primitiva de otimização de alto nível é invocada como segue optimcostfunc Aqui costfunc a função de custo a ser minimizada pela primitiva optim avalia ffx e g gradiente de f em x ind é um inteiro Seu uso é esclarecido na ajuda de optim Se a função externa necessita de outros valores estas variáveis podem ser definidas em seu ambiente Elas também podem ser colocadas em uma lista Por exemplo a função externa fgindcostfuncxindabc é válida para optim se o external função externa é listcostfuncabc e a chamada a optim é então optimlistcostfunca1b1c1 Um external também pode ser uma rotina FORTRAN ou C isto é conveniente para acelerar computações TO nome da rotina é fornecido para a primitiva de alto nível como um string A seqüência de chama mento da rotina também é imposta Rotinas FORTRAN ou C podem ser dinamicamente linkadas ligadas conectadas ver link Ver Também ode optim impl dassl intg schur gschur 49 Name extraction extração de entradas de matrizes e listas xi xij xijk li lk1kni ou llistk1kni lk1knij or llistk1knlistij Parâmetros x matriz de qualquer tipo possível l variável do tipo lista ij k índices k1kn índices Descrição CASO DE MATRIZES i j k podem ser escalares reais ou vetores ou matrizes com elementos positivos rxij constrói a matriz r tal que rlkxintilintjk para l de 1 a sizei e k de 1 a sizej O valor máximo de i j deve ser menor do que ou igual a sizex1 sizex2 rxi com x uma matriz 1x1 contrói a matriz r tal que rlkxintilintik para l de 1 a sizei1 e k para 1 a sizei2 Note que nesse caso o índice i é válido apenas se todas as suas entradas são iguais a 1 rxi com x um vetor linha constrói o vetor linha r tal que rlxintil para l de 1 a sizeii deve ter valor máximo menor do que ou igual a sizex rxi com x uma matriz com uma ou mais colunas constrói o vetor coluna r tal que rl l de 1 a sizei contém a entrada intil do vetor coluna formado pela concatenação das colunas de x i deve ter valor máximo menor do que ou igual a sizex O símbolo significa todos os elementos rxi constrói uma matriz r tal que rlkxintilk para l de 1 a sizei and k from 1 to sizex2 extraction 50 rxj constrói a matriz r tal que rlkxlintjk para l de 1 a sizer1 e k de 1 a sizej rx constrói o vetor coluna r formado pelas concatenações das colunas de x É equivalente a matrixxsizex1 vetor de booleanos Se um índice i ou j é um vetor de booleanos é interpretado como findi ou respec tivamente findj um polinômio Se um índice i ou j é um vetor de polinômios ou um vetor de polinômios implícito é interpretado como hornerim ou respectivamente hornerjn onde m e n são as dimensões associadas a x Mesmo se este recurso funcionar para todos os polinômios é recomendado utilizar polinômios em para legibilidade Para matrizes com mais de duas dimensoes verhypermatrices a dimensionalidade é automati camente reduzida quando as dimensões mais a direita são 1 CASO DE LISTAS OU TLISTS Se estiverem presentes os ki fornecem o endereço para uma entrada de sublista da estrutura de dados l Eles permitem uma extração recursiva sem cópias intermediárias As instruções lk1kni e llistk1kni são interpretadas como lk1 lk1 lkn lkn1kn lkni e as instruções lk1knij e llistk1knlistij são interpretadas como lk1 lk1 lkn lkn1kn lknij i e j podendo ser quando pontos de endereço sobre mais de um componente da lista a instrução deve ter tantos argumentos do lado esquerdo quanto os componentes selecionados Mas se a sintaxe de extração é usada dentro da seqüência de chama mento de entrada de uma função cada componente da lista retornado é adicionado à seqüência de chamamento da função Note que llist é o mesmo que l i e j podem ser escalares reais ou vetores ou matrizes de elementos positivos r1rnli extrai os elementos ik da lista l e armazenaos em variáveis rk para k de 1 a sizei O símbolo significa todos os elementos um vetor de booleanos Se i é um vetor de booleanos é interpretado como findi um polinômio Se i é um vetor de polinômios ou um vetor de polinômios implícito é interpretado como hornerim onde msizel Mesmo que este recurso funcione para todos os polinômios é recomendado utilizar polinômios em para legibilidade k1kn podem ser escalares reais posistivos extraction 51 um polinômio interpretado como hornerkim onde m é o tamanho da sublista correspondente string associado ao nome da entrada da sublista Observações Para tipos de matrizes softcoded como funções racionais e sistemas lineares de espaços de estados a sintaxe xi não pode ser usada para extração de elementos de vetores devido a confusões com extração de elementos de listas A sintaxe x1j ou xi1 deve ser usada Exemplos CASO DE MATRIZES a1 2 34 5 6 a12 a1 12 a1 a311 a1 a6 a at f f t at f2 3 a121 a112 a xteste x1 11 11 1 b1ss1s1 b11 b1 b2 o numerador CASO DE LISTAS OU TLISTS llist1qwerws l1 abl3 2 l xtlistl23 forma um tlist com os últimos dois componentes de l dtslist1tlistxab102 3 dts2a dts2b12 abdts2ab Ver Também find horner parents 52 Name for palavrachave de linguagem para laços loops significa para Descrição Usado para definir laços loops sua sintaxe é for variávelexpressão instrução instruçãoend for variável expressão do instrução instruçãoend Se expressão é uma matriz ou um vetor linha variável toma como valores os valores de cada coluna da matriz Um caso particular utiliza o operador colon para criar vetores linhas regularmente espaçados e re monta a formas de laço for tradicionais for variablen1stepn2 end Se expressão é uma lista variável toma como valores as entradas sucessivas da lista Aviso o número de caracteres usados para definir o corpo de qualquer instrução condicional if while for ou selectcase deve ser limitado a 16k Exemplos laços for tradicionais n5 for i 1n for j 1n aij 1ij1endend for j 2n1 ajj j end a for j 411 dispjend laço decrescente laço em colunas de matrizes for eeye33eend for va write6vend for j1nvaj write6vend laço em listas de entradas for llist12example lend Ver Também while end do 53 Name format impressão de números e formato de exibição formattypelong v format formatm Parâmetros type string long inteiro número máximo de digitos padrão 10 v um vetor para o formato corrente onde v1 é o de tipo de formato 0 para e e 1 para v v2 número de dígitos m um vetor para ajuste de novo formato m1 número de digitos m2 tipo de formato 0 para e e 1 para v Descrição Ajusta o formato de impressão corrente através do parâmetro type é um dos seguintes v para um formato variável default e para o formato e notação científica long define o número máximo de dígitos padrão 10 format retorna o vetor que indica o fomato corrente primeiro componente é o tipo do formato 1 se v 0 se e o segundo componente é o número de digitos No formato variável entradas de vetores que são menores que eps vezes o valor absoluto máximo das entradas era exibido como 0 em versões anteriores do Scilab Não é mais o caso a função de clean pode ser usada para ajustar as entradas negligenciáveis para zeros Exemplos xrand15 formatv10x format20x formate10x format20x x100 eps formate10x formatv10x format 54 formatv Ver Também write disp print 55 Name funcprot alterna o modo de proteção de funções Scilab protfuncprot funcprotprot Parâmetros prot inteiro com valores possíveis 01 ou 2 Descrição Funções Scilab são variáveis funcprot permite especificar o que o Scilab faz quando tais variáveis são redefinidas Se prot0 nada especial é feito Se prot1 o scilab exibe uma mensagem de aviso quando a função é redefinida modo padrão Se prot2 o scilab exibe uma mensagem de erro quando a função é redefinida Exemplos funcprot1 deffxfooaxa deffxfooaxa1 foo33 funcprot0 deffxfooaxa deffxfooaxa1 foo33 56 Name funptr codificação de primitivas numptr funptrname Parâmetros name string nome de uma primitiva numptr o número de rotina interno da primitiva Descrição Fução utilitária para usuários mais experientes apenas para retornar o número de rotina interno numptr da primitiva name numptr é formado a partir do número de interface fun e do número de rotina fin da primitiva em sua interface por numptr 100fun fin fin 100 De numptr podese obter o número de interface fun floornumptr100 que pode ser útil para ligar uma interface dinâmica com seus argumentos passados por referência ver seção de exemplos Exemplos Suponha que você queira carregar alguns códigos através das facilidades de carregamento dinâmico oferecidas por addinter Por padrão os argumentos são passados por valores mas se você quiser passálos por referência você pode fazer o seguinte nome sendo o nome scilab de uma das rotinas com interface addinterfilesspnamesfcts argumentos passados por valores numinterface floorfunptrnome100 intpptynuminterface argumentos agora passados por referência Note que se você digitar o seguinte intppty você verá todas as interfaces funcionando por referência Ver Também clearfun newfun intppty addinter 57 Name getdebuginfo retorna informações sobre o Scilab para o debug getdebuginfo dynamicinfo getdebuginfo dynamicinfostaticinfo getdebuginfo Descrição getdebuginfo retorna informações sobre o Scilab para o debug dynamicinfo getdebuginfo retorna informações sobre o seu sistema operacional dynamicinfostaticinfo getdebuginfo retorna informações sobre o seu sistema operacional e sobre o Scilab Ver Também getversion Autor AC 58 Name getmd5 retorna soma de verificação md5 resgetmd5filename resgetmd5ParamStringstring Parâmetros res resultado md5 string filename nome do arquivo string ou matrizes de strings ParamString string ou matrizes de strings Descrição getmd5 retorna a soma de verificação md5 de um arquivo ou um string Exemplos getmd5ola mundostring getmd5ola mundostring getmd5ola mundostring getmd5 SCImodulescoreetccorestart getmd5 SCImodulescoreetccorestart corequit Autor AC 59 Name getmemory retorna as memórias livre e total do sistema free totalgetmemory Descrição getmemory retorna a memória livre do sistema em kilooctetos free totalgetmemory retorna as memórias livre e total do sistema em kilooctetos Autor AC 60 Name getmodules retorna a lista de módulos instalados no Scilab resgetmodules Parâmetros res uma matriz de strings Descrição Retorna a lista de módulos instalados no Scilab Ver Também withmodule Autor Ac 61 Name getos retorna o nome e a versão do Sistema Operacional OSgetos OSVersiongetos Descrição getos retorna o nome e a versão do Sistema Operacional Exemplos OSgetos OSversiongetos Autor AC 62 Name getscilabmode retorna o modo do Scilab mode getscilabmode Descrição Retorna o modo do Scilab Quatro são os possíveis modos STD API NW NWNI API o Scilab é lançado como um API STD o Scilab padrão gui plot NW Scilab em linha de comando com esboços NWNI Scilab em linha de comando sem quaisquer gráficos Exemplos getscilabmode Ver Também scilab 63 Name getshell retorna o interpretador de comando corrente getshell Descrição getshell retorna o interpretador de comando corrente Exemplos getshell Autor Allan CORNET 64 Name getvariablesonstack retorna nomes de variáveis em na pilha Scilab sgetvariablesonstack sgetvariablesonstacklocal sgetvariablesonstackglobal Parâmetros s uma matriz de strings Descrição Retorna na variável s nomes de variáveis na pilha do Scilab getvariablesonstacklocal retorna o nome das variáveis locais na pilha getvariablesonstackglobal retorna o nome das variáveis globais na pilha As variáveis são organizadas na ordem alfabética Exemplos getvariablesonstack getvariablesonstacklocal getvariablesonstackglobal Ver Também who 65 Name getversion retorna o nome da versão do Scilab versiongetversion versionoptsgetversion vergetversionscilab versioninfogetversionscilabstringinfo vergetversionmodule versioninfogetversionmodulestringinfo Parâmetros version um string versioninfo um string sobre a versão ver um vetor de inteiros ver1 versão maior ver2 versão menor ver3 versão de manutençãp ver4 timestamp GIT opts um vetor de strings de 7 entradas compiler pvm tk modelicac releasemode releasedate releasetime Descrição Retorna em version o nome da versão do Scilab e em opts build options opções de construção que podem ser usadas para determinar se o Scilab foi construído em pvm tk ou modelicac Exemplos getversion versionoptsgetversion vergetversionscilab verstrgetversionscilabstringinfo vergetversionoverloading verstrgetversionoverloadingstringinfo Ver Também getmodules 66 Name global define variável global globalnam1namn global nam1 namn Parâmetros nam1 namn nomes de variáveis válidos Descrição De um modo simples cada função do Scilab possui suas próprias variáveis locais e pode ler todas as variáveis criadas no espaço de trabalho base ou pelas funções de chamamento A palavrachave global permite realizar leituras ou escritas de variáveis através de funções Qualquer atribuição àquela variável em qualquer função está disponível para todas as outras funções que a declaram como variável global Se a variável global não existe não possui valor na primeira vez em que você escrever a declara como global será inicializada como matriz nula Exemplos primeiro o ambiente de chamamento e uma função compartilham uma variável global a a1 deffyf1xglobal aax2ya2 f12 a segundo três funções compartilham variáveis deffinitdataglobal A C A10C30 deffletsgoglobal A C dispA C70 deffletsgo1global C dispC initdata letsgo letsgo1 Ver Também who isglobal clearglobal gstacksize resume 67 Name gstacksize Ajustaretorna a pilha global do Scilab gstacksizen gstacksizemax gstacksizemin szgstacksize Parâmetros n inteiro o tamanho da pilha global requerido dado em número das palavras de dupla precisão sz vetor de duas entradas total used Descrição Scilab armazena variáveis globais em uma pilha gstacksizen permite ao usuário aumentar ou diminuir o tamanho da pilha O tamanho máximo permitido depende da quantidade de memória livre e do espaço de troca swap space disponível no momento Note que o Scilab pode aumentar automaticamente o tamanho da pilha global quando necessário szgstacksize retorna um vetor de duas entradas que contém os tamanhos de pilha global total e usado correntes gstacksizemax permite que o usuário aumente o tamanho desta pilha global ao máximo gstacksizemin permite que o usuário diminua o tamanho desta pilha global para máximo Ver Também who stacksize 68 Name hat exponentiation Ab Descrição Exponenciação de matrizes ou vetores por um vetor constante Se A é um vetor ou uma matriz retangular a exponenciação é feita elemento a elemento no sentido usual Para matrizes quadradas a exponenciação é feita no sentido matricial Para matrizes de booleanos polinômios ou razões de polinômios o expoente deve ser um inteiro Observações 123b é interpretado como 123b Em tais casos o ponto é parte do operador não do número Para dois números reais ou complexos x1 e x2 o valor de x1x2 é o valor principal determinado por x1x2 expx2logx1 Exemplos 24 0513 1 22 41i spoly0s 1 2 s4 s 11 s1 Ver Também exp inv 69 Name ieee ajusta o modo de exceção de ponto flutuante modieee ieeemod Parâmetros mod escalar inteiro com possíveis valores 01ou 2 Descrição ieee retorna o modo de exceção de ponto flutuante corrente 0 exceção de ponto flutuante produz um erro 1 exceção de ponto flutuante produz um aviso 2 exceção de ponto flutuante produz um Inf ou NaN infinito ou não é número ieeemod ajusta o modo corrente de excessão de ponto flutuante O valor de modo incial é 0 Observações Exceções de ponto flutuante emergentes em alguns algoritmos de bibliotecas ainda não são manipu ladas pelos modos ieee Exemplos ieee110 ieee210log0 Ver Também errcatch 70 Name if then else Execução condicional significa se então senão if expressão1 then sentenças elseif expressãoi then sentenças else sentenças end Descrição A sentença if avalia sentenças lógicas e executa um grupo de sentenças se a expressão é verdadeira As expressõesi são expressões com valores numéricos ou booleanos Se as expressõesi são matrizes a condição é verdadeira somente se todas as entradas da matriz são true verdadeiro ou diferentes de 0 Os opcionais elseif e else propiciam execução de grupos de sentenças alternativas A palavra chave end keyword que corresponde ao iftermina o último grupo de sentenças A estrutura de linhas dada acima não é importante a única restrição é que cada palavrachave thendeve estar na mesma linha de sua palavrachave if ou elseif correspondente A palavrachave then pode ser substituída por um retorno de carro ou uma vírgula Aviso o número de caracteres utilizados para definir o corpo de qualquer instrução condicional if while for or selectcase deve ser limitado a 16k Exemplos i2 for j 13 if i j then aij 2 elseif absij 1 then aij 1 else aij 0 end end Ver Também try while select boolean end then else 71 Name insertion atribuição ou modificação parcial de variáveis assignation atribuição parcial de variáveis xija xia lia lk1knia or llistk1knia lk1knija or llistk1knlistija Parâmetros x matriz de qualquer tipo l lista ij índices k1kn índices com valores inteiros a novo valor de entrada Descrição CASO DE MATRIZES Se x é uma matriz os índices i e j podem ser Escalares reais vetores ou matrizes neste caso os valores fornecidos como índices devem ser inteiros e apenas suas partes inteiras são levadas em consideração Se a é uma matriz com dimensões sizeisizej xija re torna uma nova matriz x tal que xintilintjkalk para l de 1 a sizei e k de 1 a sizej as outras entradas iniciais de x não são modificadas Se a é um escalar xija retorna uma nova matriz x tal que xintilintjka para l de 1 a sizei e k de 1 a sizej as outras entradas iniciais de x não são modificadas Se o valor máximo de i ou j exceder a dimensão correspondente da matriz x o array x é previamente estendido para as dimensões requeridas com entradas 0 para matrizes padrões strings de comprimento 0 para matrizes de strings e valores falsos para matrizes de booleanos xij cancela linhas especificadas por i se j corresponde a todas as colunas de x ou cancela colunas especificadas por j se i corresponde a todas as linhas de x Em outros casos xij produz um erro xia com a um vetor retorna a nova matriz x tal que xintilal para l de 1 a sizei outras entradas iniciais de x não são modificadas xia com a um escalar retorna uma nova matriz x tal que xintila para l de 1 a sizei outras entradas iniciais de x não são modificadas insertion 72 Se o valor máximo de i exceder sizex1 x é previamente estendida para a dimensão requerida com entradas 0 para matrizes padrões strings de comprimento 0 para matrizes de strings e valores falsos para matrizes de booleanos Se x é uma matriz 1x1 a pode ser um vetor linha respectivamente coluna com dimensão sizei A matriz x resultante é um vetor linha respectivamente coluna Se x é um vetor linha a deve ser um vetor linha de dimensão sizei Se x é um vetor coluna a deve ser um vetor coluna de dimensão sizei Se x é uma matriz geral a deve ser um vetor linha ou coluna de dimensão sizei e o valor máximo de i não pode exceder sizex xi cancela entradas especificadas por i O símbolo O símbolo significa todos os elementos xia é interpretado como xi1sizex2a xja é interpretado como x1sizex1ja xa retorna em x a matriz a de forma redefinida de acordo com as dimensões de x sizex deve ser igual a sizea Vetores de booleanos se um índice i ou j é um vetor de booleanos é interpretado como findi ou respec tivamente findj Polinômios se um índice i ou j é um vetor de polinômios ou um vetor de polinômios implícito é interpretado como hornerim ou respectivamente hornerjn onde m e n são as dimensões associadas de x Mesmo se esse recurso funcionar para todos os polinômios é recomendado utilizar polinômios em para legibilidade CASO DE LISTAS OU TLISTS Se estiverem presentes os ki fornecem o endereço para uma entrada de sublista da estrutura de dados l data structure Eles permitem uma extração recursiva sem cópias intermediárias As instruções lk1knia e llistk1knia são interpretadas como lk1 lk1 lkn lkn1kn lkni a lkn1kn lkn lk1 lk1 insertion 73 E as instruções lk1knija e llistk1knlistija são interpretadas como lk1 lk1 lkn lkn1kn lknij a lkn1kn lkn lk1 lk1 i pode ser Um escalar real nãonegativo l0a adiciona uma entrada à esquerda da lista lia configura a entrada i da lista l como a Se isizel l é previamente estendido com entradas de comprimento 0 indefinidas linull suprime a iésima entrada da lista Um polinômio Se i é um polinômio é interpretado como hornerim onde msizel Mesmo se este recurso funcionar para todos os polinômios é recomendado utilizar polinômios em para legibilidade k1kn podem ser Escalares reais positivos Polinômios interpretados como hornerkim onde m é o tamanho da sublista corre spondente Strings associados a nomes de entradas de uma sublista Observações Para tipos de matrizes softcoded como funções racionais e sistemas lineares de espaços de estados a sintaxe xi não pode ser usada para inserção de entradas em vetores devido a confusões com inserção de entradas em listas A sintaxe x1j ou xi1 deve ser usada Exemplos CASO DE MATRIZES a1 2 34 5 6 a1210 a1 1212 a185 a131177 44 99 a1s a6s1 a16 at f133 a12124 a11187 a123 xteste x4 545 b1ss1s1 b110 b1b11 insertion 74 b21 2 o numerador CASO DE LISTAS OU TLISTS llist1qwerws l1Modificado l0Adicionado l6mais umadicionado dtslist1tlistxab102 3 dts2a33 dts2b12100 Ver Também find horner parents extraction 75 Name intppty ajusta propriedades de passagem de argumentos de interface funsintppty intpptyfun Parâmetros fun inteiro um número de interface ver funptr funs vetor de inteiros vetor de números de interface ver funptr Descrição Os programas de interface pode ser escritos de duas formas diferentes para o modo de passagem de argumento de funções No primeiro modo que é o padrão os argumentos são passados por valor A sintaxe é a seguinte fooA12 o argumento associado a A será passado por valores uma cópia de A é feita antes de foo i ser chamada e o argumento associado a 12 será passado por valor No segundo modo os argumentos podem ser passados por referência se houver argumentos nomea dos nenhuma cópia do valor da variável é feita intpptyfun com fun0 diz ao Scilab que a interface com o número fun pode manipular argumentos passados por referência A sintaxe é a seguinte fooA12 O argumento associado a A será passado por referência e o argumento associado a 12 será passado por valor Aviso a declaração de interface com número fun pode manipular argumentos passados por referência se não for o caso de produzir resultados imprevisíveis intpptyfun com fun0 suprime esta propriedade para para a interface fun intppty retorna o vetor de interfaces que manipulam argumentos passados por referência Esta função pode ser útil para interfaces dinamicamente carregadas ver addinter Ver Também funptr addinter 76 Name invcoeff constrói uma matriz de polinômios a partir de seus coeficientes PinvcoeffCdname Parâmetros C matriz grande de coeficientes d grau da matriz de polinômios Parâmetro opcional com valor padrão d1sizeCc sizeCr name string fornecendo o nome da variável polinomial valor padrão x Descrição PinvcoeffMpk quando k é compatível com o tamanho de Mp size retorna uma matriz de polinômios de grau k CC0C1Ck and P C0 C1x Ckxk Exemplos Aint10rand26 Construindo uma matriz de polinômios de grau 1 PinvcoeffA1 normcoeffPA Usando valor padrão para o grau P1invcoeffA normcoeffP1A Ver Também poly degree coeff 77 Name iserror teste de ocorrência de erros iserrorn Descrição Testa se um número de erro n ocorreu após uma chamada a errcatch iserror retorna 1 se o erro ocorreu e 0 caso contrário n0 é o número do erro todos os erros são testados com n0 Ver Também error errcatch 78 Name isglobal verifica se uma variável é global tisglobalx Parâmetros x qualquer variável t um valor booleano Descrição isglobalx retorna true verdadeiro se x tiver sido declarada como variável global e false falso em caso contrário Exemplos isglobal1 global a isglobala Ver Também global clearglobal who 79 Name lasterror retorna a última mensagem de erro registrada strlasterror opt strnlasterroropt strnlinefunclasterroropt Parâmetros str vetor de strings ou matriz vazia a última mensagem de erro registrada n inteiro 0 ou o último número de erro registrado line inteiro 0 ou o último número de linha da função registrado func string o último nome da função registrado opt booleano se t for registrado a mensagem é limpa O padrão é t Descrição Cada vez que um erro ocorre o manipulador de erros do Scilab o registra em tabelas tables internas apenas o último erro é retido A função lasterror permite obter a mensagem de erro o número de erro a função corrente se houver e a linha corrente da função corrente destas tabelas O número de linha reportado é o número da linha física onde o último erro ocorreu Note que versões Scilab anteriores à 50 reportavam o número da linha lógica do último erro A diferença realmente importa apenas se a função em erro inclui linhas continuadas antes do ponto onde o erro ocorreu Esta função é útil quando usada em conjunto com errcatch ou execstr A mensagem de erro pode ser retida para uma futura chamada a lasterror usando lasterrorf Exemplos ierrexecstrazzzzzzzerrcatch if ierr0 then displasterrorend Ver Também errcatch execstr error errclear editerror 80 Name left colchete esquerdo a11a12a21a22 s1s2func Parâmetros a11a12 matriz de qualquer tipo compatível com dimensões compatíveis s1s2 qualquer nome de variável possível Descrição Colchetes esquerdo e direito são usados para concatenação de vetores e matrizes Estes símbolos também são utilizados para denotar um lado esquerdo múltiplo para uma chamada de função Dentro de colchetes de concatenação espaços em branco ou vírgulas significam concatenação de colunas pontosevírgulas e retornos de carro significam concatenação de linhas Nota para evitar confusões é preferível que se use vírgula no lugar de espaços em branco para separar colunas Dentro de colchetes de lado esquerdo múltiplo nomes de variáveis devem ser separados por vírgula Exemplos 69964 sqrt1 0 1 i 2 i 3 this isa stringvector spoly0s1s2s tf2ss1stf2ss2s usschurrand33 Ver Também comma semicolon 81 Name less comparação menor do que great comparação maior do que Descrição Símbolo de comparação lógica significa diferente é o mesmo que significa menor do que significa maior do que significa maior do que significa maior do que ou igual a Ver Também if comparison equal 82 Name macr2lst conversão de função para lista txtmacr2lstfunctionname Descrição Esta primitiva converte uma versão compilada do Scilab functionname em uma lista que codifica a representação interna da função notação polonesa inversa A primeira entrada da lista é o nome da função as segunda e terceira são respectivamente os vetores das variáveis de lado esquerdo e direito lhs e rhs As entradas seguintes são registros de operação básica ou listas que contém as estruturas de controle hierárquicas como if for Registros de operação básica são descritos por um vetor de strings cujo primeiro elemento representa código do operador op code op codes significado parâmetros 0 opcode ignorado nenhum 1 não mais usado 2 referência à função ou variável nome da variável rhs lhs 3 coloca um string na pilha um string 4 coloca uma matriz vazia na pilha nenhum 5 aplica uma operação código de operação rhslhs 6 coloca um número na pilha o número 12 comando pause nenhum 13 comando break nenhum 14 comando abort nenhum 15 marca de fim da linha nenhum 17 comando quit nenhum 18 variável nomeada nome da variável 19 cria estrutura de índice recursiva comprimento do endereço número de índices finais 20 chamada a função nome da função rhs lhs 23 cria variável a partir do nome nome da variável 24 coloca uma variável de tipo 0 na pilha nenhum 25 registro de perfil número da chamada gasto de tempo 26 coloca um vetor de strings na pil ha linhas colunas seqüência de elementos 27 coloca uma referência a um builtin na pilha número da interface posição da interface nome da função 28 comando continue nenhum 29 atribuição lhs modo de exibição nome da variável rhs 30 curto circuito de expressão lógica tipo tamanho do salto jump macr2lst 83 31 comentário o comentário 99 comando return nenhum 100 chamada a um builtin obsoleto 100fun rhs lhs fin A função fun2string pode ser usada para se gerar o código inicial Exemplos EXIBIÇÃO function yfooxflag if flag then ysinx else ycosx end endfunction Lmacr2lstfoo fun2stringL Ver Também macrovar fun2string macr2tree tree2code 84 Name macr2tree conversão de função para árvore tmacr2treefunctionname Parâmetros functionname macro do Scilab t uma árvore do Scilab Descrição Esta primitiva converte uma função Scilab compilada functionname em uma árvore tlistas im bricadas que codifica a representação interna da função Deve ser usada com tree2code Exemplos treemacr2treecosh txttree2codetreeT writeio2txta Ver Também tree2code Autor VC 85 Name matrices objeto do Scilab matrizes Descrição Matrizes são objetos básicos definidos no Scilab Elas podem ser definidas como segue Ee11e12e1n e21e22e2n em1em2emn As entradas eij podem ser números reais complexos polinômios razões de polinômios strings ou booleanos Vetores são vistos como matrizes de uma linha ou uma coluna Exemplos E1234 ETF1111 spoly0sEss211s E1s0s1s1 EA11A12A21A22 Ver Também poly string boolean rational empty hypermatrices 86 Name matrix Muda a forma de vetores ou matrizes ymatrixvnm ymatrixvsizes Parâmetros v vetor matriz ou hipermatriz nm inteiros sizes vetor de inteiros y vetor matriz ou hipermatriz Descrição Para um vetor ou matriz com n x m entradas o comando ymatrixvnm ou de modo similar ymatrixvnm transforma o vetor ou matriz v em uma matriz nxm empilhando as entradas coluna a coluna de v Se uma das dimensões m ou n é igual a 1 ela é automaticamente atribuída ao quociente de tamanho v pela outra dimensão Para uma hipermatriz tal como prodsizevprodsizes o comando ymatrixvsizes ou equivalentemente ymatrixvn1n2nm transforma v em uma matriz ou hipermatriz empilhando coluna a coluna as entradas de v a primeira dimensão var iando primeiro ymatrixvsizes resulta numa matriz regular se os tamanhos são escalares ou um vetor de duas entradas Exemplos a1 2 34 5 6 matrixa16 matrixa11 matrixa32 Ver Também matrices hypermatrices ones zeros rand poly empty 87 Name mode seleciona um modo em um arquivo executável modek kmode Descrição Usado exclusivamente dentro de um arquivo executável ou uma função do Scilab modek permite mudar as informações exibidas durante a execução dependendo do valor de k k0 os novos valores de variáveis são exibidos se requeridos ver ajuda em semi ou comma k1 o arquivo executável ou a função Scilab roda silenciosamente este é o valor padrão para funções do Scilab k1 or k3 cada linha de instruções é ecoada precedida do prompt se possível Os novos valores de variáveis são exibidos se requerido Este é o padrão para arquivos executáveis k7 Os novos valores de variáveis são exibidos se requerido Cada linha de instruções é ecoada se possível e um prompt aparece após cada linha esperando por um retorno de carro Se o retorno de carro segue o caractere p a execução é pausada ver pause A exibição de linha é desabilitada para funções do Scilab compiladas ver comp Por padrão funções do Scilab são executadas no modo silencioso 1 Ver Também exec semicolon comma 88 Name mtlbmode alterna para modo de operações do Matlab mmodemtlbmode mtlbmodemmode Parâmetros mmode booleano Descrição Adições e subtrações do Scilab e do Matlab funcionam de modo diferente quando usadas com matrizes vazias Scilab a a a a a a a a Matlab a a a a mtlbmodet alterna para o modo de operações para adição e subtração do Matlab mtlbmodef volta para o modo de operações do Scilab mtlbmode retorna o valor mmode corrente Ver Também empty 89 Name names scilab names syntax Descrição Nomes de variáveis ou funções no Scilab devem começar com uma letra ou com um dos seguintes caracteres especiais Os próximos caracteres podem ser letras ou um dos seguintes caracteres especiais Nomes podem ser tão longos quanto se queira mas apenas os primeiros 24 caracteres serão levados em consideração Letras maiúsculas e minúsculas são diferentes Exemplos Nomes válidos eps A1123 Color8 MySpecialColorTablerand103 Nomes inválidos 1A b C 90 Name newfun adiciona um nome à tabela de funções newfunfunctionnamenameptr Descrição Função utilitária apenas para peritos Adiciona o nome functionname à tabela de funções conhecidas pelo interpretador nameptr é um inteiro 100funfin onde fun e fin é a codficação interna da primitiva functionname Esta função é útil para associar uma primitiva a uma rotina com interface em matusrf fun14 Usado com funptr e clearfun pode se redefinir uma primitiva por uma função com o mesmo nome Ver Também clearfun 91 Name null deleta um elemento em uma lista linull Descrição Deleta objetos dentro de uma lista Exemplos llist123 l2null retorna list13 Ver Também list clear 92 Name parents parênteses esquerdo e direito expressão funce1e2 x1x2e1e2 xij vi li Parâmetros x matriz de qualquer tipo possível v vetor linha ou coluna de qualquer tipo possível l variável tipo lista func qualquer nome de função e1e2 qualquer tipo possível de expressão Descrição Parênteses esquerdo e direito são usados para Especificar ordem de avaliação dentro de expressões Formar listas de argumentos do lado direito de uma função Dentro de lados direitos múltiplos os argumentos devem ser separados por vírgula Selecionar elementos dentro de vetores matrizes e listasVer ajuda em insertion e extraction para maiores informações x1x2e1e2 é equivalente a realizar primeiro t1 e1 t2 e2 e então x1 t1 x2 t2 onde as variáveis ti i 1 2 são visíveis ao usuário Exemplos 31 xpoly0x x102 i3eye33 a1 2 34 5 67 8 9a13a1 3a3 a3 a133 a2 1 a1101112 parents 93 wssrand222ssprintw ssprintw1 ss2tfw1 llist1234 abcdl l1novo vt1 1 1 1 1 xyz123 Ver Também colon comma brackets list extraction insertion 94 Name pause modo de pausa invoca teclado Descrição Alterna para o modo pause inserido no código de uma função pause interrompe a execução da mesma recebese um símbolo de prompt para indicar o nível de pause exemplo 1 O usuário está agora num novo espaço de trabalho em que todas as variáveis de nível infeiror em particular todas as variáveis da função estão disponíveis Para retornar ao espaço de trabalho de chamamento entre return Neste modo return retorna as variáveis dos argumentos ao espaço de trabalho de chamamento com nomes na saída Em caso contrário as variáveis de nível infeiror são protegidas e não podem ser modificadas pause é extremamente útil para propósitos de depuramento Este modo pode ser cancelado pelo comando abort Ver Também halt return abort quit whereami where sleep 95 Name percent caractere especial Descrição Alguns nomes de variáveis predefinidas começam com tais como i para sqrt1 inf para Infinity pi para 314 T para a constante booleanatrue Ainda funções cujo nome começa com são especiais elas são usadas para primitivas e overloading sobrecarga de operadores ver overloading Por exemplo a função rmr realiza a operação de multiplicação m xy para x e y matrizes de razões de polinômios r As convenções de codificação são fornecidas pelo arquivo leiame no diretório SCIDIRmacrospercent Exemplos x1tlistx12 x2tlistx23 deffxxmxx1x2xlistxx12x22x23x23 x1x2 Ver Também overloading 96 Name perl chama script Perl utilizando um executável apropriado do sistema operacional perlperlfile perlperlfilearg1arg2 result perl Descrição perlperlfile chama o script Perl perlfile utilizando o executável Perl apropriado do sistema opera cional perlperlfilearg1arg2 chama o script Perl perlfile utilizando o executável Perl apropriado do sistema operacional e passa os argumentos arg1 arg2 e assim por diante a perlfile result perl retorna os resultados de uma chamada a Perl tentada para result Ver Também unix Autor AC 97 Name plus operador de adição XY str1str2 Parâmetros XY escalar vetor ou matriz de números polinômios ou razões de polinômios Também pode ser uma lista syslin str1str2 um string um vetor ou uma matriz de strings Descrição Adição Para operandos numéricos é a adição em sentido usual Se um dos operandos é uma matriz e o outro um escalar o escalar é adicionado a cada uma das entradas da matriz Se um dos operandos é a matriz vazia um o outro operando é retornado este comportamento padrão pode ser modificado pela função mtlbmode Para strings significa concatenação A adição também pode ser definida para outros tipos de dados através de operações softcod ed codificação suave ver overloading Ver Também 121 2 spoly0s s2 1s2 catenate See Also addf mtlbmode overloading 98 Name poly definição de polinômios ppolyax flag Parâmetros a matriz ou número real x String o nome da variável simbólica Se o string tiver mais de 4 caracteres apenas os quatro primeiros serão levados em conta flag string roots coeff valor padrão é roots Descrição Se a é uma matriz p é o polinômio característico ie determinantxeyea x sendo a variável simbólica Se v é um vetor polyvxroots é o polinômio com entradas de v como raízes e x como variável formal neste caso roots e poly são funções inversas Note que infinitas raízes fornecem zero coeficientes de grau mais elevado polyvxcoeff cria o polinômio com símbolo x e com entradas de v como co eficientes v1 é o termo constante do polinômio aqui poly e coeff são funções inversas spoly0s é a fonte para definir polinômios com símbolo s Exemplos spoly0sp1s2s2 Arand22polyAx frações racionais h12spoly14sc See Also coeff roots varn horner derivat matrices rational 99 Name power operação de potenciação tAb tAb tAb Parâmetros At matriz de escalares polinômios ou razões de polinômios b um escalar ou um vetor ou matriz de escalares Descrição AsquarebscalarSe A é uma matriz quadrada e b é um escalar então Ab é a matriz A elevada à potência b AmatrixbscalarSe b é um escalar e A uma matriz então Ab é formada pelos elementos de A elevados à potência b potenciação elemento a elemento Se A é um vetor e b é um escalar então Ab e Ab realizam a mesma operação ie potenciação elemento a elemento Ascalarbmatrix Se A é um escalar e b é uma matriz ou vetor então Ab e Ab são as matrizes ou vetores formados por abij Amatrixbmatrix Se A e b são vetores matrizes de mesmo tamanho Ab é o vetor Aibi matriz Aijbij Notas Para matrizes quadradas Ap é computada através de sucessivas multiplicações de matrizes se p is é um número inteiro positivo e por diagonalização se não for Os operadores e são sinônimos Exemplos A1 23 4 A25 A25 1102 1102 spoly0s s110 Ver Também exp 100 Name predef proteção de variáveis npredef oldnewpredefn oldnewpredefall oldnewpredefclear Descrição Função utilitária para definir as variáveis mais antigas como protegidas Variáveis protegidas não podem ser cancelada Elas não são salvas pelo comando save As variáveis mais antigas são aquelas que aparecem por último em whoget predef retorna o número de variáveis protegidas predefall ajusta todas as variáveis como protegidas também retorna o número antigo e o novo de variáveis protegidas predefclear desprotege todas as variáveis exceto as 7 últimas e também retorna o número antigo e o novo de variáveis protegidas predefn ajusta as maxn7 últimas variáveis definidas como protegidas também retorna o número antigo e o novo de variáveis protegidas Observação Um número de variáveis protegidas está configurado no arquivo de startup inicialização SCI etcscilabstart O usuário pode em particular configurar suas próprias variáveis pre definidas nos arquivos de inicialização do usuário SCIHOMEscilab e SCIHOMEscilabini Definição SCIHOME no Windows CDocuments and SettingsUserScilabScilabVersion No LinuxUnix homeUserScilabScilabVersion Ver Também clear save 101 Name quit Decresce o nível de pausa ou termina o Scilab quit Descrição O comando quit tem dois significados diferentes dependendo do contexto de chamamento Se não houver pause ativo Então o comando quit faz o Scilab terminar mesmo que o comando seja chamado dentro de uma função Se houver pause ativo Então o comando quit aborta instruções iniciadas neste nível de pausa e termina o nível de pausa corrente Exemplos Saindo do Scilab function fooxif x then quitendendfunction foot quits scilab terminando instrução iniciada num contexto de pausa function fooxif x then quitendendfunction pause foot retorna ao nível de prompt principal function foo1x mprintfP1 if x then pause mprintfP2 end mprintfP3 endfunction foo1t enter com quit no prompt seguinte Ver Também pause break abort exit 102 Name quote transpose operator string delimiter Descrição quote aspas é usado para a transposta conjugada de uma matriz quote é usado para a transposta nãoconjugada de uma matriz Aspas simples ou duplas também são usadas para definir strings strings são definidos por aspas nas extremidades Aspas simples dentro de um string são denotadas por duas aspas simples e aspas duplas são denotadas por uma aspas simples e uma dupla Exemplos 1i 2 1i 2 xIsto é um string Ele disse Bom 103 Name rational objeto do Scilab razão de polinômios Descrição Um razão de polinômios r é um quociente entre dois polinômios rnum den A representação interna de uma razão de polinômios é uma lista rtlistrnumdendtnumden é o mesmo que rnumden Uma matriz de razões de polinômios pode ser definida pela sintaxe usual por exem plo r11r12r21r22 ié uma matriz 2x2 onde rij são razões 1x1 Uma ma triz de razões de polinômios também pode ser definida como acima como uma lista tlistrnumdendtnumden com num e den matrizes de polinômios Exemplos spoly0s W1s1s1 WW Numss21sDenssssss tlistrnumdendtNumDen HNumDen syslincNumDen syslincH Num1Den1simpNumDen Ver Também poly syslin simp 104 Name readgateway retorna a lista de primitivas de um módulo readgatewaymodulename primitives readgatewaymodulename primitivesprimitivesID readgatewaymodulename primitivesprimitivesIDgatewayID readgatewaymodulename Descrição Retorna a lista de primitivas de um módulo Primitives lista de primitivas de um módulo primitivesID lista de identificadores das primitivas gatewayID lista de identificadores de portas de ligaçãos associados ao módulo Exemplos primitivesprimitivesIDgatewayID readgatewaycore primitives1 primitiva debug primitive primitivesID1 1 é o ID de debug na porta de ligação de core gatewayID1 13 é o ID da porta de ligação de core no Scilab Ver Também getmodules 105 Name resume retorna ou pára a execução de uma função e copia algumas de suas variáveis locais resume x1xnresumea1an Parâmetros x Descrição Em uma função resume pára a execução da mesma resume pára a execução de uma função e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi No modo pause permite retornar a um nível inferior resume retorna ao nível inferior e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi Em um execstr chamado por uma função resume pára a execução da função e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi resume é equivalente a return Ver Também abort break 106 Name return retorna ou pára a execução de uma função e copia algumas de suas variáveis locais return x1xnreturna1an Parâmetros x Descrição Em uma função return pára a execução da mesma return pára a execução de uma função e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi No modo pause permite retornar a um nível inferior return retorna ao nível inferior e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi Em um execstr chamado por uma função return pára a execução da função e põe as variáveis locais ai no ambiente de chamamento sob os nomes de xi resume é equivalente a return Ver Também abort break 107 Name sciargs scilab command line arguments argssciargs Descrição Esta função retorna um vetor de strings contendo os argumentos da linha de comando do Scilab As primeiras entradas de args contém o endereço do arquivo executável rodado Esta função corresponde a getarg na linguagem C Ver Também getenv 108 Name scilab principal script unix para executar o Scilab e ferramentas de miscelânea scilab Options Descrição args Arguments Se esta opção estiver presente os argumentos são passados ao Scilab Eles podem ser recebidos pela função sciargs para passagem de múltiplos argumentos use seqüências de palavras separadas por espaços entre aspas simples scilab args foo1 foo2 display Display Para uso apenas em sistemas Xwindow para ajustar um display de servidor X O display padrão é unix00 display pode ser abreviado por d debug Inicia o Scilab no debugger gdb apenas para Unixlinux e Instrução Se esta opção estiver presente então a instrução Scilab Instrução é executada primeiro logo após a execução do arquivo de inicialização no Scilab As opções e e f são mutuamente exclusivas f arquivo Se esta opção estiver presente então o script Scilab arquivo é executado primeiro logo após a execução do arquivo de inicialização no Scilab As opções e e f são mutuamente exclusivas l idioma Se esta opção estiver presente ela fica o idioma do usuário Os possíveis valores para idioma são fr para francês en para inglês e br para português brasileiro O idioma padrão é inglês O valor padrão é fixado no arquivo scilabstart mem N Ajusta o tamanho de pilha inicial para uso com a opção ns Sem a opção ns a pilha inicial é ajustada pelo script scilabstart nb Se esta opção está presente então o cartão de boasvindas não é impresso ns Se esta opção está presente o arquivo de inicialização SCIetcscilabstart e os arquiv os de inicialização do usuário SCIHOMEscilab SCIHOMEscilabini não são execu tados nouserstartup Se esta opção estiver presente os arquivos de inicialização do usuário SCIHOMEscilab SCIHOMEscilabini não são executados nw Se esta opção estiver presente então o Scilab não é executado em uma janela específica nwni Se esta opção estiver presente então o Scilab não é executado em uma janela específica e não aceita interação do usuário Esta opção pode ser utilizada com as opções f ou e scilab 109 texmacs Esta opção é reservada para TexMacs version Esta opção imprime a versão do produto e sai 110 Name select Palavrachave da estrutura select significa selecionar de acordo com a variável Descrição select expressão case expressão1 then instruções1 case expressão2 then instruções2 case expressãon then instruçõesn else instruções end Notas A única restrição é de que a palavrachave then deve estar na mesma linha que a palavrachave case correspondente A palavrachave then pode ser substituída por uma vírgula ou um retorno de carro instruçõesi são executadas se expressãoiexpressão Aviso o número de caracteres usados para definir o corpo de qualquer instrução condicional if while for ou selectcase deve ser limitado a 16k Exemplos while t do nround10rand11 select n case 0 then disp0 case 1 then disp1 else break end end Ver Também if while for 111 Name semicolon fim de expressão e separador de linhas Descrição Pontosevírgulas são usados para separar linhas em uma definição de matrizes Pontosevírgulas também podem ser usados para indicar o fim de uma instrução Neste caso indica que os resultados não serão exibidos Se desejar exibição use vírgula Exemplos a123456 a1b1c2 Ver Também comma brackets 112 Name setbpt ajusta pontos de parada setbptmacroname linenumb Parâmetros macroname string linenumb escalar inteiro ou vetor de escalares Descrição setbpt insere interativamente um ponto de parada na linha de número linenumb valor padrão é 1 da função macroname linenumb pode ser um vetor linha ou coluna dos números das linhas ou um único número de linha escalar Quando alcança o ponto de parada o Scilab avalia a linha especificada imprime o número da linha e da função Se a função não for compilada see comp a linha é exibida na tela Então o Scilab entra em modo pause no qual o usuário pode verificar os valores correntes O pause é cancelado com resume ou abort Redefinir a função não limpa pontos de parada o usuário deve deletar os pontos de parada explicitamente usando delbpt O número máximo de funções com pontos de parada habilitados deve ser menor que 100 e o número máximo de pontos de parada é 1000 Exemplos setbptfoosetbptfoo10dispbpt delbpt setbptfoo1256dispbpt Ver Também delbpt dispbpt pause resume 113 Name sethomedirectory ajusta o diretório home do Scilab homescilabhome sethomedirectory Descrição Ajusta o endereço hom do Scilab variável SCIHOME No Windows 2k e XP CDocuments and SettingsUserScilabScilabVersion No Windows Vista CUsersUserScilabScilabVersion No Unix homeUserScilabScilabVersion Autor Allan CORNET 114 Name slash divisão esquerdadireita e feedback resposta Descrição Divisão esquerdadireita xA b é a solução de xbA ba a b a b é a matriz com entradas aij bij Se b é escalar matriz 1x1 esta operação é o mesmo que abonesa mesma convenção se a é um escalar Observe que 123b é interpretado como 123b Nestes casos o ponto é parte do número não do operador significa divisão direitaesquerda Feedback de sistema SGK avalia SGeyeKG1 Este operador evita o problema de simplificação Observe que G5 é interpretado como G5 Em tais casos o ponto é parte do número não do operador Comentário comenta uma linha ie linhas que começam por são ignoradas pelo interpretador Ver Também inv percent backslash ieee 115 Name stacksize ajusta tamanho da pilha do Scilab stacksizen stacksizemax stacksizemin szstacksize Parâmetros n inteiro o tamanho da pilha requerido dado em número de palavras de dupla precisão sz vetor de duas entradas total used Descrição O Scilab armazena variáveis usuais em uma pilha stk para variáveis globais ver gstacksize stacksizen permite aumentar ou diminuir o tamanho desta pilha O máximo permitido depende da quantidade de memória livre e do espaço de troca swap space disponível no momento stacksizemax permite ao usuário aumentar o tamanho dessa pilha ao máximo stacksizemin permite ao usuário diminuir o tamanho dessa pilha ao mínimo Esta função com o argumento n pode ser usada em qualquer lugar szstacksize retorna um vetor de duas entradas que contém os tamanhos correntes de pilha total e usado Ver Também who gstacksize 116 Name star operador de multiplicação Descrição Multiplicação no sentido usual Válido para matrizes de contrantes valores booleanos polinômios ou razões de polinômios e para listas syslin o significado é de conexão de série A multiplicação elemento a elemento é denotada por xy Se x ou y é escalar matriz 1x1 é o mesmo que O produto de Kronecker é denotado por xy AB é um operador sem significado predefinido Pode ser usado para definir um novo operador ver overloading com a mesma precedência que ou Ver Também slash backslash syslin 117 Name startup arquivo de inicialização Descrição O arquivo de inicialização SCIHOMEscilab e SCIHOMEscilabini são automaticamente executados se estiverem presentes quando o Scilab é chamado junto com o arquivo scilabstar no diretório Scilab SCI Observações A última linha de um arquivo de inicialização deve ser terminada por uma nova linha a ser levada em conta Definição de SCIHOME no Windows CDocuments e SettingsUserScilabScilabVersion ou no Vista CUserAppDataRoamingScilabScilabVersion No LinuxUnix homeUserScilabScilabVersion Ver Também scilab 118 Name symbols nomes dos operadores Scilab Descrição Use os nomes seguintes para obter ajuda em um símbolo específico operator nome na ajuda do Scilab quote aspas plus sinal de mais minus sinal de menos star estrela asterísco slash barra backslash barra invertida dot ponto equal igual less desigualdades tilda til left colchete esquerdo right colchete direito parents parênteses percent colon doispontos comma vírgula semi pontoevírgula hat chapéu circunflexo power potência or barra vertical ou lógico and e comercial e lógico kron produto de Kronecker Observações Por razões históricas símbolos diferentes podem representar o mesmo operador tem o mesmo significado que tem o mesmo significado que tem o mesmo significado que tem o mesmo significado que É altamente recomendável que não se use esses recursos pois eles serão removidos futuramente Ver Também overloading 119 Name testmatrix gera algumas matrizes particulares ytestmatrixnamen Parâmetros name um string n inteiros tamanho da matriz y matriz n x m Descrição Cria algumas matrizes particulares testmatrixmagin retorna um quadrado mágico de tamanho n testmatrixfrkn retorna a matriz de Franck testmatrixhilbn é a matriz inversa da matriz n x n de Hilbert Hij 1ij1 120 Name then Palavrachave usada na estrutura ifthenelse significa então Descrição Usado com if Ver Também if 121 Name tilda não lógico m Parâmetros m matriz de valores booleanos Descrição m é a negação de m 122 Name try início de um bloco try numa instrução de controle trycatch significa tentar catch início de um bloco catch numa instrução de controle trycatch significa prender try statements catch statements end Descrição A instrução de controle trycatchpode ser usada para gerenciar códigos que possivelmente pode riam gerar erros Quando uma instrução de controle trycatch é executada normalmente apenas as sentenças entre as palavraschaves try e catchsão executadas Contudo se um erro ocorre durante a execução de uma dessas sentenças o erro é registrado as sentenças restantes até catchsão puladas e as sentenças entre as palavraschaves catch e end são executadas usandose o modo de manipulação de erros padrão ver errcatch A mensagem de erro registrada pode ser recuperada pela função lasterror As sentenças catch tanto quanto a palavrachave catch podem ser omitidas se nenhuma sentença alternativa for fornecida Note que também é possível utilizar a função execstr com o argumento errcatch para manipulação de erros Isto pode ser particularmente útil para manipulação de erros sintáticos Exemplos filepathTMPDIRwrong try umopenfilepathr xmget10cu catch dispo arquivo filepath não pode ser lido usando valores padrões para x x110 end errormessageerrornumberlasterrort Ver Também error execstr if lasterror errcatch Autor Serge Steer INRIA 123 Name type tipo de variável itypex Parâmetros x objeto Scilab i inteiro Descrição typexretorna um inteiro que indica o tipo de x como segue 1 uma matriz constante de reais ou complexos 2 uma matriz de polinômios 4 uma matriz de valores booleanos 5 uma matriz esparsa 6 uma matriz de valores booleanos esparsa 7 uma matriz esparsa do Matlab 8 uma matriz de inteiros armazenados em 1 2 ou 4 bytes 9 uma matriz de manipuladores gráficos 10 uma matriz de strings 11 uma função nãocompilada código Scilab 13 uma função compilada código Scilab 14 uma biblioteca de funções 15 uma lista 16 uma lista com tipo typed list ou tlist 17 uma lista com tipo orientada matricialmente mlist 128 um ponteiro ver lufact 129 polinômio de tamanho implícito usado para indexação 130 intrínseco do Scilab código C ou Fortran Ver Também typeof 124 Name typename associa um nome ao tipo de variável types namestypename typenamenametype Parameters types vetor coluna de inteiros os códigos dos tipos de cada tipo de dado definido names vetor coluna de strings os nomes associados aos códigos de tipos type inteiro o código de tipo do novo tipo de dado name string o nome associado ao código de tipo Descrição O overloading de funções e operadores faz uso de nomes formais associados aos tipos de dados para formar o nome da função de overloading ver overloading typename pode ser usado para manipular esses nomes formais para tipos de dados hardcoded os nomes formais de tipos de dados codificados de tlist ou mlist são definidos de outra forma ver overloading Chamado sem argumento do lado direito typename retorna informações sobre tipos de dados definidos Chamado com argumento do lado direito typename associa um nome a um código de tipo de dado typenametype suprime o tipo de dado fornecido pelo seu código type de tabelas de tipos de dados conhecidos Number max of defined types is 50 Ver Também type typeof overloading tlist mlist 125 Name user interface para rotinas FORTRAN ou C s1s2slhsusere1e2erhs Descrição Com este comando é possível utilizar um programa externo como um comando do Scilab onde s1s2slhs são as variáveis de saída e e1e2erhs asão as variáveis de entrada Para inserir este comando no Scilab é necessário escrever algumas linhas na subrotina FORTRAN user do Scilab Ver intersci ou a documentação do Scilab para mais Ver Também fort link 126 Name varn variável simbólica de um polinômio symbvarnp pmvarnxvar Parâmetros p polinômio matriz de polinômios symb string x polinômio ou matriz de polinômios var variável simbólica string pm matriz ou matriz de polinômios Descrição symbvarnp retorna em symb a variável simbólica de p ie varnpoly0x is x varnxs retorna uma matriz de polinômios com os mesmos coeficientes que x mas com s como variável simbólica mudança do nome de variável Exemplos spoly0sps21s varnp varnpx Ver Também horner poly 127 Name ver informação de versão sobre Scilab r ver Parâmetros r uma matriz de strings Descrição Informação de versão sobre o Scilab Retorna uma matriz de strings com informações de versão sobre o Scilab Exemplos ver Autor AC 128 Name warning mensagens de aviso warningstring warningoff warningon mode warningquery Descrição Imprime o string string em uma mensagem de aviso on habilita mensagens de aviso off desabilita mensagens de aviso query retorna o estado on ou off Exemplos warningon warningeste é um aviso warningoff warningeste é um aviso warningquery warningon Ver Também error 129 Name what lista de primitivas do Scilab what primitivescommandswhat Descrição Lista de comandos e primitivas de nível baixo Autor AC 130 Name where retorna a árvore de chamamento de instruções corrente linenummacwhere Parâmetros linenum vetor coluna de inteiros mac vetor coluna de strings Descrição Retorna linenum e mac tais que a instrução corrente foi chamada pela linha linenum1 da função mac1 mac1 foi chamada pela linha linenum2 da função mac2 e assim por diante maci é em geral o nome de uma função mas também pode ser exec ou execstr se a instrução reside em um arquivo executável ou em uma instrução execstr Ver Também whereami pause 131 Name whereami exibe a árvore de chamamento de instruções corrente whereami Descrição Exibe a árvore de chamamento para a instrução que contém whereami Pode ser usado dentro de níveis de pause pausa Exemplos deffytestaysina1 yt1y yy1 deffyt1yyy2whereami test1 Ver Também where pause errcatch 132 Name while palavrachave da estrutura while significa enquanto Descrição while Deve ser terminado por end while expressão instruções1else instruções end while expressão do instruções1else instruções end while expressão then instruções1else instruções end Notas A única restrição é que cada palavrachave then ou do deve estar na mesma linha que a palavra chave while As palavraschaves then ou do podem ser substituídas por um retorno de carro ou uma vírgula Para compatibilidade com o Matlab também é possível mas não recomendado por um espaço entre o fim da expressão e o início da primeira instrução A construção opcional else instruções permite fornecer instruções que são executadas quando a expressão expressão tornase falsa Aviso o número de caracateres usados para definir o corpo de qualquer estrutura condicional if while for ou selectcase deve ser limitado a 16k Exemplos e1 a1 k1 while normaae1 eps ee2 kk1 end ek Ver Também for select break return pause 133 Name who listagem de variáveis who who nameswholocal namesmemwholocal nameswhoglobal namesmemwhoglobal whosorted nameswholocalsorted namesmemwholocalsorted nameswhoglobalsorted namesmemwhoglobalsorted Descrição who exibe os nome de variáveis correntes wholocal ou whoget retorna os nomes de variáveis correntes e a memória utilizada em palavras de dupla precisão whoglobal retorna os nomes de variáveis globais e a memória utilizada em palavras de dupla precisão whosorted exibe todas as variáveis em ordem alfabética Ver Também whos whouser 134 Name whouser listagem das variáveis do usuário whouser Descrição whouser exibe os nomes das variáveis do usuário Ver Também whos who 135 Name whos listing of variables in long form whos whos type typ whos name nam Parâmetros typ nome do tipo da variável selecionada ver typeof nam os primeiros caracteres dos nomes selecionados Descrição whos exibe todos os nomes de variáveis correntes bem como seus tipos e memória utilizada whos type typ exibe todas as variáveis correntes com o tipo especificado whos name nam exibe todas as variáveis cujos nomes começam com nam Nota se uma variável é global um aparece em frente ao seu tipo Exemplos lines0 whos whos type boolean whos name Ver Também who typeof 136 Name withatlas Checa se o Scilab foi construído com a biblioteca Atlas rwithatlas Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido construído com a biblioteca Atlas ou f senão 137 Name withgtk Checa se o Scilab foi contstruído com a biblioteca GIMP Toolkit rwithgtk Parameters r um booleano Description Sempre retorna f a biblioteca gtk não é mais suportada pelas versões 5 em diante 138 Name withjavasci Checa se o Scilab foi construído com a interface java rwithjavasci Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido construído com a interface java ou f senão 139 Name withmacrossource Verifica se a fonte de macros está instalada rwithmacrossource Parâmetros r um booleano Descrição Retorna t se a fonte de macros está instalada ou f senão 140 Name withmodule checa se um módulo Scilab foi instalado rwithmodulemodulename Parâmetros r um booleano modulename um string Exemplo core Descrição Retorna t se o módulo Scilab tiver sido instalado Ver Também getmodules Autor AC 141 Name withpvm Checa se o Scilab foi construído com a interface Parallel Virtual Machine rwithpvm Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido construído com a interface Parallel Virtual Machine ou f senão 142 Name withtexmacs checa se o Scilab foi chamado por TeXmacs rwithtexmacs Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido chamado por TeXmacs 143 Name withtk checa se o Scilab foi construído com TCLTK rwithtk Parâmetros r um booleano Descrição Retorna t se o Scilab tiver sido construído com a interface TCLTK ou f se não Parte II Equações Diferenciais 145 Name dae Solucionador de equações diferenciais algébricas ydaeinitialt0tres y hddaeinitialt0t rtol atolres jac hd yrddaerootinitialt0tresngsurface y rd hddaerootinitialt0t rtol atolres jac ng surface hd Parâmetros initial um vetor coluna Pode ser igual a x0 or x0xdot0 onde x0 é o valor de estado no tempo inicial t0 e ydot0 é o valor da derivada do estado inicial ou uma estimativa dela ver abaixo t0 número real o tempo inicial t escalar real ou vetor Fornece instantes para os quais você deseja uma solução Note que você pode obter soluções para cada ponto de passo de dae fazendo DAEOPTIONS21 rtol escalar real ou vetor coluna com o mesmo tamanho que x0 A tolerância do erro relativo da solução Se rtol for um vetor as tolerâncias são especificadas para cada componente do estado atol escalar real ou vetor coluna com o mesmo tamanho que x0 A tolerância do erro absoluto da solução Se atol for um vetor as tolerâncias são especificadas para cada componente do estado res uma função externa external Computa o valor de gtyydot Pode ser Uma função do Scilab Neste caso a sua seqüência de chamamento pode ser riresrestxxdot e res deve retornar o resíduo rgtxxdot e o indicador de erro ires ires 0 se res obtiver sucesso ao computar r 1 se o resíduo é indefinido localmente para txxdot 2 se os parâmetros estão fora do intervalo admissível Uma lista Esta forma é utilizada para passar parâmetros à função Deve ser como segue listresp1p2 Onde a seqüência de chamamento da função res é agora rrestyydotp1p2 res ainda retorna o valor residual como uma função de txxdotx1x2 e p1p2 são parâmetros da função Um string Deve se referir ao nome subrotina C ou Fortran Supondo que rname ié o nome dado A seqüência de chamamento em Fortran deve ser dae 146 rnametxxdotresiresrparipar double precision txxdotresrpar integer iresipar A seqüência de chamamento em C deve ser C2Frnamedouble t double x double xdot double res integer ires double rpar integer ipar onde t é o valor de tempo corrente x é o array de estados xdot é o array das derivadas dos estados res é o array de resíduos ires é o indicador de execução rpar é o array de valores de parâmetros em ponto flutuante necessário mas não pode ser definido pela função dae ipar é o array de valores de parâmetros inteiros necessário mas não pode ser definido pela função dae jac uma função externa external Computa o valor de dgdxcjdgdxdot para um dado valor do parâmetro cj Pode ser Uma função do Scilab Sua seqüência de chamamento deve ser rjactxxdotcj e a função jac deve re tornar rdgtxxdotdycjdgtxxdotdxdot onde cj é um escalar real Uma lista Esta forma é utilizada para passar parâmetros à função Deve ser como segue listjacp1p2 Onde a seqüência de chamamento da função jac é agora rjactxxdotp1p2 jac ainda retorna dgdxcjdgdxdot como uma função de txxdotcjp1p2 Um string Deve se referir ao nome de uma subrotina C ou Fortran Supondo que jname é o nome dado A seqüência de chamamento em Fortran deve ser jnamet x xdot r cj ires rpar ipar dae 147 double precision t x xdot r ci rpar integer ires ipar A seqüência de chamamento dem C deve ser C2Fjnamedouble t double x double xdot double r double cj integer ires double rpar integer ipar onde t x xdot ires rpar ipar são definidas semelhantemente como acima r é o array de resultados surface uma função externa external Computa o valor de cada vetor coluna surfacetx como componentes ng Cada componente define uma superfície Uma função do Scilab Sua seqüência de chamamento deve ser rsurfacetx esta função deve retornar um vetor com ng elementos Uma lista Esta forma é utilizada para passar parâmetros à função Deve ser como segue listsurfacep1p2 Onde a seqüência de chamamento da função surface é agora rsurfacetxp1p2 String Deve se referir ao nome de uma rotina C ou Fortran Supondo que sname é o nom dado A seqüência de chamamento em Fortran deve ser rnamenx t x ng r rpar ipar double precision t x r rpar integer nx ngipar A seqüência de chamamento em C deve ser C2Frnamedouble t double x double xdot double r double cj integer ires double rpar integer ipar onde t x rpar ipar são definidas semelhantemente como acima ng é o número de superfícies nx é a dimensão do estado e r é o array de resultados rd um vetor com duas entradas times num times é o valor do tempo no qual a superfície é cruzada num é o número da superfície cruzada hd um vetor de reais que permite armazenar o contexto de dae Pode ser utilizado como argumento de entrada para retomar a integração recomeço rápido dae 148 y matriz de reais Se DAEOPTIONS21 cada coluna é o vetor txtxdott onde t é o índice do tempo para o qual a solução foi computada De outro modo y é o vetor xtxdott Descrição A função dae é uma porta construída sobre as funções dassl e dasrt designada para equações difer enciais implícitas gtxxdot0 xt0x0 e xdott0xdot0 Se xdot0 não for fornecido no argumento initial a função dae tenta computálo resolvendo gtx0xdot00 Se xdot0 for fornecido no argumento initial pode ser tanto uma derivada compatível satis fazendo gtx0xdot00 ou um valor aproximado No último caso DAEOPTIONS7 deve ser ajustado para 1 Exemplos detalhados utilizando funções externas codificadas em C e Fortran são dados em mod ulesdifferentialequationstestsunittestsdassldasrttst Exemplos Exemplo com um código Scilab function rireschemrestyyd r1 004y1 1d4y2y3 yd1 r2 004y1 1d4y2y3 3d7y2y2 yd2 r3 y1 y2 y31 ires 0 endfunction function pdchemjacxyydcj pd004cj 1d4y3 1d4y2 004 1d4y323d7y2cj 1d4y2 1 1 1 endfunction x01 0 0 xd0004 004 0 t1d50024 04114 40 400 4000 40000 4d5 4d6 4d7 4d8 4d9 4d10 ydaex0xd00tchemres retorna os pontos de observação requisitados DAEOPTIONSlist100 pede que a malha de dae seja retornada ydaex0xd004d10chemres sem jacobiano ydaex0xd004d10chemreschemjac com jacobiano exemplo com um código C requerse um compilador C 1 criando os códigos C em TMPDIR equação de Vanderpol forma implícita codeinclude ltmathhgt void res22double tdouble ydouble yddouble resint iresdouble rparint ipar res0 yd0 y1 res1 yd1 100010 y0y0y1 y0 dae 149 void jac22double tdouble ydouble yddouble pddouble cjdouble rparint ipar pd0cj 00 pd1 2000y0y1 10 pd2 10 pd3cj 100010 y0y0 void gr22int neq double t double y int ng double groot double rpar int ipar groot0 y0 mputlcodeTMPDIRt22c 2 compilando e carregando ilibforlinkres22 jac22 gr22t22ccTMPDIRMakefileTMPDIRt22loadersce execTMPDIRt22loadersce 3 executando rtol1d61d6atol1d61d4 t00y020y0d02t2020200ng1 simulação simples t00003300 yydaey0y0dt0tatolrtolres22jac22 clfplotyy1yy2 achando o primeiro ponto onde yy10 yynnhotddaerooty0y0dt0300atolrtolres22jac22nggr22 plotyy11yy21r xstringyy1101yy21stringnn1 recomeço rápido para o próximo ponto t01nn1ppqqsizeyyy01yy23qqy0d1yy34qq yynnhotddaerooty01y0d1t01300atolrtolres22jac22nggr22hotd plotyy11yy21r xstringyy1101yy21stringnn1 Ver Também ode daeoptions dassl impl fort link external 150 Name daeoptions ajusta opções para o solucionador de equações diferenciais algébricas daeoptions Descrição Se no contexto do chamamento da função dae existe a variável DAEOPTIONS a função dae a utiliza para ajustar suas opções A função daeoptions exibe interativamente um comando que deveria ser executado para se ajustar diversas opções do solucionador dae CUIDADO a função dae verifica se esta variável existe e neste caso a utiliza Para utilizar valores padrões você deve limpar esta variável Note que daeoptions não cria esta variável Para criála você deve executar a linha de comando exibida por daeoptions A variável DAEOPTIONS é uma lista list com os seguintes elementos listtstopimodebandmaxstepstepinnonnegisest O valor padrão é list000 Os siginificados destes elementos são listados abaixo tstop um escalar real ou uma matriz fornece o tempo máximo para o qual se permite a avaliação de g Uma matriz vazia significa que não há limites impostos pelo tempo imode Se for 0 dae retorna apenas os valores de pontos do tempo especificado pelo usuário Se for 1 dae retorna seus valores intermediários computados band um vetor de dois componentes que fornece a definição mlmu da matriz de bandas computada por jac ri j ml mu 1j dgidyjcjdgidydotj Se jac retorna uma matriz completa ajustado band maxstep um escalar ou matriz vazia o tamanho máximo do passo Uma matriz vazia indica ausência de limitiação stepin um escalar ou matriz vazia o tamanho mínimo do passo Uma matriz vazia indica não especi ficado nonneg um escalar deve ser ajustado para 0 se a solução se conhece ser não negativa E caso contrário deve ser ajustado para 1 daeoptions 151 isest A scalar deve ser ajustado para 0 se a dada condição inicial é compatível gt0x0xdot00 Deve ser ajustado para 1 se xdot0 é apenas uma estimativa Ver Também dae 152 Name dasrt Solucionador de equações diferenciais algébricas com cruzamento de zeros rnnhddasrtx0t0t atolrtolres jacng surf info hd Parâmetros x0 pode ser tanto y0 ydot0 é estimado por dassl com a primeira estimativa sendo 0 ou a matriz y0 ydot0 gty0ydot0 deve ser igual a zero Se você conhece apenas uma estimativa de ydot0 faça info71 y0 vetor coluna de reais de condições iniciais ydot0 vetor coluna de reais da derivada do tempo de y em t0 pode ser uma estimativa t0 número real é o instante inicial t escalar real ou vetor Fornece instantes para os quais você deseja uma solução Note que você pode obter soluções para cada ponto de passo de dassl fazendo info21 nn um vetor com duas entradas times num times é o valor do tempo no qual a superfície é cruzada num é o número da superfície cruzada atolrtol escalares reais ou vetores colunas com o mesmo tamanho que y atolrtol fornecem respec tivamente as tolerâncias de erros absolutos e relativos da solução Se forem vetores as tolerâncias são especificadas para cada elemento de y res função lista ou string externos Computa o valor de gtyydotPode ser Uma função do Scilab Sua seqüência de chamamento pode ser riresrestyydot e res e deve retornar o resíduo rgtyydot e o indicador de erro ires ires 0 se res obtiver suces so ao computar r 1 se o resíduo é indefinido localmente para tyydot 2 se os parâmetros estão fora do intervalo admissível Uma lista Esta forma permite passar outros parâmetros além de tyydot à função Deve ser como segue listresx1x2 Onde a seqüência de chamamento da função res é agora rrestyydotx1x2 res ainda retorna rgtyydot como função de tyydotx1x2 Warning this form must not be used if there is no extra argument to pass to the function dasrt 153 Um string Deve se referir ao nome subrotina C ou Fortran ligada ao Scilab Em C a seqüência de chamamento void resdouble t double y double yd double r int ires double rpar int ipar Em Fortran deve ser subroutine restyydriresrparipar double precision t yydrrpar integer iresipar Os arrays rpar e ipar devem estar presentes mas não podem ser utilizados jac função lista ou string externos Computa o valor de dgdycjdgdydot para um dado valor do parâmetro cj Uma função do Scilab Sua seqüência de chamamento deve ser rjactyydotcj e a função jac deve re tornar rdgtyydotdycjdgtyydotdydot onde cj é um escalar real Uma lista Deve ser como segue listjacx1x2 Onde a seqüência de chamamento da função jac é agora rjactyydotcjx1x2 jac ainda retorna dgdycjdgdydot como uma função de tyydotcjx1x2 Um string Deve se referir ao nome de uma subrotina C ou Fortran ligada ao Scilab Em C a seqüência de chamamento deve ser void jacdouble t double y double yd double pd double cj double rpar int ipar Em Fortran deve ser subroutine jactyydpdcjrparipar double precision t yydpdcjrpar dasrt 154 integer ipar surf função lista ou string externo Computa o valor do vetor coluna surfty com componentes ng Cada componente define uma superfície Pode ser definido por Uma função Scilab Sua seqüência de chamamento deve ser surfty Uma lista Deve ser como segue listsurfx1x2 onde a seqüência de chamamento surf é agora rsurftyx1x2 Um string Deve se referir ao nome de uma subrotina C ou Fortran ligada ao Scilab Em C a seqüência de chamamento deve ser void surfint ny double t double y int ng double gout Em Fortran deve ser subroutine surfnytynggout double precision t ygout integer nyng info lista que contém 7 elementos o valor padrão é list000 info1 escalar real que fornece o tempo máximo para o qual se permite avaliar g ou uma matriz vazia se não houver limites impostos sobre o tempo info2 indica se dassl retorna seus valores intermediários computados flag1 ou apenas os valores de pontos tempo especificados pelo usuário flag0 info3 vetor de dois componentes que fornece a definição mlmu de matriz de bandas computa da por jac ri j ml mu 1j dgidyjcjdgi dydotj Se jac retorna uma matriz cheia faça info3 info4 escalar real que fornece o tamanho de passo máximo Faça info4 se não houver limitação dasrt 155 info5 escalar real que fornece o passo inicial Faça info5 se não for especificado info6 faça info61 caso se saiba que a soulução não é negativa em outro caso ajuste in fo60 info7 faça info71 se ydot0 é apenas uma estimativa info70 se gt0y0ydot00 hd vetor de reais que permite armazenar o contexto de dassl e retomar integração r matriz de reais Cada coluna é o vetor txtxdott onde t é o índice do tempo para o qual a solução foi computada Descrição Solução da equação diferencial implícita gtyydot0 yt0y0 e ydott0ydot0 Retorna os instantes de cruzamento da superfície e o número da superfície alcançada em nn Exemplos detalhados podem ser encontrados em SCIDIRtestsdassldasrttst Exemplos dydt 2logy8t 5y y1 1 1lttlt6 g1 2logy8t 5y g2 logy 22491 y01t26t01y0d3 atol1d6rtol0ng2 deffdeltairesres1tyydotires0deltaydot2logy8t5y deffrtsgr1tyrts2logy8t5ylogy22491 yynndasrty0y0dt0tatolrtolres1nggr1 Deveria retornar nn24698972 2 Ver Também ode dassl impl fort link external 156 Name dassl Equação diferencial algébrica r hddasslx0t0t atolrtolres jac info hd Parâmetros x0 pode ser tanto y0 ydot0 é estimado por dassl com a primeira estimativa sendo 0 ou a matriz y0 ydot0 gty0ydot0 deve ser igual a zero Se você conhece apenas uma estimativa de ydot0 faça info71 y0 vetor coluna de reais de condições iniciais ydot0 vetor coluna de reais da derivada do tempo de y em t0 pode ser uma estimativa t0 número real é o instante inicial t escalar real ou vetor Fornece instantes para os quais você deseja uma solução Note que você pode obter soluções para cada ponto de passo de dassl fazendo info21 atolrtol escalares reais ou vetores colunas com o mesmo tamanho que y atolrtol fornecem respec tivamente as tolerâncias de erros absolutos e relativos da solução Se forem vetores as tolerâncias são especificadas para cada elemento de y res função lista ou string externos Computa o valor de gtyydot Pode ser Uma função do Scilab Sua seqüência de chamamento pode ser riresrestyydot e res deve retornar o resíduo rgtyydot e o indicador de erro ires ires 0 se res obtiver suces so ao computar r 1 se o resíduo é indefinido localmente para tyydot 2 se os parâmetros estão fora do intervalo admissível Uma lista Esta forma permite passar outros parâmetros além de tyydot à função Deve ser como segue listresx1x2 Onde a seqüência de chamamento da função res é agora rrestyydotx1x2 res ainda retorna rgtyydot como função de tyydotx1x2 Um string Deve se referir ao nome subrotina C ou Fortran ligada ao Scilab dassl 157 Em C a seqüência de chamamento void resdouble t double y double yd double r int ires double rpar int ipar Em Fortran deve ser subroutine restyydriresrparipar double precision t yydrrpar integer iresipar Os arrays rpar e ipar devem estar presentes mas não podem ser utilizados jac função lista ou string externos Computa o valor de dgdycjdgdydot para um dado valor do parâmetro cj Uma função do Scilab Sua seqüência de chamamento deve ser rjactyydotcj e a função jac deve re tornar rdgtyydotdycjdgtyydotdydot onde cj é um escalar real Uma lista Deve ser como segue listjacx1x2 Onde a seqüência de chamamento da função jac é agora rjactyydotcjx1x2 jac ainda retorna dgdycjdgdydot como uma função de tyydotcjx1x2 Um string Deve se referir ao nome de uma subrotina C ou Fortran ligada ao Scilab Em C a seqüência de chamamento deve ser void jacdouble t double y double yd double pd double cj double rpar int ipar Em Fortran deve ser subroutine jactyydpdcjrparipar double precision t yydpdcjrpar integer ipar dassl 158 info lista opcional que contém 7 elementos O valor padrão é list000 info1 escalar real que fornece o tempo máximo para o qual se permite avaliar g ou uma matriz vazia se não houver limites impostos sobre o tempo info2 indica se dassl retorna seus valores intermediários computados flag1 ou apenas os valores de pontos tempo especificados pelo usuário flag0 info3 vetor de dois componentes que fornece a definição mlmu de matriz de bandas computa da por jac ri j ml mu 1j dgidyjcjdgi dydotj Se jac retorna uma matriz cheia faça info3 info4 escalar real que fornece o tamanho de passo máximo Faça info4 se não houver limitação info5 escalar real que fornece o passo inicial Faça info5 se não for especificado info6 faça info61 caso se saiba que a soulução não é negativa em outro caso ajuste in fo60 info7 faça info71 se ydot0 é apenas uma estimativa info70 se gt0y0ydot00 hd vetor de reais que permite armazenar o contexto de dassl e retomar integração r matriz de reais Cada coluna é o vetor txtxdott onde t é o índice do tempo para o qual a solução foi computada Descrição A função dassl integra a equação alegébricadiferencial e retorna a evolução de y em pontos de tempo dados gtyydot0 yt0y0 e ydott0ydot0 Exemplos function rireschemrestyyd r004y11d4y2y3yd1 004y11d4y2y33d7y2y2yd2 y1y2y31 ires0 endfunction function pdchemjacxyydcj pd004cj 1d4y3 1d4y2 004 1d4y323d7y2cj 1d4y2 1 1 1 dassl 159 endfunction y0100 yd00040040 t1d5002404114404004000400004d54d64d74d84d94d10 ydassly0yd00tchemres infolist000 info21 ydassly0yd004d10chemresinfo ydassly0yd004d10chemreschemjacinfo utilizando um argumento extra para parâmetros function rireschemrestyyd abc ray1by2y3yd1 ay1by2y3cy2y2yd2 y1y2y31 ires0 endfunction function pdchemjacxyydcj abc pdacj by3 by2 a by32cy2cj by2 1 1 1 endfunction ydassly0yd00tlistchemres0041d43d7listchemjac0041d43d7 utilizando código c criando o código C rescodevoid chemresdouble t double y double yd double r int ires double rpar int ipar r0 004y010e4y1y2 yd0 r1 004y010e4y1y230e7y1y1yd1 r2 y0y1y21 ires 0 jaccodevoid chemjacdouble t double y double yd double pd double cj double rpar int ipar primeira coluna pd0 004cj pd1 004 pd2 10 segunda coluna pd3 10e4y2 pd4 10e4y2230e7y1cj pd5 10 terceira coluna pd6 10e4y1 pd7 10e4y1 pd8 10 mputlrescodejaccodeTMPDIRmycodec create the C file compilandoo ilibforlinkchemreschemjacmycodeccTMPDIRMakefileTMPDIRloaderscecompilando dassl 160 ligandoo com o Scilab execTMPDIRloadersce linking incremental chamada a dassl ydassly0yd00tchemreschemjac Ver Também ode dasrt impl fort link external 161 Name feval múltipla avaliação zfevalxyf zfevalxf Parâmetros xy dois vetores f função ou string para chamada FORTRAN ou C Descrição Múltipla avaliação de uma função para um ou dois argumentos do tipo vetor zfevalxf retorna o vetor z definido por zifxi zfevalxyf retorna a matriz z tal que zijfxiyj f é uma external função ou rotina que aceita dois ou mais argumentos supostos reais O re sultado retornado por f pode ser real ou complexo No caso de uma chamada FORTRAN a função f deve ser definida na subrotina fevaltablec no diretório SCImod ulesdifferentialequationssrcc Exemplos deffzfxyzx2y2 feval11015f deffzfxyzxiy feval11015f feval11015parab See ffevalf file feval110parab Para link dinâmico ver exemplo ftest em ffevalf você pode usar o comando link os parâmetros dependem da máquina unixmake ftestolinkftestfftest feval11015ftest Ver Também evstr horner execstr external link 162 Name impl equações diferenciais algébricas yimpltypey0ydot0t0t atol rtolresadda jac Parâmetros y0ydot0 vetor de reais ou matriz condições iniciais t0 escalar real tempo inicial t vetor de reais tempos nos quais a solução é computada resadda funções externas função strting ou lista type string adams ou stiff atolrtol escalar real ou vetor de reais com as mesmas dimensões que y jac função externa função string ou lista Descrição Solução da equação diferencial linear implicita Aty dydtgty yt0y0 t0 é o instante inicial y0 é o vetor de condições iniciais O vetor ydot0 da derivada em relação ao tempo y em t0 também deve ser dado A entrada res é uma função externa ie uma função com sintaxe especificada ou o nome da subrotina FORTRAN ou da função C string com seqüência de chamamento especificada ou uma lista Se res for uma função a sintaxe deve ser como segue r restyydot onde t é um escalar real tempo e y e ydot são vetores de reais estado e derivada do estado Esta função deve retornar rgtyAtyydot Se res for um string ele se refere a uma subrotina FORTRAN ou uma função C Ver SCImod ulesdifferentialequationsscigatewayfortranEximplf para um exem plo res também pode ser uma lista ver a ajuda de ode A entrada adda também é uma função externa Se adda for uma função a sintaxe deve ser como segue impl 163 r addatyp e deve retornar rAtyp onde p é uma matriz a ser adicionada a Aty Se adda for um string ele se refere a uma subrotina FORTRAN ou uma função C Ver SCImod ulesdifferentialequationsscigatewayfortranEximplf para um exem plo adda também pode ser uma lista ver a ajuda de ode A entrada jac também é uma função externa Se jac for uma função a sintaxe deve ser como segue j jactyydot e deve retornar o Jacobiano de rgtyAtyydot em relação a y Se jac for um string ele se refere a uma subrotina FORTRAN ou uma função C Ver SCImod ulesdifferentialequationsscigatewayfortranEximplf para um exem plo jac também pode ser uma lista ver a ajuda de ode Exemplos yimpl1000040040004residaplusp utilizando reinicialização rápida x1wiwimpl1000040040002residaplusp inicialização rápida da chamada anterior x1impl10000400400204residapluspwiw maxiabsx1x Ver Também dassl ode external 164 Name int2d integral definida 2d por quadratura e cubatura Ierrint2dXYf params Parâmetros X um array 3 por N contendo as abscissas dos vertices dos N triângulos Y um array 3 por N contendo as ordenadas dos vertices dos N triângulos f função externa função string ou lista definindo o integrando fuv params vetor de reais tol iclose maxtri mevals iflag O valor padrão é 1d10 1 50 4000 1 tol o limite desejado do erro Se iflag0 tol é interpretado como um limite de erro relativo se iflag1 o limite é de erro absoluto iclose um inteiro que determina a seleção dos métodos LQM0 ou LQM Se iclose1 então LQM1 é utilizado Qualquer outro valor de iclose faz com que LQM0 seja usado LQM0 utiliza valores da função apenas em pontos interiores ao triângulo LQM1 geralmente é mais preciso que LQM0 mas envolve a avaliação do integrando em mais pontos incluindo em alguns pontos da fronteira do triângulo Geralmente é melhor utilizar LQM1 a não ser que o integrando possuia singularidades nas bordas do triângulo maxtri o número máximo de triângulos na triangularização final da região mevals o número máximo de avaliações da função permitido Este número terá efeito na limitação da computação se for menor que 94maxtri quando LQM1 é especificado ou 56maxtri quando LQM0 é especificado iflag I o valor da integral err o erro estimado Descrição int2d computa a integral bidimensional de uma função f sobre uma região que consiste de n triângulos Um estimativa de erro total é obtida e comparada a tol que é fornecida como entrada para a subrotina A tolerância de erro é tratada como relativa ou absoluta dependendo do valor de entrada de iflag Um módulo de quadratura local Local Quadrature Module é aplicado para cada triângulo de entrada e estimativas da integral total e do erro total são computadas O módulo de quadratura local é a subrotina LQM0 ou a subrotina LQM1 e a escolha entre elas é determinada pelo valor da variável iclose int2d 165 Se a estimativa de erro total excede a tolerância o triângulo com maior erro absoluto é dividio em dois outro triângulos traçandose uma mediana por seu maior lado O módulo de quadratura local é então aplicado a cada um dos subtriângulos para se obter novas estimativas da integral e do erro Este proces so é repetido até que um dos seguintes 1 a tolerância é satisfeita 2 o número de triângulos gerados excede o parâmetro maxtri 3 o número de avaliações do integrando excede o parâmetro mevals ou 4 a função sente que um erro de arredondamento está começando a contaminar o resultado Exemplos X001110 Y000111 deffzfxyzcosxy Ieint2dXYf computa o integrando sobre o quadrado 0 1x0 1 Ver Também intc intl int3d intg mesh Autores Autores da rotina FORTRAN twodq KahanerDKNBS RechardOWNBS BarnhillRobertUniv de UTAH 166 Name int3d integral definida 3d pelo método da quadratura e cubatura resulterrint3dXYZf nfparams Parâmetros X um array 4 por NUMTET contendo as abscissas dos vértices dos NUMTET tetraedros Y um array 4 por NUMTET contendo as ordenadas dos vértices dos NUMTET tetraedros Z um array 4 por NUMTET contendo as terceiras coordenadas dos vértices dos NUMTET tetraedros f função externa function string ou lista definindo o integrando fxyznf onde xyz é o vetor das coordenadas de um ponto e nf os números das funções nf o número da função a ser integrada o padrão é 1 params vetor de reais minpts maxpts epsabs epsrel O valor padrão é 0 1000 00 1d5 epsabs limite do erro absoluto desejado epsrel limite do erro relativo desejado minpts número mínimo de avaliações da função maxpts número máximo de avaliações da função O número de avaliações da função sobre cada subregião é 43 result o valor da integral ou vetor de valores da integral err estimativas do erro absoluto Descrição A função calcula uma aproximação a um dado vetor de integrais definidas I I I F F F dx3dx2dx1 1 2 numfun onde a região de integração são os NUMTET tetraedros e onde int3d 167 F F X1X2X3 J 12NUMFUN J J uma estratégia globalmente adaptativa é aplicada para se computar aproximações resultk esperandose que satisfaça para cada componente de I à seguinte precisão ABSIK RESULTKMAXEPSABSEPSRELABSIK int3d repetidamente subdivide os tetraedros com maiores erros estimados e estima as integrais e os erros sobre os novos tetraedros até que a exigência de erro seja encontrada ou MAXPTS avaliações da função tenham sido feitas Uma regra de 43 pontos de integração com todos os pontos de avaliação dentro dos tetraedros é apli cada A regra tem grau polinomial 8 Se os valores dos parâmetros de entrada EPSABS ou EPSREL são suficientemente grandes uma re gra de integração é aplicada sobre cada tetraedro e os valores são aproximados para se fornecer as aproximações RESULTK Nenhuma subdivisão posterior dos tetraedros será feita Quando int3d computa estimativas a um vetor de integrais é dado tratamento igual a todos os com ponentes do vetor Isto é IFj e IFk para j diferente de k são estimados com a mesma subdivisão da região de integração Para integrais suficientemente semelhantes podemos economizar tempo aplicando int3d a todos os integrando em uma chamada Para integrais que variam continu amente em função de um parâmetro as estimativas produzidas por int3d também irão variar con tinuamente quando a subdivisão é aplicada a todos os componentes Este geralmente não será o caso quando componentes diferentes são tratados separadamente Por outro lado este recurso deve ser utilizado com cautela quando os componentes diferentes da in tegral requerem claramente subdivisões diferentes Referências Rotina FORTRAN dcutetf Exemplos X0100 Y0010 Z0001 RESULTERRORint3dXYZint3dex computa o integrando expxxyyzz sobre o tetraedro 000100010001 integração sobre um cubo 1ltxlt11ltylt11ltzlt1 fundo topo direita esquerda frente traseira X 0 0 0 0 0 0 0 0 0 0 0 0 11 11 1 1 11 11 11 11 11 1 1 11 11 11 1 1 1 1 1 1 11 1 1 1 1 Y 0 0 0 0 0 0 0 0 0 0 0 0 11 11 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 11 11 11 1 1 Z 0 0 0 0 0 0 0 0 0 0 0 0 11 1 1 1 1 1 1 11 11 11 1 1 11 11 1 1 1 1 int3d 168 11 1 1 1 1 1 1 1 1 1 1 function vfxyznumfunvexpxyzxyzendfunction resulterrint3dXYZf101000001d51d7 function vfxyznumfunv1endfunction resulterrint3dXYZf101000001d51d7 Ver Também intc intl int2d Autores Jarle Berntsen The Computing Centre University of Bergen Thormohlens gt 55 N5008 Bergen Noruega Fone 475544055 Email jarleeikiiuibno Ronald Cools Dept of Computer Science Katholieke Universiteit Leuven Celestijnenlaan 200A B3030 Hev erlee Belgium Fone 3216201015 3562 Email ronaldcskuleuvenacbe Terje O Espelid Department of Informatics University of Bergen Thormohlens gt 55 N5008 Bergen Norway Fone 475544180 Email terjeeikiiuibno 169 Name intc integral de Cauchy yintcabf Parâmetros ab dois números complexos f função externa Descrição Se f é uma função com valores complexos intcabf computa o valor da integral de a a b de fzdz ao longo da reta a b do plano complexo Ver Também intg intl Autor F D 170 Name integrate integração pela quadratura xintegrateexprvx0x1 atol rtol Parâmetros expr string definindo uma expressão Scilab v string variável da integração x0 número real limite inferior de integração x1 vetor de números reais limites superiores de integração atol número real erro absoluto Valor padrão 18 rtol número real erro relativo Valor padrão 1e14 x vetor de números reais o valor da integral para cada x1i Descrição Computa para i1sizex1 Onde é dado pela expressão expr A avaliação procura satisfazer à seguinte precisão absIx maxatolrtolabsI onde I é o valor exato da integral Restrição A expressão dada não deve utilizar nomes de variáveis começando por Exemplos x00x10012pi Xintegratesinxxx0x1 normcosx11X x1100110 Xintegrateif x0 then 1 else sinxxendx0x1 integrate 171 Ver Também intg inttrap intsplin ode 172 Name intg integral definida verrintgabf ea er Parâmetros ab números reais f função externa função lista ou string ea er números reais ea erro absoluto requerido no resultado Valor padrão 1d14 er erro relativo requerido no resultado Valor padrão 1d8 err erro absoluto estimado no resultado Descrição intgabf avalia a integral definida de a a b de ftdt A função ft deve ser contínua Esperase que a avaliação satisfaça à seguinte precisão absIv maxeaerabsI onde I é o valor exato da integral f é uma função externa Se f é uma função sua definição deve ser como segue y ft Se f é uma lista a lista deve ser como segue listfx1x2 onde f é uma função com seqüência de chamamento ftx1x2 Se f é um string ele se refere ao nome de uma função FORTRAN ou procedure C com dada seqüência de chamamento No caso FORTRAN a seqüência de chamamento deve ser double precision function fx onde x tabém é um número de dupla precisão No caso C a seqüência de chamamento é double fdouble x Exemplos caso de função Scilab function yfxyxsin30xsqrt1x2pi2endfunction exact25432596188 Iintg02pif absexactI caso de função Scilab com parâmetros function yf1xwyxsinwxsqrt1x2pi2endfunction intg 173 Iintg02pilistf130 absexactI caso de código FORTRAN compilador FORTRAN requerido escreve o código FORTRAN cd TMPDIR F double precision function ffunx double precision xpi pi314159265358979312d0 ffunxsin300d0xsqrt10d0x20d0pi2 return end mputlFTMPDIRffunf compile o código FORTRAN lilibforlinkffunffunff linking incremental linklffunf integrando a função Iintg02piffun absexactI caso de código C compilador C requerido escreva o código C Cinclude mathh double cfundouble x double ypi314159265358979312 yx20e0pi return xsin300e0xsqrt10e0yy mputlCTMPDIRcfunc compile o código C lilibforlinkcfuncfuncc linking incremental linklcfunc integrando a função Iintg02picfun absexactI Ver Também intc intl inttrap intsplin ode Funções Utilizadas As rotinas associadas podem ser encontradas no diretório SCImodulesdifferentialequationssrcfor tran dqag0f e dqagsf de quadpack 174 Name intl integral de Cauchy yintlabz0rf Parâmetros z0 número complexo ab dois número reais r número real positivo f função externa Descrição Se f é uma função externa com valores complexos intlabz0rf computa a integral de fzdz ao longo da curva no plano complexo definida por z0 rexpit para atb parte do círculo com centro z0 e raio r com fase entre a e b Ver Também intc Autor F D 175 Name ode Solucionador de equações diferenciais ordinárias yodey0t0tf ywiwodetypey0t0t rtol atolf jac wiw yrdwiwoderooty0t0t rtol atolf jacngg wiw yodediscretey0k0kvectf Parâmetros y0 matriz ou vetor de reais condições iniciais t0 escalar real tempo inicial t vetor de reais tempos nos quais a solução é computada f função externa função lista ou string type um dos strings seguintes adams stiff rk rkf fix discrete roots rtolatol constantes reais ou vetores com o mesmo tamanho que y jac função externa função lista ou string wiw vetores de reais ng inteiro g função externa função lista ou string k0 inteiro tempo inicial kvect vetor de inteiros Descrição ode é a função padrão para se resolver sistemas de EDO explícitos definidos por dydtfty yt0y0 É uma interface entre vários solucionadores em particular a ODEPACK O tipo de proble ma resolvido e o método a ser utilizado dependem do primeiro argumento opcional type que pode ser um dos strings seguintes not given O lsoda solucionador do pacote ODEPACK é chamado por padrão Ele escolhe automati camente entre o método preditorcorretor nãorígido de Adams e a Fórmula de Diferenciação Retroativa FDR rígida Ele utiliza o método não rígido inicialmente e monitora os dados para decidir qual método utilizar ode 176 adams Este é para problemas não rígidos O solucionador lsode do pacote ODEPACK é chamado e utiliza o método de Adams stiff Este é para problemas rígidos O solucionador lsode do pacote ODEPACK é chamado e é uti lizado o método FDR rk Método adaptativo de RungeKutta de ordem 4 RK4 rkf O programa de Shampine e Watts baseado no par RungeKutta de Fehlberg de ordem 4 e 5 RKF45 é utilizado Este é utilizado para problemas nãorígidos e mediamente rígidos quando as computações de derivação não são custosas Este método não é recomendado ser utilizado quando o usuário requer uma maior precisão fix Mesmo solucionador que rkf mas a interface do usuário é bem simples ie apenas os parâmetros rtol e atol podem ser passados ao solucionador Este é o método mais simples a se tentar root Solucionador de EDOs com capacidade de encontrar raízes O solucionador lsodar do pacote ODEPACK é utilizado É uma variante do solucionador lsoda onde se acha raízes de uma dada função vetorial Ver ajuda em oderoot para mais detalhes discrete Simulação de tempo discreto Ver ajuda em odediscrete para mais detalhes Nesta ajuda podemos apenas descrever o uso de ode para sistemas padrões explícitos EDOs A chamada mais simples a ode é yodey0t0tf onde y0 é o vetor de condições iniciais t0 é o tempo inicial t é o vetor de tempos onde a solução y é computada e y é a matriz de vetores soluções yyt1yt2 O argumento de entrada f define o lado direito da equação diferencial de primeira ordem dy dtfty É uma função externa isto é uma função com sintaxe especificada ou o nome de uma subrotina Fortran ou uma subfunção C string com seqüência de chamamento especificada ou uma lista Se f for uma função do Scilab a sua sintaxe deve ser ydot fty onde t é um escalar real tempo e y é um vetor de reais estado ydot é um vetor de reais dydt Se f é um string ele se refere ao nome de uma subrotina Fortran ou uma subfunção C ie Se odey0t0tfex for o comando então a subrotina fex será chamada A rotina Fortran deve ter a seguinte seqüência de chamamento fexntyydot com n um inteiro t um escalar de dupla precisão y e ydot vetores de dupla precisão A função C deve ter o seguinte protótipo fexint ndouble tdouble ydouble ydot t é o tempo y o estado e ydot a derivada do estado dydt Esta função externa pode ser construída em um SO de modo indpendente através de ilibforlink e ligada dinamicamente através da função do Scilab link O argumento f também pode ser uma lista com a seguinte estrutura lstlistrealfu1u2un onde realf é uma função do Scilab com a sintaxe ydot ftyu1u2un ode 177 Esta sintaxe permite utilizar parâmetros como argumentos de realf A função f pode retornar uma matriz p x q ao invés de um vetor Com esta notação de matriz nos resolvemos o sistema npq de EDOs dYdtFtY onde Y é uma matriz p x q matrix Então as condições iniciais Y0 também devem ser uma matriz p x q e o resultado de ode é a matriz p x qT1 Yt0Yt1YtT Argumentos de entrada opcionais podem ser fornecidos para o erro da solução rtol e atol são limiares para os erros relativos e absolutos estimados O erro estimado em yi é rtoliabsyiatoli e uma intergração é feita enquanto este erro é pequeno para todos os componentes do estado Se rtol eou atol for uma constante rtoli eou atoli são ajustados para esta constante Os valores padrões para rtol e atol são respectivamente rtol1d5 e atol1d7 para a maior parte dos solucionadores rtol1d3 e atol1d4 para rfk e fix Para problemas rígidos é melhor fornecer o Jacobiano da função do lado direito da equação como o argumento opcional jac É uma função externa istoé ie uma função com sintaxe especificada ou o nome de uma subrotina Fortran ou uma subfunção C string com seqüência de chamamento especificada ou uma lista Se jac for uma função a sintaxe deve ser Jjacty onde t é um escalar real tempo y é um vetor de reais estado A matriz resultante J deve fornecer dfdx ie Jki dfkdxi com fk késimo componente de f Se jac for um sting ele se refere a uma subrotina Fortran ou uma subfunção C com as seguinte seqüência de chamamento No caso Fortran subroutine fexntymlmuJnrpd integer nmlmunrpd double precision tyJ No caso C void fexint ndouble tdouble yint mlint mudouble Jint nrpd jacntymlmuJnrpd Na maior parte dos casos você não tem que se referir a ml mu e nrpd Se jac for uma lista as mesmas convenções que para f se aplicam Os argumentos opcionais w e iw e vetores para armazenamento de informações podem ser retor nados pela rotina de integração ver odeoptionaloutput para detalhes Queando esses vetores são fornecidos no lado direito de ode a integração reinicia com os mesmos parâmetros da parada anteiror Mais opções podem ser fornecidas a solucionadores ODEPACK utilizandose a variável ODEOP TIONS Ver odeoptions Exemplos ode 178 EDO simples de uma dimensão função externa do Scilab dydty2y sintcost y00 function ydotftyydoty2ysintcostendfunction y00t00t001pi yodey0t0tf plotty EDO simples de uma dimensão função externa codificada em C ccodeinclude mathh void myodeint ndouble tdouble ydouble ydot ydot0y0y0y0sintcost mputlccodeTMPDIRmyodec criando o arquivo C ilibforlinkmyodemyodeccTMPDIRMakefileTMPDIRloaderscecompilando execTMPDIRloadersce linking incremental y00t00t001pi yodey0t0tmyode Simulação de dxdt A xt B ut com utsinomegat x010 solução xt desejada em t01 02 05 1 A e a função u são passados para a função do lado direito em uma lista B e omega são passados como variáveis globais function xdotlineartxAuxdotAxButendfunction function utututsinomegatendfunction A1 10 2B11omega5 ode1000102051listlinearAu Integração com notação matricial da equação diferencial de Ricatti XdotAX XA XBX C X0Identity Solução em t12 function XdotrictXXdotAXXAXBXCendfunction A1102 B1001 C1001 t00t001pi XodeeyeA0tric Notação matricial computação de expA A1102 function xdotftxxdotAxendfunction odeeyeA01f odeadamseyeA01f Notação de matriz computação de expA com matriz rígida Jacobian fornecida A10001 function xdotftxxdotAxendfunction function JJacobiantyJAendfunction odestiff0101fJacobian Ver Também odediscrete oderoot dassl impl odedc odeoptions csim ltitr rtitr Autor Alan C Hindmarsh mathematics and statistics division l316 livermore ca 9455019 ode 179 Bibliografia Alan C Hindmarsh lsode and lsodi two new initial value ordinary differential equation solvers acm signum newsletter vol 15 no 4 1980 pp 1011 Funções Utilizadas As rotinas associadas podem ser encontradas no diretório SCImodulesdifferentialequationssrcfor tran lsodef lsodaf lsodarf 180 Name odediscrete solucionador de equações diferenciais ordinárias simulação de tempo discreto yodediscretey0k0kvectf Parâmetros y0 vetor de reais ou matriz condições iniciais t0 escalar real tempo inicial f função externa ie função string ou lista k0 inteiro tempo inicial kvect vetor de inteiros Descrição Com esta sintaxe primeiro argumento igual a discrete ode computa recursivamente yk 1fkyk de um estado inicial yk0 e retorna yk para k em kvect kvect1 deve ser maior do que ou igual a k0 Outros argumentos e opções são os mesmos que para ode veja a página de ajuda de ode Exemplos y1123 deffypafunctionkyypAyBuk Adiag020509 B111u110n5 yodediscretey111nafunction y2Ay1Bu1 Agora y é avaliado em y3y5y7y9 yodediscretey11329afunction Ver Também ode 181 Name odeoptionaloutput descrição de saídas opcionais de solucionadores de EDOs Descrição Esta página descreve os valores mais importantes retornados nos argumento opcionais do lado esquer do da função ode w e iw São válidos apenas para os solucionadores de EDOs lsode lsoda e lsodar Para mais detalhes pode se consultar os comentários dos códigos das subrotinas FORTRAN SCImodulesdifferentialequationssrcfortranlsodf w11 último tamanho do passo em t utilizado sucessivamente w12 o tamanho do passo a ser tentado no próximo passo w13 o valor corrente da variável independente alcançado pelo solucionador ie o ponto de malha interno t corrente Ná saída tcur sempre estará pelo menos tão longe quanto o argumento t mas pode estar mais longe se foi realizada interpolação w14 um fator de escala de tolerância maior que 10 computado quando se detecta requerer muita precisão istate 3 se detectado no início do problema istate 2 em caso contrário Se itol for inalterado mas rtol e atol forem uniformemente escalados por um fator de tolsfw14 para a próxima chamada emtão supõese que o solucionador pode continuar o usuário também pode ignorar tolsf e alterar os parâmetros de tolerância de qualquer outro modo apropriado w15 o valor de t no tempo da última alternação de método se houver Este valor não é significante com o solucionador lsode iw10 o número de avaliações de g para problema até então Este valor é significante apenas para o solucionador lsodar iw11 o número de passos tomados para o problema até então iw12 o número de avaliações de f até então iw13 o número de avaliações do jacobiano e de decomposições lu da matriz para o problema até então iw14 a última ordem do método utilizada sucessivamente iw15 a ordem a ser tentada no próximo passo iw16 o índice do componente de maior magnitude no vetor de erro local ponderado eiewti sobre um erro retorna istate 4 or 5 iw17 o comprimento de w realmente requerido supondo que o comprimento de rwork deve ser fixado para o resto do problema e que a alternância pode ocorrer Isto é definido sobre retornos normais e sobre um retorno de entrada ilegal para armazenamento insuficiente odeoptionaloutput 182 iw18 o comprimento de iw realmente requerido supondo que o comprimento de iw deve ser fixado pelo resto do problema e que a alternância pode ocorrer Isto é definido sobre retornos normais e sobre um retorno de entrada ilegal para armazenamento insuficiente iw19 o indicador do método para o último passo realizado com sucesso 1 significa adams nonstiff 2 significa bdf stiff Este valor não é significante com o solucionador lsode iw20 o indicador do método corrente 1 significa adams nonstiff 2 significa bdf stiff Este é o método a ser tentado no próximo passo Logo difere de iw19 apenas se uma alternância de métodos foi realizada Este valor não é significante com o solucionador lsode 183 Name oderoot solucionador de EDOs com busca de raízes yrdwiwoderooty0t0t rtol atolf jacngg wiw Parâmemtros y0 vetor de reais ou matriz condições iniciais t0 escalar real tempo inicial t vetor de reais tempos nos quais a solução é computada f função externa ie função string ou lista rtolatol constantes reais ou vetores reais com o mesmo tamanho que y jac função externa ie função string ou lista wiw vetores de reais ng inteiros g função externa ie função string ou lista Descrição Com esta sintaxe primeiro argumento igual a root ode computa a solução da EDO dy dtfty até que o estado yt cruze a superfície gty0 g deve fornecer a equação da superfície É uma função externa ie uma função com sintaxe especi ficada ou o nome de uma subrotina FORTRAN ou função C string com seqüência de chamamento especificada ou uma lista Se g é uma função a sintaxe deve ser como segue zgty onde t é um escalar real tempo e y um vetor de reais estado Ela retorna um vetor de tamanho ng que corresponde às ng restrições Se g é um string ele se refere a uma subrotina FORTRAN ou uma função C com a seguinte seqüência de chamamento gntynggout onde ng é o número de restrições e gout é o valor de g saída do programa Se g é uma lista as mesmas convenções para f se aplicam ver ajuda de ode A saída rd é um vetor 1 x k A primeira entrada contém o tempo de parada Outras entradas indicam que componentes de g possuem sinal trocado k maior que 2 indica que mais de uma superfície k1 superfícies foram simultaneamente atravessadas oderoot 184 Outros argumentos e opções são os mesmos que para ode ver a página de ajuda de ode Exemplos Integração da equação diferencial dydty y01 e acha o tempo mínimo t tal que yt2 deffydotftyydoty deffzgtyzy2 y01ng1 yrdoderootsy002fngg deffzgtyzy2233 yrdoderoots102f3g Ver Também dasrt ode 185 Name odedc solucionador de EDOs contínuasdiscretas ytodedcy0ndstdelt0tf Parâmetros y0 vetor coluna de reais condições iniciais y0y0cy0d onde y0d tem nd componentes nd inteiro dimensão de y0d stdel vetor de reais com uma ou duas entradas stdelh delta com delta0 como valor padrão t0 escalar real tempo inicial t vetor linha de reais instantes onde yt é calculado f função externa ie função string ou lista com seqüência de chamamento ypftycydflag Descrição yodedcy0cy0dndhdeltat0tf computa a solução de um sistema misto contínuodiscreto O estado de sistema discreto ydk é embutido em uma função de tempo seccional constante ydt como segue ydtydk para t em tkatrasokhtk1delayk1h com atrasohdelta As equações simuladas são agora dycdtftyctydt0 para t em tktk1 yct0y0c e nos instantes tk a variável discreta yd é atualizada por ydtkfyctkydtk1 Note que utilizando a definição de ydt a última equação fornece ydk f tkyctkydtk11 yc é de tempo contínuo yctkyctk Os parâmetros de chamada de f são fixados ycdftycydflag esta função deve retornar a derivada do vetor yc se flag0 ou a atualização de yd se flag1 odedc 186 ycddotyc deve ser um vetor de mesma dimensão que yc se flag0 e ycdupdateyd deve ser um vetor com a mesma dimensão que yd se flag1 t é um vetor de constantes onde a solução y é computada y é o vetor yyt1yt2 Esta função pode ser chamada com os mesmo parâmetro opcionais da função ode desde que nd e stdel sejam dados na seqüência de chamamen to como segundo e terceiro parâmetros Em particular flags de integração e tolerâncias podem ser ajustadas Parâmetros opcionais podem ser ajustados pela função odeoptions Um exemplo para chamada de rotina externa é encontrado em SCIDIRdefaultfydot2f Rotinas externas podem ser ligadas dinamicamente ver link Exemplos sistema linear com entrada alternante deffxduphistxuflagif flag0 then xduAxBu else xdu1uend x011A1221B12u0nu1stdel10u00t000510 xuodedcx0u0nustdel0tphisxxu12uxu3 nx2 plot2d1onntx1nx161 plot2d2onntunx1nxnu000 função externa FORTRAN ver fydot2f normxuodedcx0u0nustdel0tphis1 feedback resposta amostrado xcdotfctxcu sistema yhctxc xdfdxdy feedback uhdtxd deffxcdftxcxdiflag if iflag0 then xcdfctxcethdtxd else xcdfdxdhctxc end A102341067810B111C111 Ad1210120Bd11Cd11 deffstetstsin3t deffxdotfctxuxdotAxBu deffyhctxyCx deffxpfdxyxpAdx Bdy deffuhdtxuCdx h01t00t0012 x0c000x0d00nd2 xcdodedcx0cx0dndht0tf normxcdodedcx0cx0dndht0tfcd1 cálculo rápido ver fydot2f plot2dtttxcd13 xsetwindow2plot2d2gnnttxcd45 odedc 187 xsetwindow0 Ver Também ode odeoptions csim external 188 Name odeoptions ajusta opções para solucionadores de EDO odeoptions Descrição Esta função exibe interativamente um comando que deveria ser executado para se ajustar diversas opções para solucionadores de EDOs A variável global ODEOPTIONS ajusta as opções CUIDADO a função ode verifica se esta variável existe e neste caso a utiliza Para se utilizar valores padrões devese limpar esta variável Note que odeoptions não cria esta variável Para criála você deve executar a linha de comando exibida por odeoptions A variável ODEOPTIONS é um vetor com os seguintes elementos itasktcrith0hmaxhminjactypmxstepmaxordnmaxordsixprmlmu O valor padrão é 100inf02500125011 O significado de cada elemento é descrito abaixo itask 1 computação normal nos tempos especificados 2 computação nos tempos de malha dados na primeira linha da saída de ode 3 um passo em um ponto interno da malha e retorna 4 computação normal sem overshooting desvalorização excessiva tcrit 5 um passo sem passagem de tcrit e retorna tcrit assume itask igual a 4 ou 5 descrito acima h0 primeiro passo tentado hmax tamanho máximo do passo hmin tamanho mínimo do passo jactype 0 iterações funcionais nenhum jacobiano usado adams ou stiff apenas 1 jacobiano completo fornecido pelo usuário 2 jacobiano completo internamente gerado 3 jacobiano diagonal internamente gerado adams ou stiff apenas 4 jacobiano com bandas fornecido pelo usuário ver ml e mu abaixo 5 jacobiano com bandas internamente gerado ver ml e mu abaixo maxordn máxima ordem nãostiff permitida no máximo 12 maxords máxima ordem stiff permitida no máximo 5 ixpr nível de impressão 0 ou 1 mlmu se jactype é igual a 4 ou 5 ml e mu são as semibandas inferior e superior do jacobiano com bandas a banda são os ijs com iml j ny1 Se jactype é igual a 4 a função jacobiana deve retornar uma matriz J que é mlmu1 x ny onde nydim de y em ydotfty tal que a coluna 1 de J é feita de mu zeros seguidos por df1dy1 df2dy1 df3dy1 1ml entradas nãonulas possivelmente a coluna 2 é feita de mu1 zeros seguidos por df1dx2 df2dx2 etc Ver Também ode 189 Name bvode boundary value problems for ODE using collocation method bvodeS Simplified call to bvode zubvodexpointsNmxlowxupzetaiparltoltolfixpntfsubdfsubgsubdgsubguess zubvodeSxpointsmNxlowxupfsubgsubzeta optionalargs Parameters zu a column vector of size M The solution of the ode evaluated on the mesh given by points It contains zux for each requested points xpoints an array which gives the points for which we want to observe the solution N a scalar with integer valuenumber of differential equations N 20 m a vector of size N with integer elements It is the vector of order of each differential equation mi gives the order of the ith differential equation In the following M will represent the sum of the elements of m xlow a scalar left end of interval xup a scalar right end of interval zeta a vector of size Mzetaj gives jth side condition point boundary point One must have xlowzetaj zetaj1xup All side condition points must be mesh points in all meshes used see description of ipar11 and fixpnt below ipar an array with 11 integer elements nonlin collpnt subint ntol ndimf ndimi iprint iread iguess rstartnfxpnt nonlin ipar1 0 if the problem is linear 1 if the problem is nonlinear collpnt ipar2 Gives the number of collocation points per subinterval where maxmj collpnt 7 if ipar20 then collpnt is set to max maxmj1 5maxmj subint ipar3 Gives the number of subintervals in the initial mesh if ipar3 0 then bvode arbitrarily sets subint 5 ntol ipar4 Gives the number of solution and derivative tolerances We require 0 ntol M ipar4 must be set to the dimension of the tol argument or to 0 In the latter case the actual value will automatically be set to sizetol bvode 190 ndimf ipar5 Gives the dimension of fspace a real work array its value provides a constraint on nmax the maximum number of subintervals The ipar5 value must respect the constraint ipar5nmaxnsizef where nsizef43M5collpntNcollpntNM2Mnrec2M nrec is the number of right end boundary conditions ndimi ipar6 Gives the dimension of ispace an integer work array its value provides a constraint on nmax the maximum number of subintervals The ipar6 value must respect the constraint ipar6nmaxnsizei where nsizei3 collpntNM iprint ipar7 output control make take the following values 1 for full diagnostic printout 0 for selected printout 1 for no printout iread ipar8 0 causes bvode to generate a uniform initial mesh xx Other values are not implemented yet in Scilab 1 if the initial mesh is provided by the user it is defined in fspace as follows the mesh will occupy fspace1 fspacen1 the user needs to supply only the interior mesh points fspacej xj j 2 n 2 if the initial mesh is supplied by the user as with ipar81 and in addition no adaptive mesh selection is to be done iguess ipar9 0 if no initial guess for the solution is provided 1 if an initial guess is provided by the user trought the argument guess 2 if an initial mesh and approximate solution coefficients are provided by the user in fspace the former and new mesh are the same 3 if a former mesh and approximate solution coefficients are provided by the user in fspace and the new mesh is to be taken twice as coarse ieevery second point from the former mesh bvode 191 4 if in addition to a former initial mesh and approximate solution coefficients a new mesh is provided in fspace as well see description of output for further details on iguess 2 3 and 4 ireg ipar10 0 if the problem is regular 1 if the first relax factor is equal to ireg and the nonlinear iteration does not rely on past covergence use for an extra sensitive nonlinear problem only 2 if we are to return immediately upon a two successive nonconvergences or b after obtaining error estimate for the first time nfxpnt ipar11 Gives the number of fixed points in the mesh other than xlow and xup the dimension of fixpnt ipar11 must be set to the dimension of the fixpnt argument or to 0 In the latter case the actual value will automatically be set to sizefixpnt ltol an array of dimension ntolipar4 ltolj l specifies that the jth tolerance in the tol array controls the error in the lth component of It is also required that 1 ltol1 ltol2 ltolntol M tol an array of dimension ntolipar4 tolj is the error tolerance on the ltolj th component of Thus the code attempts to satisfy on each subinterval if is the approximate solution vector an u the exact solution unknown fixpnt an array of dimension nfxpntipar11 it contains the points other than xlow and xup which are to be included in every mesh The code requires that all side condition points other than xlow and xup see description of zeta be included as fixed points in fixpnt fsub an external used to evaluate the column vector f for any x such as xlow x xup and for any zzux see description below The external must have the headings In Fortran the calling sequence must be subroutine fsubxzuf double precision zu fx bvode 192 In C the function prototype must be void fsubdouble x double zu double f And in Scilab function ffsubxzuparameters dfsub an external used to evaluate the Jacobian of fxzu at a point x Where zux is defined as for fsub and the N by M array df should be filled by the partial derivatives of f The external must have the headings In Fortran the calling sequence must be subroutine dfsubxzudf double precision zu dfx In C the function prototype must be void dfsubdouble x double zu double df And in Scilab function dfdfsubxzuparameters gsub an external used to evaluate given z z zetai for 1iM The external must have the headings In Fortran the calling sequence must be subroutine gsubizug double precision zu g integer i In C the function prototype must be bvode 193 void gsubint i double zu double g And in Scilab function ggsubizuparameters Note that in contrast to f in fsub here only one value per call is returned in g dgsub an external used to evaluate the ith row of the Jacobian of gxux Where zu is as for fsub i as for gsub and the Mvector dg should be filled with the partial derivatives of g viz for a particular call one calculates The external must have the headings In Fortran the calling sequence must be subroutine dgsubizudg double precision zu dg In C the function prototype must be void dgsubint i double zu double dg And in Scilab function dgdgsubizuparameters guess An external used to evaluate the initial approximation for zux and dmvalux the vector of the mjth derivatives of ux Note that this subroutine is used only if ipar9 1 and then all M components of zu and N components of dmval should be computed for any x such as xlow x xup The external must have the headings In Fortran the calling sequence must be subroutine guessxzudmval double precision xz dmval In C the function prototype must be bvode 194 void fsubdouble x double zu double dmval And in Scilab function dmvalzufsubxparameters optionalargs It should be either any left part of the ordered sequence of values guess dfsub dgsub fixpnt ndimf ndimi ltol tol ntolnonlin collpnt subint iprint ireg ifail or any sequence of argnameargvalue with argname in guess dfsub dgsub fixpnt ndimf ndimi ltol tol ntol nonlin collpnt subint iprint ireg ifail Where all these arguments excepted ifail are described above ifail can be used to display the bvode call corresonding to the selected optional arguments If guess is given iguess is set to 1 Description These functions solves a multipoint boundary value problem for a mixed order system of odes given by Where The argument zu used by the external functions and returned by bvode is the column vector formed by the components of zux for a given x The method used to approximate the solution u is collocation at gaussian points requiring mi1 continuous derivatives in the ith component i 1N here k is the number of collocation points stages per subinterval and is chosen such that k ge max mi a rungekuttamonomial solution representation is utilized bvode 195 Examples The first two problems below are taken from the paper 1 of the Bibliography The problem 1 describes a uniformy loaded beam of variable stifness simply supported at both end It may be defined as follow Solve the fourth order differential equation Subjected to the boundary conditions The exact solution of this problem is known to be N1 just one differential equation m4a fourth order differential equation Msumm xlow1xup2 the x limits zetaxlowxlowxupxup two constraints on the value of u and its second derivative on each bound The external functions Theses functions are called by the solver with zuuxuxuxux The function which computes the right hand side of the differential equation function ffsubxzuf16x2zu46xzu3x3endfunction The function which computes the derivative of fsub with respect to zu function dfdfsubxzudf006x26xendfunction The function which computes the ith constraint for a given i function ggsubizu select i case 1 then xzeta11 gzu1 u10 case 2 then xzeta21 gzu3 u10 case 3 then xzeta32 gzu1 u20 case 4 then xzeta42 gzu3 u20 end bvode 196 endfunction The function which computes the derivative of gsub with respect to z function dgdgsubiz select i case 1 then xzeta11 dg1000 case 2 then xzeta21 dg0010 case 3 then xzeta32 dg1000 case 4 then xzeta42 dg0010 end endfunction The function which computes the initial guess unused here function zumparguessxzu0mpar0endfunction define the function which computes the exact value of u for a given x for testing purposes function zutrusolx zu0ones41 zu1 02510log231x 05 1x 3xlogx x zu2 02510log23 05 1x2 3xx logx 1 zu3 05 2x3 1x 3x2 zu4 056x4 1xx 6x3 endfunction fixpnt All boundary conditions are located at xlow and xup nonlin collpnt n ntol ndimf ndimi iprint iread iguess rstart nfxpnt ipar0 0 1 2 2000 200 1 0 0 0 0 ltol13set tolerance control on zu1 and zu3 tol1e111e11set tolreance values for these two controls xpointsxlow001xup zubvodexpointsNmxlowxupzetaiparltoltolfixpnt fsubdfsubgsubdgsubguess check the constraints zu131 should be zero plotxpointszu1 the evolution of the solution u zu1for xxpointszu1zu1trusolx end normzuzu1 Same problem using bvodeS and an initial guess function zlhSzstartx zzeros51z51 lhS01 endfunction zubvodexpointsNmxlowxupzetaltolltoltoltolguesszstart The problem 2 describes the small finite deformation of a thin shallow spherical cap of constant thickness subject to a quadratically varying axisymmetric external pressure distribution Here phi bvode 197 is the meridian angle change of the deformed shell and psi is a stress function For epsmu1e3 two different solutions may found depending on the starting point Subject to the boundary conditions for x0 and x1 N2 two differential equations m2 2each differential equation is of second order Msumm xlow0xup1 the x limits zetaxlowxlow xup xup two constraints on each bound The external functions Theses functions are called by the solver with zuu1xu1xu2xu2x The function which computes the right hand side of the differential equation function ffsub2xzuepsdmueps4mugamxt fzu1x2zu2xzu1zu31zu1xgamx1x22eps4mu phi zu3x2zu4xzu11zu12xdmupsi endfunction The function which computes the derivative of fsub with respect to zu function dfdfsub2xzuepsdmueps4mugamxt df1x21zu3xeps4mu 1x 1zu1xeps4mu 0 1zu1xdmu 0 1x2 1x endfunction The function which computes the ith constraint for a given i function ggsub2izu select i case 1 then xzeta10 gzu1 u00 case 2 then xzeta20 g03zu3 xpsi03psi07x0 case 3 then xzeta31 gzu1 u10 case 4 then xzeta41 g1zu403zu3071 xpsi03psi07x0 end endfunction The function which computes the derivative of gsub with respect to z function dgdgsub2iz select i bvode 198 case 1 then xzeta11 dg1000 case 2 then xzeta21 dg00030 case 3 then xzeta32 dg1000 case 4 then xzeta42 dg00031 end endfunction gam11 eps1d3 dmueps eps4mueps4dmu xtsqrt2gam1gam fixpnt All boundary conditions are located at xlow and xup collpnt4 nsizef43M5collpntNcollpntNM2M22M nsizei3 collpntNM nmax200 nonlin collpnt n ntol ndimf ndimi iprint iread iguess rstart nfxpnt ipar1 k 10 4 nmaxnsizef nmaxnsizei 1 0 0 0 0 ltol14set tolerance control on zu1 zu2 zu3 and zu4 tol1e51e51e51e5set tolreance values for these four controls xpointsxlow001xup zubvodexpointsNmxlowxupzetaiparltoltolfixpnt fsub2dfsub2gsub2dgsub2guess2 scf1clfplotxpointszu1 3 the evolution of the solution phi and psi using an initial guess The function which computes the initial guess unused here function zudmvalguess2xgam consgamx1x22 dconsgam13x22 d2cons3gamx dmvalzeros21 if xxt then zu0 0 cons dcons dmval2d2cons else zu2x22xcons2dcons dmval2d2cons end endfunction ipar91iguess zu2bvodexpointsNmxlowxupzetaiparltoltolfixpnt fsub2dfsub2gsub2dgsub2guess2 scf2clfplotxpointszu21 3 the evolution of the solution phi and psi An eigenvalue problem bvode 199 yxlayx BV y0y0 y10 Eigenfunctions and eigenvalues are yxnsinsn1x lansn2 where sn are the zeros of fsnsatansn1pi n012 To get a third boundary condition we choose y01 With yx also cyx is a solution for each constant c We solve the following ode system ylay la0 BV y0y0 y01 y10 zyx yx la function rhsfsubxz rhsz3z10 endfunction function ggsubiz gz1z2 z11 z1 ggi endfunction The following start function is good for the first 8 eigenfunctions function zlhsystartxzla0 z10la0 lhs00 endfunction a0b1 m21 n2 zetaa a b N101 xlinspaceabN We have snn12pi 0 for n to infinity la0inputnth eigenvalue n la0pi2la0pi2 zbvodeSxmnabfsubgsubzetaystartlistystartla0 clf plotxz1 z2 xtitleStartvalue stringla0Eigenvalue stringz31x legendyxyx A boundary value problem with more than one solution DE yxexpyx BV y00 y10 This boundary value problem has more than one solution It is demonstrated how to find two of them with the help of some preinformation of the solutions yx to build the function ystart zyxyx a0b1m2n1 zetaa b N101 bvode 200 tol1e81 1 xlinspaceabN function rhsfsubxzrhsexpz1endfunction function ggsubiz gz1 z1 ggi endfunction function zlhsystartxzM z4x1xM 412xM zM0 lhsexp4x1xM lhs0 endfunction for M1 4 if M1 zbvodeSxmnabfsubgsubzetaystartlistystartMtoltol else z1bvodeSxmnabfsubgsubzetaystartlistystartMtoltol end end Integrating the ode yield eg the two solutions yex and yex1 function yfcyc1tanhsqrtc422endfunction cfsolve2f function yyexxc ylogc21tanhsqrtc14x22 endfunction function yf1c1 y2c12tanh14c121endfunction c1fsolve01f1 function yyex1xc1 ylog1tanh2x14c122c1c1 endfunction dispnormz1yexxnormyexxz1 dispnormz11yex1xnormyex1xz11 clf subplot211 plot2dxz1style5 xtitleTwo different solutionsx subplot212 plot2dxz11style5 xtitle x A multipoint boundary value problem DE yx1 zyxyxyx BV y12 y12 bvode 201 Side condition y01 a1b1c0 The side condition point c must be included in the array fixpnt n1 m3 function rhsfsubxz rhs1 endfunction function ggsubiz gz12 z11 z12 ggi endfunction N10 zetaa c b xlinspaceabN zbvodeSxmnabfsubgsubzetafixpntc function yyexx yx36x2x61 endfunction dispnormyexxz1normyexxz1 See Also link external ode dassl Used Functions This function is based on the Fortran routine colnew developped by U Ascher Department of Computer Science University of British Columbia Vancouver BC V6T 1W5 Canada G Bader institut f Angewandte mathematik university of Heidelberg im Neuenheimer feld 294d6900 Heidelberg 1 Authors This help is based on the original colnewf comments adapted to Scilab by JP Chancelier ENPC on the bvodeS help page due to Rainer von Seggern both merged and revised by S Steer INRIA Bibliography 1 U Ascher J Christiansen and RD Russell collocation software for boundaryvalue ODEs acm trans math software 7 1981 209222 this paper contains EXAMPLES where use of the code is demonstrated 2 G Bader and U Ascher a new basis implementation for a mixed order boundary value ode solver siam j scient stat comput 1987 3 U Ascher J Christiansen and RD Russell a collocation solver for mixed order systems of bound ary value problems math comp 33 1979 659679 bvode 202 4 U Ascher J Christiansen and RD russell colsys a collocation code for boundary value problems lecture notes compsc 76 springer verlag b childs et al eds 1979 164185 5 C Deboor and R Weiss solveblok a package for solving almost block diagonal linear systems acm trans math software 6 1980 8087 Parte III Funções Elementares 204 Name abs valor absoluto magnitude tabsx Parâmetros x matriz ou vetor de reais ou complexos t matriz ou vetor de reais Descrição absx é o valor absoluto dos elementos de x Quando x é de complexos absx é o módulo complexo magnitude dos elementos de x Exemplos abs1i1i1i 205 Name acos arcocosseno em relação aos elementos tacosx Parâmetros x vetor de reais ou complexos t vetor de reais ou complexos Descrição Os componentes do vetor t são os arcoscossenos das entradas correspondentes do vetor x O domínio de definição é 1 1 acos toma valores em Exemplos x1i1i cosacosx 206 Name acosd arcocosseno elemento a elemento com resultado em graus tacosdx Parâmetros x array de reais ou complexos t array de reais ou complexos Descrição Os componentes do vetor t são o arcocosseno em graus das entradas correspondentes do vetor x tacosx180pi Para dados reais em 1 1 os resultados estão em 0 180 Exemplos x1 0 1 sqrt22 sqrt22 sqrt32 sqrt32 acosdx Ver Também acos 207 Name acosh arcocoseno hiperbólico tacoshx Parâmetros x vetor de reais ou complexos t vetor de reais ou complexos Descrição Os componentes do vetor t são os arcoscosenos hiperbólicos das entradas correspondentes do vetor x O domínio de definição é 1infinito A função toma valores em conjuntos Exemplos x01i coshacoshx 208 Name acoshm arcocosseno hiperbólico da matriz matriz arcocosseno hiperbólico tacoshmx Parâmetros xt matriz quadrada de reais ou complexos Descrição acoshm é o arcocosseno hiperbólico da matriz x matriz arcocosseno hiperbólico Usa a fórmula tlogmxxeyesqrtmxeyexeye Para matrizes nãosimétricas o resultado pode ser impreciso Exemplos A1234 coshmacoshmA A11A11i coshmacoshmA Ver Também acosh logm sqrtm 209 Name acosm arcocoseno da matriz matriz arcocosseno tacosmx Parâmetros x matriz quadrada de reais ou complexos t matriz quadrada de reais ou complexos Descrição t é o arcocosseno da matriz x matriz arcocosseno de x É usado o método da diagonalização Para matrizes nãosimétricas o resultado pode ser impreciso Temse tilogmx isqrtmeyexx Exemplos A1234 cosmacosmA Ver Também acos sqrtm logm 210 Name acot computa o arcocotangente elemento a elemento do argumento y acotx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição computa o arcocotangente elemento a elemento do argumento Para argumento reais o resultado é real As seguintes desigualdades se verificam acotz piacotzpi2atanz iacothizpi21csgnzi Exemplos x1 2 2 sqrt2 sqrt2 2sqrt3 2sqrt3 1 acotxpi Ver Também cotg acotd Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 211 Name acotd computa o arcocotangente elemento a elemento do argumento com resultado em graus y acotdx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa o arcocotangente elemento a elemento do argumento com resultado em graus Para argu mento real w o resultado é real Exemplos x1 2 2 sqrt2 sqrt2 2sqrt3 2sqrt3 1 acotdx Ver Também cotd acot Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 212 Name acoth arcocotangente hiperbólico elemento a elemento y acothx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa o arcocotangente hiperbólico do argumento elemento a elemento Exemplos x300130 xabsx1nan plotxacothx Ver Também atanh coth Autor Serge Steer INRIA Funções Usadas Esta rotina é baseada na função atanh 213 Name acsc computa o arcocossecante elemento a elemento do argumento y acscx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição computa o arcocossecante elemento a elemento do argumento Para entradas com valores reais abso lutos maiores que 1 o resultado é real As seguintes desigualdades se verificam acscz acscz asin1z pi2 asecz iacschiz Exemplos xlinspace120200 xx11 nan x plotxacscx Ver Também csc acscd Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 214 Name acscd computa o arcocossecante elemento a elemento do argumento com resutado em graus y acscdx Parâmetros x array de reais y array de reais ou complexos Descrição computa o arcocossecante elemento a elemento do argumento com resutado em graus Para entradas reais com valores absolutos maiores que 1 o resultado é real Exemplos xlinspace120200 xx11 nan x plotxacscdx Ver Também cscd acsc Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 215 Name acsch computa o arcocossecante hiperbólico elemento a elemento do argumento y acschx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa o arcocossecante hiperbólico elemento a elemento do argumento Para argumentos com valores absolutos maiores que 1 o resultado é real As seguintes igualdades se verificam acschz acschz asinh1z csgni 1zasechizipi2 iacsciz Exemplos xlinspace120200 xx11 nan x plotxacschx Ver Também csch Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 216 Name adj2sp converte forma de adjacência para matriz esparsa Parâmetros xadj vetor de inteiros de comprimento n1 adjncy vetor de inteiros de comprimento nz contendo os índices de linha para os elementos correspon dentes em anz anz vetor coluna de comprimento nz contendo os elementos nãonulos de A mn vetor linha com duas entradas mnsizeA opcional A matriz quadrada esparsa de reais ou complexos nz entradas nãonulas Descrição adj2sp converte uma representação em forma de adjacência de uma matriz em sua representação padrão do Scilab função utilitária xadj adjncy anz representação de adjacência de A ie xadjj1xadjj número de entradas nãonulas na linha j adjncy índice de coluna das entradas nãonulas nas linha 1 linha 2 linha n anz valores das entradas nãonulas nas linha 1 linha 2 linha n xadj é um vetor coluna de tamanho n1 e adjncy é um vetor coluna de inteiros de tamanho nznnzA anz é um vetor de reais de tamanho nznnzA Exemplos A sprand1005005 xadjadjncyanz sp2adjA nmsizeA p adj2spxadjadjncyanznm Ap Ver Também sp2adj spcompack 217 Name amell função am de Jacobi snamelluk Parâmetros u escalar real ou vetor de reais k escalar sn escalar real ou vetor de reais Descrição Computa a função elíptica de Jacobi amuk onde k é o parâmetro e u é o argumento Se u é um vetor sn é o vetor dos valores computados elemento a elemento Usado na função sn Ver Também delip sn asn 218 Name and E lógico bandA bandA bandAr bandA1 bandAc bandA2 AB Descrição andA é o E lógico dos elementos da matriz de valores booleanos A andA retorna T true verdadeiro se e só se todas as entradas de A são T yandAr ou de modo equivalente yandA1 é o e em relação às linhas Retorna em cada entrada do vetor linha y o e das linhas de x O e é realizado no índice de linhas yj andAiji1m yandAc ou de modo equivalente yandA2 é o e em relação às colunas Retorna em cada entrada do vetor coluna y o e das colunas de x O e é realizado no índice de colunas yi andAijj1n AB fornece o and elemento a elemento das matrizes de valores booleanos A e B A e B devem ser matrizes com mesmas dimensões ou uma delas deve ser um único booleano Ver Também not or 219 Name asec computa o arcosecante elemento a elemento do argumento y asecx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição computa o arcosecante elemento a elemento do argumento Para valores reais com valores absolutos maiores que 1 o resultado é real As seguintes igualdades se verificam asecz acscz asin1z pi2 asecx iacschiz Exemplos x1 2 2 sqrt2 sqrt2 2sqrt3 2sqrt3 1 asecxpi Ver Também sec asecd Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 220 Name asecd computa o arcosecante elemento a elemento do argumento com resultados em graus y asecdx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição computa o arcosecante elemento a elemento do argumento com resultados em graus Para dados de entrada com valores absolutos maiores que 1 os resultados são reais em 90 90 asecdx is equal to asecx180pi Exemplos x1 2 2 sqrt2 sqrt2 2sqrt3 2sqrt3 1 asecdx Ver Também asec secd Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 221 Name asech computa o arcosecante hiperbólico elemento a elemento do argumento y asechx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa o arcosecante hiperbólico elemento a elemento do argumento Se o argumento é real e tem valor absoluto menor que 1 o resultado é real As seguintes igualdades se verificam asechx acosh1 x icsgni11 xasecxcsgni1 1 xpi2iacschix Exemplos asech1 Ver Também sech Referências Kahan W Branch cuts for complex elementary functions or Much ado about nothings sign bit Proceedings of the joing IMASIAM conference on The State of the Art in Numerical Analysis Uni versity of Birmingham A Iserles and MJD Powell eds Clarendon Press Oxford 1987 165210 Autor Serge Steer INRIA 222 Name asin arcoseno tasinx Parâmetros x vetor ou matriz de reais ou complexos t vetor ou matriz de reais ou complexos Descrição As entradas de t são os arcossenos das entradas correspondentes de x O domínio de deifinição é 1 1 A função toma valores em conjuntos Exemplos A1234 sinasinA Ver Também sin sinm asinm 223 Name asind arcoseno resultado em graus tasindx Parâmetros x vetormatriz de reais Os elementos devem estar em 1 1 t vetormatriz de reais com as mesmas dimensões que x Descrição As entradas de t são os arcosinversos das entradas correspondentes de x O domínio de definição é 1 1 Os resultados estão em 90 90 Exemplos x1 0 1 sqrt22 sqrt22 sqrt32 sqrt32 asindx Ver Também sin sind asinm 224 Name asinh arcoseno hiperbólico tasinhx Parâmetros x vetor ou matriz de reais ou complexos t vetor ou matriz de reais ou complexos Descrição As entradas de t são os arcossenos hiperbólicos das entradas correspondentes de x O domínio de definição é1infinito A função toma valores em conjuntos Exemplos A1223 sinhasinhA 225 Name asinhm arcoseno hiperbólico da matriz matriz arcoseno hiperbólico tasinhmx Parâmetros xt matriz quadrada de reais ou complexos Descrição asinhm é o arcoseno hiperbólico da matriz x matriz arcoseno hiperbólico de x Usa a fórmula tlogmxsqrtmxxeye Os resultados podem ser imprecisos se a matriz é não simétrica Exemplos A1223 sinhmasinhmA Ver Também asinh logm sqrtm 226 Name asinm arcoseno da matriz matriz arcoseno tasinmx Parâmetros x matriz quadrada de reais ou complexos t matriz quadrada de reais ou complexos Descrição t é o arcoseno da matriz x matrix matriz arcoseno de x É usado o método da diagonalização Para matrizes nãosimétricas o resultado pode ser impreciso Exemplos A1234 sinmasinmA asinmAilogmiAsqrtmeyeAA Ver Também asin sinm 227 Name atan arcotangente 2quadrantes e 4quadrantes phiatanx phiatanyx Parâmetros x escalar real ou complexo ou vetor ou matriz de reais ou complexos phi escalar real ou complexo ou vetor ou matriz de reais ou complexos x y escalares real ou vetores ou matrizes de reais de mesmo tamanho phi escalar real ou vetor ou matriz de reais Descrição A primeira forma computa o arcotangente 2quadrantes que é o inverso de tanphi Para um real x phi está no intervalo pi2 pi2 Para um complexo x atan tem dois pontos de ramificação singulares ii e os ramos escolhidos são as duas semiretas imaginárias i ioo e ioo i A segunda forma computa o arcotangente 4quadrantes atan2 em FORTRAN isto é retorna o ar gumento ângulo do número complexo xiy A imagem de atanyx é pi pi Para argumentos reais ambas as formas produzem valores idênticos se x0 No caso de os argumentos serem vetores ou matrizes a avaliação é feita elemento a elemento de modo que phi é um vetor ou matriz com o mesmo tamanho de phiijatanxij ou phiijtanyijxij Exemplos exemplos com a segunda forma x1i1i phasexatanimagxrealx atan01 ataneps1 ramos ataneps 2i ataneps 2i ataneps 2i ataneps 2i valores nos pontos de ramificação ieee2 atani atani atan 228 Ver Também tan ieee Autores BP LVD autores da função atan para complexos 229 Name atand arcostangentes 2quadrantes e 4quadrantes elemento a elemento do argumento com resul tados em graus phiatandx phiatandyx Parâmetros x escalar vetor ou matriz de reais phi escalar vetor ou matriz de reais x y escalare vetore ou matrizes de reais com tamanhos iguais phi escalar vetor ou matriz de reais Descrição A primeira forma computa o arcotangente 2quadrantes que é o inverso de tandphi Os ele mentos de phi estão no intervalo 90 90 A primeira forma computa o arcotangente 4quadrantes atan2 em Fortran isto é retorna o argu mento ângulo do número complexo xiy A imagem de atandyx é 180180i Ambas as formas são idênticas se x0 Exemplos exemplo com a segunda forma x01sqrt31sqrt3inf0 atandx Ver Também tan tand Autor Serge Steer INRIA 230 Name atanh arcotangente hiperbólico tatanhx Parâmetros x matriz ou vetor de reais ou complexos t matriz ou vetor de reais ou complexos Descrição Os compontente do vetor t são os arcostangentes hiperbólicos das entradas correspondentes em x O domínio de definição é 11 para a função real ver Observação Observação No Scilab como em alguns outros softwares numéricos quando se tenta avaliar uma função matemática elementar fora de seu domínio de definição no caso real uma extensão complexa é usa da com resultado complexo O exemplo mais famoso é a função sqrt tente sqrt1 Es ta aproximação tem algumas desvantagens quando você avalia a função em um ponto singular que pode levar a diferentes resultados quando o ponto é considerado como real ou complexo Para a função atanh isto ocorre para 1 e 1 porque nestes pontos a parte imaginária não converge e então atanh1 Inf i NaN enquanto atanh1 Inf para o caso real como lim x1 de atanhx Então quando você avaliar esta função no vetor 1 2 como 2 está fora do domínio de definição a extensão complexa é usada para todo o vetor e o resultado de atanh1 Inf i NaN enquanto o resultado de atanh1 Inf com 1 05 por exemplo Exemplos exemplo 1 x0ii tanhatanhx exemplo 2 x inf 3 2 1 0 1 2 3 inf ieee2 atanhtanhx exemplo 3 ver Observação ieee2 atanh1 2 atanh1 05 Ver Também tanh ieee 231 Name atanhm Arcotangente hiperbólico da matriz matriz arcotangente hiperbólico tatanhmx Parâmetros x matriz quadrada de reais ou complexos t matriz quadrada de reais ou complexos Descrição atanhmx é o arcotangente hiperbólico da matriz x matriz arcotangente hiperbólico O resul tado pode ser impreciso se x não é simétrica Exemplos A1234 tanhmatanhmA Ver Também atanh tanhm 232 Name atanm arcotangente da matriz quadrada matriz arcotangente tatanmx Parâmetros x matriz de reais ou complexos quadrada t matriz de reais ou complexos quadrada Descrição atanmx é o arcotangente da matriz x matrtiz arcotangente de x O resultado pode ser impreciso se x não é simétrica Exemplos tanmatanm1234 Ver Também atan 233 Name base2dec conversão da base b para inteiros dbase2decsb Parâmetros d matriz de inteiros s matriz de strings correspondentes às representações em base b b inteiro a base Descrição base2decxb retorna a matriz de número correspondentes à representação em base b Exemplos base2decABC0A16 Ver Também bin2dec oct2dec hex2dec dec2bin dec2oct dec2hex 234 Name bin2dec conversão de representação binária para inteira ybin2decstr Parâmetros str um string ou vetormatriz de strings contendo apenas caracteres 1 e 0 y um escalar ou um vetormatriz de inteiros positivos Descrição Dado str um string binário está função retorna y o número decimal cuja representação binária é dada por str y e str possuem o mesmo tamanho Exemplos example 1 1010110 é a representação binária de 86 str1010110 ybin2decstr example 2 1011011 é a representação binária de 91 1010010 é a representação binária de 82 str1011011 1010010 ybin2decstr Ver Também base2dec oct2dec hex2dec dec2bin dec2oct dec2hex 235 Name binomial probabilidades de distribuição binomial prbinomialpn Parâmetros pr vetor linha com n1 componentes p número real em 01 n um inteiro 1 Descrição prbinomialpn retorna o vetor de probabilidade binomial ie prk1 é a probabilidade de k successos em n tentativas independentes de Bernoulli com probabilidade de sucesso p Em outras palavras prk1 probabilityXk com X uma variável aleatória segundo a distribuição Bnp e numericamente n k nk n n prk1 p 1p com k k k nk Exemplos primeiro exemplo n10p03 xbasc plot2d30nbinomialpn segundo exemplo n50p04 meanp sigmasqrtnp1p x 0nmea sigma xbasc plot2dx sigmabinomialpn deffyGaussxy1sqrt2piexpx22 plot2dx Gaussx style2 pela fórmula binomial cuidado se n for grande function prbinomial2pn xpoly0xprcoeff1pxnhornerx0np endfunction p13n5 binomialpnbinomial2pn pela função gama gamman1n cuidado se n for grande p13n5 Cnksgamman1gamma1n1gamman111 xpoly0x prCnkshornerx0n1xn10p binomial 236 prbinomialpn Ver Também cdfbin grand 237 Name bitand AND e aplicado às representações binárias dos argumentos de entrada zbitandxy Parâmetros x escalarvetormatrizhipermatriz de inteiros positivos y escalarvetormatrizhipermatriz de inteiros positivos z escalarvetormatrizhipermatriz de inteiros positivos Descrição Dado x e y dois inteiros positivos esta função retorna z o número decimal cuja forma binária é o AND das representações binárias de x e y x y e z devem ter o mesmo tamanho Se a dimensão de x e y é superior a 1 então zi é igual a bitandxiyi Exemplos exemplo 1 1010110 é a representação binária de 86 1011011 é a representação binária de 91 1010010 é a representação binária para AND aplicado às formas binárias de 86 e 91 então o número decimal correspondente a AND aplicado às formas binárias de 86 and 91 is 82 x86 y91 zbitandxy exemplo 2 x1245y2549 zbitandxy Ver Também bitor bin2dec dec2bin 238 Name bitor OR ou aplicado às representações binárias dos argumentos de entrada zbitorxy Parâmetros x escalarvetormatrizhipermatriz de inteiros positivos y escalarvetormatrizhipermatriz de inteiros positivos z escalarvetormatrizhipermatriz de inteiros positivos Descrição Dado x e y dois inteiros positivos esta função retorna z o número decimal cuja forma binária é o OR das representações binárias de x e y x y e z devem ter o mesmo tamanho Se a dimensão de x é superior a 1 então zi é igual a bitorxiyi Exemplos exemplo 1 110000 é a representação binária de 48 100101 é a representação binária de 37 110101 é a representação binária para OR aplicado às formas binárias de 48 e 37 então o número decimal correspondente a OR aplicado às formas binárias de 48 e 37 é 53 x48 y37 zbitorxy exemplo 2 x1245 y2549 zbitorxy Ver Também bitand bin2dec dec2bin 239 Name bloc2exp retorna a avaliação simbólica de um diagrama de blocos strbloc2expblocd strnamesbloc2expblocd Parâmetros blocd lista str string names string Descrição Dada uma representação em diagrama de blocos de um sistema linear bloc2exp retorna sua avaliação simbólica O primeiro elemento da lista blocd deve ser o string cadeia de caracteres blocd Cada outro elemento desta lista blocd2blocd3 é por si mesmo uma lista de um dos seguintes tipos listtransfernomedosistemalinear listlinknomedaligação númerodecaixadefluxosuperiorportadacaixadefluxosuperior caixadefluxoinferior1númerodeportadacaixainferior1 caixadefluxoinferior2númerodeportadacaixainferior2 Os strings transfer e links são palavraschaves as quais indicam o tipo de elemento no diagrama de blocos transfertransferência link ligação Caso 1 o segundo parâmetro da lista é um string que pode se referir para uma possível avaliação posterior ao nome Scilab de um sistema linear dado em representação de estadoespaço lista sys lin ou em forma de trasnferência matriz de razões de polinômios A cada bloco de transferência é associado um inteiro A cada entrada e saída de um bloco de transferência também é associado seu número um inteiro ver exemplos Caso 2 O segundo tipo de elemento em uma representação de diagrama de blo cos é um link Um link liga uma saída de um bloco representado pelo par númerodecaixadefluxosuperiorportadacaixadefluxosuperior a diferentes entradas de outros blocos Cada tal entrada é representada pelo par caixadefluxoinferiorinúmerodeportadacaixainferiori Os diferentes elementos de um diagrama de blocos podem ser definidos em ordem arbitrária Por exemplo 1 S1S2 com feedback resposta de unidade bloc2exp 240 Há 3 transferências S1 número ns12 S2 número ns23 e um adicionador adder número nadd4 com função de transferência simbólica 11 Há 4 ligações O primeiro de nome U liga a entrada porta 0 de bloco fictício 1 omitido à porta 1 do adicionador Os segundo e terceiro ligam respectivamente a porta de saída 1 do adicionador à porta de entrada 1 do sistema S1 e a porta de saída 1 de S1 à porta de entrada 1 de S2 A quarta ligação de nome Y liga a porta de saída 1 de S2 à saída porta 0 do bloco fictício 1 omitido e à porta de entrada 2 do adicionador Inicialização systlistblocd l1 Sistemas ll1ns1lsystllisttransferS1 Sistema 1 ll1ns2lsystllisttransferS2 Sistema 2 ll1nadderlsystllisttransfer11 adicionador Links Entradas 1 entrada 1 ll1systllistlinkU1nadder1 Internal ll1systllistlink nadder1ns11 ll1systllistlink ns11ns21 Saídas 1 saída 1 ll1systllistlinkYns211nadder2 Chamada de avaliação wbloc2expsyst O resultado é o string ws2s1eyes2s1 Perceba que chamado com dois agumentos de saída strnames blocdsyst retorna em names a lista de nomes simbólicos dos links nomeados Isto é útil para definir nomes de entradas e saídas 2 segundo exemplo Inicialização systlistblocd l1 Sistema planta de blocos 2x2 ll1nslsystllisttransferP11P12P21P22 Controlador ll1nklsystllisttransferk Links ll1systllistlinkw1ns1 ll1systllistlinkzns11 ll1systllistlinkunk1ns2 ll1systllistlinkyns2nk1 Chamada de avaliação wbloc2expsyst Neste caso o resultado é uma fórmula equivalente à usual bloc2exp 241 P11P12invreyeKP22KP21 Ver Também bloc2ss Autores S S F D INRIA 242 Name bloc2ss conversão de diagrama de blocos para espaço de estados slbloc2ssblocd Parâmetros blocd lista sl lista Descrição Dada uma representação em diagrama de blocos de um sistema linear bloc2ss converte esta representação em um sistema linear de espaço de estados O primeiro elemento da lista blocd deve ser o string cadeia de caracteres blocd Cada outro elemento desta lista é por si mesmo uma lista de um dos seguintes tipos listtransfernomedosistemalinear listlinknomedolink númerodecaixadefluxosuperiorportadacaixadefluxosuperior caixadefluxoinferior1númerodeportadacaixainferior1 caixadefluxoinferior2númerodeportadacaixainferior2 Os strings transfer e links são palavraschaves as quais indicam o tipo de elemento no diagrama de blocos transfertransferência link ligação Caso 1 o segundo parâmetro da lista é um string que pode se referir para uma possível avaliação posterior ao nome Scilab de um sistema linear dado em representação de espaço de estados lista syslin ou em forma de trasnferência matriz de razões de polinômios A cada bloco de transferência é associado um inteiro A cada entrada e saida de um bloco de transferência também é associado seu número um inteiro ver exemplos Caso 2 O segundo tipo de elemento em uma representação de diagrama de blo cos é um link Um link liga uma saída de um bloco representado pelo par númerodecaixadefluxosuperiorportadacaixadefluxosuperior a diferentes entradas de outros blocos Cada tal entrada é representada pelo par caixadefluxoinferiorinúmerodeportadacaixainferiori Os diferentes elementos de um diagrama de blocos podem ser definidos em ordem arbitrária Por exmeplo 1 S1S2 com feedback resposta de unidade Há 3 transferências S1 número ns12 S2 número ns23 e um adicionador adder número nadd4 com função de transferência simbólica 11 Há 4 links O primeiro de nome U liga a entrada porta 0 de bloco fictício 1 omitido à porta 1 do adicionador Os segundo e terceiro ligam respectivamente a porta de saída 1 do adicionador à bloc2ss 243 porta de entrada 1 do sistema S1 e a porta de saída 1 de S1 à porta de entrada 1 de S2 O quarto link de nome Y liga a porta de saída 1 de S2 à saída porta 0 do bloco fictício 1 omitido e à porta de entrada 2 do adicionador Inicialização systlistblocd l1 Sistemas ll1ns1lsystllisttransferS1 Sistema 1 ll1ns2lsystllisttransferS2 Sistema 2 ll1nadderlsystllisttransfer11 adicionador Links Entradas 1 entrada 1 ll1systllistlinkU11nadder1 Internal ll1systllistlink nadder1ns11 ll1systllistlink ns11ns21 Saídas 1 saída 1 ll1systllistlinkYns211nadder2 Com spoly0sS11s1S21s o resultado da avaliação de chamada slbloc2sssyst é uma representação em estadoespaço para 1s2s1 2 exemplo da transformação linear fracional TLF e em inglês LFT Inicialização systlistblocd l1 Sistema planta de blocos 2x2 ll1nslsystllisttransferP11P12P21P22 Controlador ll1nklsystllisttransferk Links ll1systllistlinkw1ns1 ll1systllistlinkzns11 ll1systllistlinkunk1ns2 ll1systllistlinkyns2nk1 Com PsyslincABCD P11P11 P12P12 P21P21 P22P22 KsyslincAkBkCkDk bloc2expsyst retorna a avaliação de TLF de P e K bloc2ss 244 Ver Também bloc2exp Autores S S F D INRIA 245 Name cat concatena vários arrays ycatdimsA1A2An Parâmetros dims um escalar real positivo A1A2An escalares vetores matrizes multiarrays ou cell arrays A1 A2 An devem ter o mesmo taman ho excluindo o número de dimensão dims sizeA1isizeA2isizeAni para i diferente de dims e sizeA1dims sizeA2dimssizeAndims podem ser diferentes y um escalar vetor matriz ou multiarray y tem o mesmo tipo de A1A2An Descrição ycatdimsA1A2An y é o resutado da concatenação dos argumentos de entrada A1 A2 An Se dims 1 então a concatenação é feita de acordo com as linhas se dims 2 então a concatenação é feita de acordo com as colunas dos argumentos de entrada Se dims 1então a concatenação é feita de acordo com as linhas A11 2 3 4 5 6 A27 8 9 10 11 12 ycat1A1A2 y1 2 3 4 5 61 7 8 9 10 11 12 Se dims 2então a concatenação é feita de acordo com as colunas dos argumentos de entrada A11 2 34 5 6 A27 8 9 10 11 12 ycat2A1A2 y1 2 3 7 8 9 4 5 6 10 11 12 Exemplos primeiro exemplo concatenação de acordo com as linhas dims1 A11 2 3 A24 5 6 7 8 9 A310 11 12 ycatdimsA1A2A3 segundo exemplo concatenação de acordo com as colunas dims2 A11 2 3 A24 57 89 10 ycatdimsA1A2 terceiro exemplo concatenação de acordo com a terceira dimensão dims3 A1matrix112223 A213 1415 16 A3matrix2136224 ycatdimsA1A2A3 Ver Também permute matrix Autor Farid Belahcene 246 Name ceil arredonda o número para o inteiro maior ou igual ao número yceilx Parâmetros x uma matriz de reais y uma matriz de inteiros Descrição ceilx retorna uma matriz de inteiros feita de arredondamentos para cima dos elementos Exemplos ceil19 2522 ceilinf xrand1020ceilxx Ver Também round floor int 247 Name cell2mat converte um cell array array de células em uma matriz xcell2matc Parâmetros c cell os componentes de c devem ter o mesmo tipo e podem ser escalares ou matrizes x matriz Descrição Retorna uma matriz que é a concatenação de todos os componentes do cell célula c cell2matc todos os componentes de c devem ter o mesmo tipo de dado string doubles inteiros ou booleanos Para cada linha i de c cell2mat concatena todos os componentes da iésima linha do cell c Perceba que se os componentes da entrada do cell c são são strings então cell2matc retorna um vetorcoluna de concatenação de strings Exemplos cmakecell221 2 3 6 7 84 59 1011 1216 1714 13 1518 19 20 cell2matc Ver Também cell 248 Name cellstr converte um vetor ou matriz de strings em um cell de strings ccellstrs Parâmetros s vetor de strings ou matriz de strings Descrição Retorna um cell array de strings Se s ié um vetor linha de strings então cellstrs retorna um cell umporum que contém um componente a concatenação de todas as colunas componentes de s Se s é um vetor coluna de strings então cellstrs converte s em um cell que tem o mesmo tamanho cell de strings sizes1porum Se s é uma matriz de strings então para cada linha i de s cellstrs concatena todos os componentes da iésima linha da matriz s ie si1 si2 si3 e retorna um cell de strings sizes1porum Exemplos cellstrfoo cellstrscilab cellstrabcdefghijklm Ver Também cell string 249 Name char função char ychar x ycharst1st2st3 Parâmetros x um cell de arrays de strings ou um array de códigos ASCII st1st2st3 arrays de strings y vetor coluna de strings Descrição Argumento de uma entrada Dado um cell de arrays de strings x esta função retorna um vetor de strings y no qual as linhas são componentes do cell de strings Dado um array de códigos ASCII x esta função retorna um array de strings y corre spondente aos códigos ASCII Se dims xn1n2n3n4 então o valor retornado tem o mesmo tamanho que o valor de entrada ao invés do segundo dims dimsyn1n3n4 Argumento de mais de uma entrada Dados arrays de strings st1st2st3 esta função retorna um vetor de strings no qual as linhas são os componentes de st1st2st3 No vetor y o comprimento de todos os strings sti é completado por lacunas para terem o mesmo comprimento que o comprimento máximo de sti Exemplos exemplo com uma hipermatriz de códigos ASCII xhypermat4236184 ycharx sizex sizey Exemplo com mais de um argumento st1zeros st2onetwo st3three ycharst1st2st3 sizey todos os strings são completados por lacunas para terem o mesmo comprimento 6 lengthy Ver Também asciimat Autor FB 251 Name conj matriz conjugada yconjx Parâmetros xy matrizes de reais ou complexos Descrição conjx é a matriz conjugada complexa de x Exemplos x1iii2i conjx xconjx x é a matriz transposta conjugada 252 Name cos função coseno ycosx Parâmetros x matriz ou vetor de reais ou complexos Descrição Para uma matriz ou vetor cosx é o coseno de seus elementos Para o coseno da matriz matriz coseno use a função cosmX Exemplos x01i acoscosx Ver Também cosm 253 Name cosd função coseno elemento a elemento argumento dado em graus ycosdx Parâmetros x vetormatriz de reais Descrição Para um vetor ou uma matriz x de ângulos dados em graus cosdx é o coseno de seus elementos Os resultados estão em 1 1 Para elementos de entrada que são iguais a n90 com n inteiro e ímpar o resultado é exatamento zero Exemplos x030 45 60 90 360 cosdx Ver Também cos Autor Serge Steer INRIA 254 Name cosh coseno hiperbólico tcoshx Parâmetros xt matriz ou vetor de reais ou complexos Descrição Os elementos de t são os cosenos hiperbólicos da entradas correspondentes do vetor x Exemplos x01i acoshcoshx Ver Também cos acosh 255 Name coshm coseno hiperbólico da matriz matriz coseno hiperbólico tcoshmx Parâmetros xt matriz quadrada de reais ou complexos Descrição coshm é o coseno hiperbólico da matriz x matriz coseno hiperbólico de x texpmxexpm x2 O resultado pode ser impreciso para matrizes nãosimétricas Exemplos A1224 acoshmcoshmA Ver Também cosh expm 256 Name cosm coseno da matriz matriz coseno tcosmx Parâmetros x matriz quadrada de reais ou complexos Descrição cosmx é o coseno da matriz x matriz coseno de x t05expmixexpm ix Exemplos A1234 cosmA05expmiAexpmiA Ver Também cos expm 257 Name cotd cotangent elemento a elemento do argumento dado em graus ycotdx Parâmetros x array de reais y array de reais com as mesmas dimensões que x Descrição As entradas y são as cotangentes das entradas correspondentes de x supostamente dadas em graus tcosxsinx Para entradas iguais a n180 com n inteiro os resultados são infinitos en quanto que com cotgnpi o resultado é grande pois pi não pode ser representado exata mente para entradas iguais a n90 com n inteiro e ímpar o resultado é exatamente 0 Exemplos x30 45 60 90 cotdx Ver Também cotg Autor Serge Steer INRIA 258 Name cotg cotangente tcotgx Parâmetros xt vetores ou matrizes de reais ou complexos Descrição Os elementos de t são as cotangentes das entradas correspondentes de x tcosxsinx Exemplos x1i cotgxcosxsinx Ver Também tan 259 Name coth cotangente hiperbólica tcothx Descrição Os elementos do vetor t são as cotangentes hiperbólicas dos elementos do vetor x Exemplos x12i texpx tonesxttonesxt cothx Ver Também cotg 260 Name cothm cotangente hiperbólica da matriz matriz cotangente hiperbólica tcothmx Descrição cothmx é a matriz contangente hiperbólica da matriz quadrada x Exemplos A1234 cothmA Ver Também coth 261 Name csc computa a cossecante do argumento elemento a elemento y cscx Parâmetros x array de reais ou complexos y array de reais ou complexos com as mesmas dimensões que x Description Computa a cossecante do argumento elemento a elemento A função cossecante é uma função periódica definida como 1sin Para dados reais os resultados são reais em inf 1 U 1 inf Exemplos xlinspace001pi001200 clfplotxcscxxcscx Ver Também sec cscd Autor Serge Steer INRIA 262 Name cscd computa a cossecante elemento a elemento do argumento em graus x cscdx Parâmetros x array de reais ou complexos x array de reais ou complexos Descrição As emtradas de y são as cossecantes 1sin das entradas de x dadas em graus Os resultados são reais em inf 1 U 1 inf Para entradas iguais a n180 com n inteiro o resultado é infinito ou um erro dependendo do modo ieee Para entradas iguais a n90 com n inteiro e ímpar o resultado é exatamente 1 ou 1 Exemplos cscpi4 cscd90 Ver Também secd csc sind Autor Serge Steer INRIA 263 Name csch computa a cossecante hipertbólica do argumento elemento a elemento y cschx Parâmetros x array de reais ou complexos y array de reais ou complexos com as mesmas dimensões que x Descrição Computa a cossecante hipertbólica do argumento elemento a elemento Para dados reais os resultados são reais Exemplos xlinspace0014200xx11 nan x clfplotxcschx Ver Também csc acsch Autor Serge Steer INRIA 264 Name cumprod produto cumulativo ycumprodx ycumprodxr ou ycumprodx1 ycumprodxc ou ycumprodx2 ycumprodxm Parâmetros x vetor ou matriz de reais ou complexos y vetor ou matriz de reais ou complexos Descrição Para um vetor ou matriz x ycumprodx retorna em y o produto cumulativo de todas as entradas de x tomadas coluna a coluna ycumprodxc ou equivalentemente ycumprodx2 retorna em y o produto cumu lativo dos elementos das colunas de x yicumprodxi ycumprodxr ou equivalentemente ycumprodx2 retorna em y o produto cumu lativo dos elementos das linhas de x yicumprodxi ycumprodxm é o produto cumulativo ao longo da primeira dimensão nãosingleton de x para compatibilidade com Matlab Exemplos A1234 cumprodA cumprodAr cumprodAc randseed0 arand34 mnsizea wzerosa w1a1 for k2mwkwk1akendwcumprodar Ver Também cumsum sum prod 265 Name cumsum soma cumulativa ycumsumx ycumsumxr or ycumsumx1 ycumsumxc or ycumsumx2 Parâmetros x vetor ou matrix de reais ou complexos y vetor ou matrix de reais ou complexos Descrição Para um vetor ou uma matriz x ycumsumx retorna em y a soma cumulativa de todas as entradas de x tomadas coluna a coluna ycumsumxc ou equivalentemente ycumsumx2 retorna em y a soma cumulativa das colunas de x yicumsumxi ycumsumxr ou equivalentemente ycumsumx1 retorna em y a soma cumulativa das linhas de x yicumsumxi ycumsumxm é a soma cumulativa ao longo da primeira dimensão nãosingleton de x para compatibilidade com o Matlab Exemplos A1234 cumsumA cumsumAr cumsumAc arand34i mnsizea wzerosa w1a1 for k2mwkwk1akendwcumsumar Ver Também cumprod sum 266 Name dec2bin representação binária strdec2binxn Parâmetros x escalarvetormatrizhypermatriz de inteiros positivos n um inteiro positivo str um string ou vetor de strings Descrição Dado x um inteiro ou um vetormatriz de inteiros positivo esta função retorna um string ou um vetor coluna de strings que é a representação binária de x Se a dimensão de x é superior a 1 então cada componente do vetor coluna str é a representação binária dos componentes de x ie stri é a representação binária de xi Se o comprimento dos componentes de str é menor que n ie length stri n então adicione aos componentes de str os caracteres 0 à esquerda para se obter o comprimento dos componentes igual a n Exemplos exemplo 1 x86 strdec2binx exemplo 2 a representação binária de 86 é 1010110 seu comprimento é 7menor que n então temos adicionamos a str 8 vezes o caracteres 0 à esquerda x86n15 strdec2binxn exemplo 3 x1245135 zdec2binx Ver Também base2dec bin2dec oct2dec hex2dec dec2oct dec2hex 267 Name dec2hex representação hexadecimal de inteiros hdec2hexd Parâmetros d matriz de inteiros nãonegativos h matriz de strings Descrição dec2hexx retorna a representação hexadecimal de uma matriz de inteiros Exemplos dec2hex2748 1011 3 Ver Também base2dec bin2dec oct2dec hex2dec dec2bin dec2oct 268 Name dec2oct representação octal de inteiros odec2octd Parâmetros d matriz de inteiros nãonegativos o matriz de strings Descrição dec2octx retorna a representação octal de uma matriz de inteiros Exemplos dec2oct2748 1011 3 Ver Também base2dec bin2dec oct2dec hex2dec dec2bin dec2hex 269 Name delip Integral elíptica rdelipxck Parâmetros x vetor real com elementos nãonegativos ck número real entre 1 e 1 r número real ou complexo ou vetor de reais ou complexos com mesmo tamanho que x Descrição A integral elíptica de primeira espécie com parâmetro ck definido como segue Onde x é real e positivo e ck está em 1 1 Se x é menor do que ou igual a 1 o resultado é real Quando chamado com x um vetor real r é avaliado para cada entrada de x Exemplos ck05 delip12ck deffyfty1sqrt1t21ck2t2 intg01f OK desde que a solução seja real Ver Também amell asn sn 270 Name diag inclusão ou extração diagonal ydiagvm k Parâmetros vm vetor ou matriz armazenamento cheio ou esparso k inteiro o valor padrão é 0 y vetor ou matriz Descrição Para um nvetor linha ou coluna vm diagvm retorna uma matriz diagonal com entradas de vm ao longo da diagonal principal diagvmk é uma matriz nabskxnabsk com entradas de vm ao longo da késima diagonal k0 é a diagonal principal k0 são as diagonais superiores e k0 são as diagonais infe riores Para uma matriz vm diagvmk é o vetor coluna feito das entradas da késima diagonal de vm diagvm é a diagonal principal de vm diagdiagx é a matriz diagonal Se vm é uma matriz esparsa diagvmk retorna uma matriz esparsa Para construir um sistema linear diagonal use sysdiag Perceba que eyeAA retorna uma matriz diagonal feita das entradas diagonais de A Isto é válido para qualquer matriz constante de polinômios de razões de polinômios sistema linear em espaço de estados Exemplos diag12 A1234 diagA diagonal principal diagA1 diagsparse110 matriz diagonal esparsa forma de uma matriz triadiagonal de tamanho 2m1 m5diagmm diagones2m11 diagones2m11 Ver Também sysdiag sparse 271 Name diff diferença e derivada discreta ydiffx ydiffx n dim Parâmetros x vetor ou matriz de reais complexos esparsoa ou de polinômios n inteiro ordem da diferenciação dim inteiro ou cadeia de caracteres com valores rc e y escalar ou vetor Descrição ydiffx computa a função de diferença yx2x11 diffxndim é a nésima função de diferença ao longo da dimensão dim diffxn é equivalente a diffxn O valor padrão para n é 1 O valor padrão para dim é dimr é equivalente a dim1 e dimc é equivalente a dim2 Exemplos v183 diffv diffv3 A182 183 184 diffA32 diferenciação aproximada step0001 t0step10 ysint dydiffsintstep diferenciação aproximada da função seno normdycost11inf 272 Name double conversão de inteiro para representação de dupla precisão ydoubleX yint16X yint32X yuint8X yuint16X yuint32X Parâmetros X matriz de números em ponto flutuante ou inteiros y matriz de números em ponto flutuante Descrição Converte os dados armazenados usando inteiros de 1 2 ou 4 bytes em representação de ponto flutuante de dupla precisão Se as entradas de X já são números de ponto flutuante de dupla precisão nada é feito Exemplos xint80 12 140 doublex Ver Também int8 inttype type 273 Name dsearch Busca binária também conhecida como busca dicótoma em francês ind occ info dsearchX val ch Parâmetros X um vetor ou matriz de reais val um vetor linha ou coluna de reais com n componentes em ordem estritamente crescente val1 val2 valn ch opcional um caractere c ou d valor padrão c ind um vetor ou matriz de reais com as mesmas dimensões que X occ um vetor de reais com o mesmo formato que val mas com n1 componentes no caso em que chc info inteiro Descrição Esta função é útil para encontrar em uma tabela table ordenada eou contar o número de compo nentes de um vetor caindo em algumas classes sendo uma classe um intervalo ou um valor Por padrão ou quando chc temos o caso de intervalos isto é para cada Xi busca em qual dos n1 intervalos o componente do vetor cai sendo os intervalos definidos por I1 val1 val2 Ik valk valk1 for 1 k n1 e indi é o número do intervalo de Xi 0 se Xi não está em val1valn occk é o número de componentes de X que estão em Ik info é o número de componentes de X que não estão em val1valn Quando chd temos o caso discreto isto é para cada Xi busca se é igual a um valor valk e indi é igual ao índice do componente de val que corresponde a Xi indi k se Xivalk ou 0 se Xi não está em val dsearch 274 occk é igual ao número de componentes de X iguais a valk info é o número de componentes de X que não estão no conjunto val1valn Exemplos exemplo 1 estatística elementar para U01 m 50000 n 10 X grandm1def val linspace01n1 ind occ dsearchX val xbasc plot2d2val occm0 sem normalização y deve ser próximo de 1n exemplo 2 estatística elementar para BNp N 8 p 05 m 50000 X grandm1binNp val 0N ind occ dsearchX val d Pexp occm Pexa binomialpN xbasc hm 11maxmaxPexamaxPexp plot2d3val val01 Pexa Pexp1 2111 PexactPexp 1 0 N1 hm0 N2 0 6 xtitle Distribuição binomial BstringNstringp probabilidades exatas versus as experimentais exemplo 3 polinômio de Hermite seccionado x 0 02 035 05 065 08 1 y 0 01 01 0 04 01 0 d 1 0 0 1 0 0 1 X linspace0 1 200 ind dsearchX x definindo funções bases hermitianas deffyLltkxytxk1xkxk1 Lagrange esquerdo em Ik deffyLrtkxytxkxk1xk Lagrange direito em Ik deffyHltkxy12txkxkxk1Lltkx2 deffyHrtkxy12txk1xk1xkLrtkx2 deffyKltkxytxkLltkx2 deffyKrtkxytxk1Lrtkx2 plotando a curva Y yindHlXind yind1HrXind dindKlXind dind1KrXind xbasc plot2dXY2 plot2dxy9000 xtitleUm polinômio seccionado de hermite NOTE a verificação pode ser feita adicionandose YY interpXxyd plot2dXYY3000 Ver Também find tabul Autor BP 275 Name eval avaliação de uma matriz de strings H evalZ Descrição Retorna a avaliação da matriz de strings Z Exemplos a1 b2 Zasinb evalZ retorna a matriz 10909 Ver Também evstr execstr 276 Name exp exponencial em relação aos elementos expX Parâmetros X escalar vetor ou matriz de entradas reais ou complexas Descrição expX é a função exponencial elemento a elemento das entradas deX Exemplos x123i logexpx elemento a elemento 2x expxlog2 Ver Também coff log expm 277 Name eye matriz identidade Xeyemn XeyeA Xeye Parâmetros AX matrizes ou listas syslin mn inteiros Descrição Define uma matriz mxn com 1s ao longo de sua diagonal ou uma matriz identidade com as mesmas dimensões de A Cuidado eye10 é interpretado como eyeA com A10 ie 1 NÃO é uma matriz identidade 10 x 10 Se A é um sistema linear representado por uma lista syslin eyeA retorna uma matriz eye com dimensões apropriadas número de saídas x número de entradas eye produz uma matriz identidade com dimensões indefinidas As dimensões serão definidas quan do esta matriz identidade for adicionada a uma matriz com dimensões fixas Exemplos eye23 Arand23eyeA spoly0sAs1ss1eyeA A1s1s2eyeA Assrand223eyeA 1 23 42eye Ver Também ones zeros 278 Name factor fatoração yfactorx Parâmetros x escalar real y vetor de números primos Descrição Dado um real x factorx retorna em um vetor y a decomposição em números primos de x Caso particular factor0 retorna 0 e factor1 retorna 1 Exemplos x620 yfactorx Ver Também primes 279 Name fix arredonda em direção a zero yfixx Parâmetros x uma matriz de reais y uma matriz de inteiros Descrição fixx retorna uma matriz de inteiros feita de arredondamentos em direção a zero ie ysignxfloorabsx É o mesmo que int Ver Também round floor ceil 280 Name flipdim gira os componentes de x ao longo de uma dada dimensão yflipdimxdim Parâmetros x um escalar vetor ou array de reais dim um inteiro positivo y um escalar vetor ou array de reais Descrição Dado x um escalarvetorarray de reais e dim um inteiro positivo esta função gira os componentes de x ao longo da dimensão de número dim de x x e y têm o mesmo tamanho Exemplos exemplo 1 girando os componentes de x ao longo da primeira dimensão x1 2 3 4 5 6 7 8 dim1 yflipdimxdim exemplo 1 girando os componentes de x ao longo da segunda dimensão dim2 yflipdimxdim exemplo e girando os componentes de x ao longo da terceira dimensão xmatrix1483 242 dim3 yflipdimxdim Ver Também FBelahcene 281 Name floor arredondamento para o inteiro menor ou igual ao número yfloorx Parâmetros x matriz de reais y matriz de inteiros Descrição floorx retorna uma matriz de inteiros feita a partir de arredondamentos para baixo Exemplos floor19 2513 floorinf xrand1020floorxx Ver Também round fix ceil 282 Name frexp separa um número em ponto flutuante em potência de base 2 e mantissa fefrexpx Parâmetros x vetor ou matriz de reais f array de valores reais geralmente no intervalo 05 absf 1 e array de inteiros que satisfazem a equação x f2e Descrição Esta função corresponde à função ANSI C frexp Quaisquer zeros em x produzem f0 e e0 Exemplos fefrexp1pi3eps Ver Também log hat ieee log2 283 Name gsort ordenação decrescente s kgsortv s kgsortvflag1 s kgsortvflag1flag2 Parâmetros vs vetor ou matriz de reais inteiros ou strings ou sparse vector flag1 um string r cglr ou lc flag2 um string i para ordem crescente ou d para ordem decrescente k vetor ou matriz de inteiros Descrição gsort é semelhante a sort com propriedades adicionais O terceiro argumento pode ser usado para escolher ordem crescente ou decrescente O segundo argumento podem ser usado para ordens léxicas skgsortag e skgsortagd são o mesmo que skgsorta Eles realizam uma ordenação das entradas da matriz a a sendo vista como vetor de pilhas a coluna a coluna skgsortagi realiza a mesma operação mas em ordem crescente skgsortalr ordena as linhas da matriz a em ordem léxica decrescente s é obtida por uma permutação das linhas da matriz a dada pelo vetor coluna k de tal modo que as linhas de s verificam si sj se ij skgsortalri realiza a mesma operação mas em ordem léxica crescente skgsortalc ordena as colunas da matriz a em ordem léxica decrescente s é obtida por uma permutação das colunas da matriz inta ou a dada pelo vetor linha k ide tal modo que as colunas de s verificam si sj se ij skgsortalci realiza a mesma operação mas em ordem léxica crescente Quando v é complexo os elementos são ordenados pela magnitude ie absv Apenas g como segundo argumento funciona com complexos Se v tem elementos nan ou inf gsort coloca esses elementos no início com o argumento i ou ao fim com o argumento d Exemplos alr122 121 112 111 alr1kgsortalrlri alr1kgsortalrlci vint32alr gsortv gsort 284 gsortvlri gsortvlci vScilab 26 Scilab 27 Scicos 27 Scilab 31 Scicos 31 Scicos 40 Scilab 40 gsortvlri gsortvlci Ver Também find Bibliografia Algoritmo Quicksort 285 Name hex2dec conversão de representação hexadecimal para inteiros dhex2dech Parâmetros d matriz de inteiros h matriz de strings correspondentes às representações hexadecimais Descrição hex2decx retorna a matriz de números correspondentes às representações hexadecimais Exemplos hex2decABC0A Ver Também base2dec bin2dec oct2dec dec2bin dec2oct dec2hex 286 Name imag parte imaginária yimagx Parâmetros x matriz ou vetor de reais ou complexos y matriz ou vetor de reais Descrição imagx é a parte imaginária de x ver i para entrar com números complexos Ver Também real 287 Name imult multiplicação pela parte imaginária i yimultx Parâmetros x escalar real ou complexo vetor ou matriz de reais ou complexos y escalar complexo vetor ou matriz de complexos Descrição imultx é um modo mais eficiente de se multiplicar x por i que y ix sem os problemas que ocorrem quando x inclui números especiais em ponto flutuante como inf e nan Exemplos z1 imultinf z2 i inf Autor BP 288 Name ind2sub conversão de índice linear para matriz de valores subescritos i1i2 ind2subdimsI Mi ind2subdimsI Parâmetros dims vetor com as dimensões da matriz I vetor com os dados índices lineares i1i2 valores subescritos de mesma forma que I Mi matriz cujas colunas contém os valores subescritos Descrição ind2sub é usado para determinar os valores subescritos equivalentes que correspondem a um índice único num array i1i2 ind2subdimsI retorna os arrays i1 i2 contendo os subescritos das linha coluna equivalentes correspondente à matriz de índices I para uma matriz de tamanho dims Miind2subdimsI retorna uma matriz Mi cujas colunas são os arrays i1 i2 Exemplos ind2sub232112 ijkind2sub232112 Ver Também sub2ind extraction insertion Autor Serge Steer INRIA 289 Name int parte inteira yintX Parâmetros X matriz de reais y matriz de inteiros Descrição intX retorna a parte inteira da matriz de reais X É o mesmo que fix Ver Também round floor ceil 290 Name intersect returns the vector of common values of two vectors v kakbintersectab v kakbintersectaborient Parâmetros a vetor de números ou strings b vetor de números ou strings orient flag com possíveis valores 1 ou r 2 ou c v vetor linha de números ou strings ka vetor linha de inteiros kb vetor linha de inteiros Descrição intersectab retorna um vetorlinha ordenado dos valores comuns a dois vetores a e b vkakbintersectab retorna também dois vetores de índices ka e kb tais que vaka e vbkb intersectabr ou intersectab1retorna a matriz formada interseção das linhas únicas de a e b ordenadas em ordem lexicográfica ascendente Neste caso a e b devem ter o mesmo número de colunas vkakbintersectabr retorna também dois vetores de índices ka e kb tais que vaka e vbkb intersectabc ou intersectab2retorna a matriz formada interseção das colu nas únicas de a e b ordenadas em ordem lexicográfica ascendente Neste caso a e b devem ter o mesmo número de linhas vkakbintersectabc retorna também dois vetores de índices ka e kb tais que vaka e vbkb Observação NaN são considerados diferentes deles mesmos então são excluídos da interseção em caso de interseção de vetores Exemplos intersect 291 Around5rand101 Bround5rand71 intersectAB NkakbintersectAB intersectastringAastringB intersectint16Aint16B com matrizes A 0011 1 01111 20111 02222 20111 0011nan B 101 102 123 204 125 nan06 vkakb intersectABc Aka Ver Também unique gsort union 292 Name inttrap integração de dados experimentais por interpolação trapezoidal v inttrapx s Parâmetros x vetor de dados de coordenadas x crescentes O valor padrão é 1sizey s vetor de dados de coordenadas y v valor da integral Descrição Computa Onde f é uma função descrita por um conjuto de valores experimentais sifxi e x0x1 x1xn Entre os pontos da malha a função é interpolada linearmente Exemplos t001pi inttraptsint Ver Também intg intc intl integrate intsplin splin 293 Name isdef verifica existência de variáveis isdefname where Parâmetros name um string where um string opcional com valor padrão all todos os locais Descrição isdefname retorna T se a variável name existe e F em caso contrário Aviso uma função que utiliza isdef pode retornar um resultado que depende do ambiente isdefnamelocal retorna T se a variável name existe no ambiente local da função cor rente e F em caso contrário isdefnamenolocal retorna T se a variável name existe no ambiente de chamada com pleto incluindo o nível global da função corrente e F em caso contrário Exemplos A1 isdefA clear A isdefA function level1 function level2 dispisdefaall dispisdefalocal dispisdefanolocal endfunction level2 endfunction function go a1 level1 endfunction go Ver Também exists isglobal whereis type typeof clear 294 Name isempty verifica se uma variável é uma matriz vazia ou uma lista vazia tisemptyx Parâmetros x vetor matriz ou lista t um booleano Descrição isemptyx retorna true verdadeiro se x é uma matriz vazia ou uma lista vazia Exemplos a1 isemptya2 isemptyfindrand1105 295 Name isequal comparação de objetos tisequalab tisequalab Parâmetros a b variáveis de quaisquer tipos t um booleano Descrição isequal compara seus argumentos Se todos eles forem iguais a função retorna t e em caso contrário retorna f Na comparação de listas estruturas etc a o processo é feito recursivamente e a ordem dos campos importa Dados de ponto flutuante são comparados de acordo com a regra IEEE ie valores NaN não é um número não são iguais Ver isequalbitwise para comparações bit a bit Exemplos a1 2 isequala1 2 isequala1 Ver Também isequalbitwise equal less 296 Name isequalbitwise comparação bit a bit de variáveis tisequalbitwiseab tisequalbitwiseab Parâmetros a b variáveis de quaisquer tipos t um booleano Descrição isequalbitwise compara seus argumentos Se todos eles são iguais a função retorna t e em caso contrário f Na comparação de listas estruturas etc a comparação é feita recursivamente a ordem dos campos importa Dados de ponto flutuante são comparados bit a bit ie valores NaN não é um número são iguais double1 e int321 não são iguais Ver isequal para comparações IEEE Exemplos alist15s1ABCDEFG isequalbitwiseaa Ver Também isequal 297 Name isinf verifica se há entradas infinitas risinfx Parâmetros x um vetor ou matriz de reais ou complexos r um vetor ou matriz de valores booleanos Descrição isinfx retorna um vetor ou matriz de valores booleanos que contém entradas verdadeiras corre spondentes às entradas de x infinitas e entradas falsas correspondentes às entradas de x finitas Exemplos isinf1 001 inf inf Ver Também isnan 298 Name isnan verifica entradas NaN não é um número risnanx Parâmetros x real or complex vector or matrix r boolean vector or matrix Descrição isnanx retorna um vetor ou matriz de valores booleanos que contém entradas verdadeiras corre spondentes às entradas NaN de x e entradas falsas correspondentes às entradas regulares de x Exemplos isnan1 001 nan infinf Ver Também isinf 299 Name isreal verifica se uma variável é armazenada como real ou complexa tisrealx tisrealxeps Parâmetros x vetor ou matriz com entradas ou coeficientes de ponto flutuante t um booleano Descrição isrealx retorna true verdadeiro se x é armazenado como uma variável real e falso se x é armazenado com uma parte imaginária que pode ser zero 0 isrealxeps retorna true se x é armazenado como uma variável real ou se o valor absoluto máximo dos pontos flutuantes imaginários é menor que ou igual a eps Exemplos isreal1 2 isreal10i isreal10i0 isreal1s isrealsprand3301 300 Name kron produto de Kronecker kronAB AB Descrição kronAB ou AB retorna o produto tensorial de Kronecker entre duas matrizes A e B A matriz resultante tem a seguinte forma de blocos A11 B A1n B A B Am1 B Amn B Se A é uma matriz m x n e B é uma matriz p x q então AB é uma matriz mp x nq A e B podem ser matrizes esparsas Exemplos A1234 kronAA AA sparseAsparseA A11i kronAA 301 Name lexsort ordenação lexicográfica de linhas de uma matriz N klexsortM sel unique Parâmetros M matriz de reais N matriz de reais k vetor coluna de inteiros Descrição A função lexsort está obsoleta gora Ela pode ser substituída pelas funções gsort e unique NlexsortM ordena as linhas como um grupo da matriz M em ordem ascendente Se requeri do o argumento de saída k contém a ordem NklexsortM retorna k tal que N é igual a Mk NlexsortMsel unique produz o mesmo resultado que a seguinte seqüência de instruções NklexsortMsel unique NMk O flag indicador unique deve ser fornecido caso desejese reter apenas linhas únicas no resulta do Perceba que lexsortMselunique retém apenas linhas tais que Msel são únicas Exemplos Mround2rand203 lexsortM lexsortMunique NklexsortM1 3unique Ver Também gsort unique 302 Name linspace vetor linearmente espaçado vlinspacex1x2 n Parâmetros x1x2 escalares reais ou complexos n inteiro número de valores O valor padrão é 100 v vetor linha de reais ou complexos Descrição Vetor linearmente espaçado linspacex1 x2 era um vetor linha de n valor padrão 100 pontos linearmente espaçados de modo igual entre x1 e x2 Se x1 ou x2 são complexos então linspacex1x2 retorna um vetorlinha de n complexos cujas partes reais e respectivamente as imaginárias dos n complexos são linearmente espaçadas de modo igual entre a partes reais e re spectivamente as imaginárias de x1 e x2 Exemplos linspace1210 linspace1i22i10 Ver Também logspace 303 Name log logaritmo natural ylogx Parâmetros x vetor ou matriz de constantes Descrição logx é o logaritmo natural elemento a elemento yijlogxij Para logaritmo da matriz matriz logaritmo veja logm Exemplos explog1i1i Ver Também exp logm log10 ieee 304 Name log10 logaritmo na base 10 ylog10x Parâmetros x vetor ou matriz Descrição Logartimo decimal Se x é um vetor log10xlog10x1log10xn Exemplos 10log101i1i Ver Também log logm hat ieee 305 Name log1p computa com precisão o logaritmo natural de seu argumento acrescido de uma unidade ylog1px Parâmetros x escalar real ou vetor ou matriz de reais y escalar real ou vetor ou matriz de reais Descrição logp1x é a função log1x elemento a elemento yijlog1 xij Esta função definida para x 1 deve ser usada se quisermos computar log1x com precisão para x 1 significa muito menor Exemplos formate24 log1001 log1p0001 log1 1e7 log1p1e7 log1 1e20 log1p1e20 formatv retoma o formato padrão Ver Também log Autor BP 306 Name log2 logaritmo na base 2 ylog2x Parâmetros x vetor ou matriz Descrição Logaritmo na base 2 Se x é um vetor log2xlog2x1log2xn Exemplos 2log21i1i Ver Também log hat ieee log10 frexp 307 Name logm logaritmo de matriz quadrada matriz logaritmo ylogmx Parâmetros x matriz quadrada Descrição logmx é o logaritmo da matriz x matriz logaritmo de x O resultado é complexo se x não é positiva ou positiva definida Se x é uma matriz simétrica o cálculo é feito pela forma de Schur Em caso contrário x é assumida como sendo diagonalizável Temse expmlogmxx Exemplos A1234 logmA expmlogmA A1AA logmA1 expmlogmA1 A111i expmlogmA1 Ver Também expm log 308 Name logspace vetor espaçado logaritmicamente logspaced1d2 n Parâmetros d1d2 escalar real ou complexo significado especial para pi n inteiro número de valores O valor padrão é 50 Descrição Retorna um vetor linha de n pontos espaçados logaritmicamente de maneira igual entre 10d1 e 10d2 Se d2pi então os pontos estão entre 10d1 e pi Exemplos logspace1210 Ver Também linspace 309 Name lstsize números de entradas de uma lista tlist ou mlist nlstsizex Parâmetros l uma lista tlist ou mlist n um inteiro número de entradas Descrição lstsizex retorna o número de entradas de uma lista tlist ou mlist Esta função é mais eficiente que a função size e opera de modo semelhante para todos os tipos de listas enquanto a função size fica sobrecarregada para mlists Exemplos lstsizelist1aqsdf xssrand324 nynusizex lstsizex Ver Também length size list tlist mlist 310 Name max máximo m kmaxA m kmaxAc m kmaxAr m kmaxAm m kmaxA1A2An m kmaxlistA1A2An Parâmetros A vetor ou matriz de reais A1An um conjunto de vetores ou matrizes todos de tamanhos iguais ou de escalares Descrição Para A um vetor ou matriz de reais maxA é o maior elemento de A mkmaxA fornece ainda o índice do máximo Um segundo argumento do tipo string r ou c pode ser usado r é usado para obter um vetorlinha m tal que mj contém o méximo da j ésima coluna de A Aj kj fornece o índice de linha que contém o máximo para a coluna j c é usado para a operação dual de linhas de A m é usado para compatibilidade com Matlab mmaxA1A2An onde todos os Aj são matrizes de mesmo tamanho retorna um vetor ou matriz m de tamanho sizemsizeA1 tal que mi max Aji j1n mkmaxA1A2An fornece ainda o vetor ou matriz k Fixado i ki é o número do primeiro Aji a alcançar o máximo mkmaxlistA1An é uma outra sintaxe para mkmaxA1A2An Exemplos mnmax131 mnmax311131113 mnmax3211 mnmaxlist311131113 mnmaxlist131 Ver Também gsort find mini 311 Name maxi máximo m kmaxiA m kmaxiAc m kmaxiAr m kmaxiAm m kmaxiA1A2An m kmaxilistA1A2An Parâmetros A vetor ou matriz de reais A1An um conjunto de vetores ou matrizes todos de tamanhos iguais ou de escalares Descrição Para A um vetor ou matriz de reais maxiA é o maior elemento de A mkmaxiA fornece ainda o índice do máximo Um segundo argumento do tipo string r ou c pode ser usado r é usado para obter um vetorlinha m tal que mj contém o méximo da j ésima coluna de A Aj kj fornece o índice de linha que contém o máximo para a coluna j c é usado para a operação dual de linhas de A m é usado para compatibilidade com Matlab mmaxiA1A2An onde todos os Aj são matrizes de mesmo tamanho retorna um vetor ou matriz m de tamanho sizemsizeA1 tal que mi maxi Aji j1n mkmaxiA1A2An fornece ainda o vetor ou matriz k Fixado i ki é o número do primeiro Aji a alcançar o máximo mkmaxilistA1An é uma outra sintaxe para mkmaxiA1A2An Exemplos mnmaxi131 mnmaxi311131113 mnmaxi3211 mnmaxilist311131113 mnmaxilist131 Ver Também gsort find mini 312 Name meshgrid cria matrizes ou arrays 3D X Y meshgridx X Y meshgridxy X Y Z meshgridxyz Parâmetros x y z vetores X Y Z matrizes no caso de dois argumentos de entrada arrays 3D no caso de 3 argumentos de entrada Descrição Exemplos x 1011 y 1011 XY meshgridxy for i1sizeX1 for j1sizeX2 Zij sinc2piXijYij end end surfXYZ Ver Também ndgrid Autor Farid Belahcene 313 Name min mínimo m kminA m kminAc m kminAr m kminAm m kminA1A2An m kminlistA1A2An Parâmetros A vetor ou matriz de reais A1An um conjunto de vetores ou matrizes todos de tamanhos iguais ou de escalares Descrição Para A um vetor ou matriz de reais minA é o menor elemento de A mkminA fornece ainda o índice do mínimo Um segundo argumento do tipo string r ou c pode ser usado r é usado para obter um vetor linha m tal que mj contém o mínimo da j ésima coluna de A Aj kj fornece o índice de linha que contém o mínimo para a coluna j c é usado para a operação dual de linhas de A m é usado para compatibilidade com Matlab mminA1A2An onde todos os Aj são matrizes de mesmo tamanho retorna um vetor ou matriz m de tamanho sizemsizeA1 tal que mi min Aji j1n mkminA1A2An fornece ainda o vetor ou matriz k Fixado um i ki é o número do primeiro Aji a alcançar o mínimo mkminlistA1An é uma outra sintaxe para mkminA1A2An Exemplos mnmin131 mnmin311131113 mnmin3211 mnminlist311131113 mnminlist131 Ver Também gsort find mini 314 Name mini mínimo m kminiA m kminiAc m kminiAr m kminiAm m kminiA1A2An m kminilistA1A2An Parâmetros A vetor ou matriz de reais A1An um conjunto de vetores ou matrizes todos de tamanhos iguais ou de escalares Descrição Para A um vetor ou matriz de reais miniA é o menor elemento de A mkminiA fornece ainda o índice do mínimo Um segundo argumento do tipo string r ou c pode ser usado r é usado para obter um vetor linha m tal que mj contém o mínimo da j ésima coluna de A Aj kj fornece o índice de linha que contém o mínimo para a coluna j c é usado para a operação dual de linhas de A m é usado para compatibilidade com Matlab mminiA1A2An onde todos os Aj são matrizes de mesmo tamanho retorna um vetor ou matriz m de tamanho sizemsizeA1 tal que mi mini Aji j1n mkminiA1A2An fornece ainda o vetor ou matriz k Fixado um i ki é o número do primeiro Aji a alcançar o mínimo mkminilistA1An é uma outra sintaxe para mkminiA1A2An Exemplos mnmini131 mnmini311131113 mnmini3211 mnminilist311131113 mnminilist131 Ver Também gsort find min 315 Name minus operador de subtração mudança de sinal XY Y Parâmetros X escalar vetor ou matriz de números polinômios ou razões de polinômios Também pode ser uma lista syslin Y escalar vetor ou matriz de números polinômios ou razões de polinômios Também pode ser uma lista syslin Descrição Subtração Para operandos numéricos é a operação de subtração em seu sentido usual Se um dos operandos é uma matriz e o outro um escalar a operção é realizada elemento a elemento Se Y X é retornado Se X Y é retornado A subtração também pode ser definida para outros tipos de dados através de operações softcoded Exemplos 121 2 s2 1s2 catenate Ver Também addf mtlbmode 316 Name modulo Resto aritmético simétrico da divisão de n por m pmodulo Resto aritmético positivo da divisão de n por m imodulonm ipmodulonm Parâmetros nm inteiros ou vetores ou matrizes de inteiros de ordens iguais Descrição modulo computa i n modulo m ie resto da divisão de m n e m inteiros i n m int n m Aqui a resposta pode ser negativa se n ou m são negativos pmodulo computa i n m floor n m a resposta é positiva ou zero Exemplos n121015m2235 modulonm modulo39 pmodulo39 317 Name ndgrid Arrays para avaliação de função multidimensional em grid X Y ndgridxy X Y Z ndgridxyz X Y Z T ndgridxyzt X1 X2 Xm ndgridx1x2xm Parâmetros x y z vetores X Y Z matrizes no caso de 2 argumentos de entrada ou hipermatrizes em outro caso Descrição Esta rotina utilitária é útil para criar arrays para a avaliação da função em grids 2 3 n dimensionais Por exemplo em 2d um grid é definido por dois vetores x e y de comprimento nx e ny e se deseja avaliar uma função dita f em todos os pontos do grid isto é em todos os pontos de coordenadas xiyj com i1nx e j1ny Neste caso esta função pode computar as duas matrizes XY de tamanho nx x ny tais que Xij xi para todo i em 1nx Yij yj e j em 1ny e a avaliação pode ser feita com ZfXY sob a condição de que f foi codificada para a avaliação em argumentos de vetor que é feito em geral usando os operadores elemento a elemento and no lugar de e No caso 3d considerando 3 vetores xyz de comprimentos nx ny e nz XYZ são 3 hipermatrizes de tamanho nx x ny x nz tais que Xijk xi Yijk yj para todo ijk in 1nxx1nyx1nz Zijk zk No caso geral de m argumentos de entrada x1 x2 xm os m argumentos de saída X1 X2 Xm são hipermatrizes de tamanho nx1 x nx2 x x nxm e Xji1i2ijim xjij for all i1i2im in 1nx1x1nx2xx1nxm Exemplos criando um grid 2d simples nx 40 ny 40 x linspace11nx y linspace11ny ndgrid 318 XY ndgridxy computando uma função no grid e plotando deffzfxyz128x2 1x2 y2 1y2 deffzfxyzx2 y3 Z fXY xbasc plot3dxyZ flag2 6 4 xselect criando um grid 3d simples nx 10 ny 6 nz 4 x linspace02nx y linspace01ny z linspace005nz XYZ ndgridxyz tente exibir este grid 3d XF YF ZF for k1nz xfyfzf nf3dXkYkZk XF XF xf YF YF yf ZF ZF zf end for j1ny xfyfzf nf3dmatrixXjnxnz matrixYjnxnz matrixZjnxnz XF XF xf YF YF yf ZF ZF zf end xbasc plot3dXFYFZF flag0 6 3 legXYZ xtitleA 3d grid xselect Ver Também kron Autor B Pincon 319 Name ndims número de dimensões de um array Parâmetros A um array n inteiro o número de dimensões do array Descrição nndimsA retorna o número de dimensões de um array A n é maior que ou igual a 2 Exemplos Arand23 ndimsA Arand232 sizeAndimsA H1s1s1 ndimsH Ver Também size Autor S Steer 320 Name nearfloat get previous or next floatingpoint number xnear nearfloatdir x Parâmetros dir string succ ou pred x escalar real vetor ou matriz de reais xnear escalar real vetor ou matriz de reais Descrição Esta função computa elemento a elemento os vizinhos correspondentes dos elementos de x no con junto de pontos flutuantes subjacente ver numberproperties os sucessores se dir succ e e os predecessores se dir pred Exemplos formate22 nearfloatsucc1 1 1 nearfloatpred1 formatv retoma o formato padrão Ver Também numberproperties frexp Autor BP 321 Name nextpow2 próxima potência de 2 mais alta tnextpow2x Parameters x vetor ou matriz de reais p matriz ou vetor de inteiros Descrição Se x é escalar nextpow2x retorna o primeiro p tal que 2p absx Se x é um vetor ou uma matriz nextpow2x se aplica elemento a elemento Exemplos nextpow2127 nextpow2128 nextpow2010 Ver Também frexp 322 Name norm norma de matrizes ynormx flag Parâmetros x vetor ou matriz de reais ou complexos armazenamento cheio ou esparso flag string tipo da norma valor padrão 2 Descrição For matrices normx ou normx2 é o maior valor singular de x maxsvdx normx1 a norma l1 de x a maior soma coluna a coluna maxisumabsxr normxinfnormxinf a norma infinitesimal de x a maior soma linha a linha maxisumabsxc normxfro norma de Frobenius ie sqrtsumdiagxx Para vetores normvp norma lp sumvip1p normv normv2 norma l2 normvinf maxabsvi Exemplos A123 normA1 normAinf A1234 maxsvdAnormA Asparse1 0 0 33 1 normA Ver Também hnorm dhnorm h2norm abs 323 Name not não lógico A Descrição A fornece a negação dos elementos da matriz de valores booleanos A elemento a elemento Exemplos t t f Ver Também and or find 324 Name numberproperties determina parâmetros de ponto flutuante pr numberpropertiesprop Parâmetros prop string pr escalar real ou booleano Descrição Esta função pode ser usada para receber os númerospropriedades característicos do conjunto de pontos flutuantes aqui dentoado por Fbpeminemax geralmente o conjunto de floats de 64 bits prescritos por IEEE 754 Números de F são da forma sign m be e é o expoente e m a mantissa m d1 b1 d2 b2 dp bp di os dígitos estão em 0 b1 e e em emin emax o número é dito normalizado se d1 0 Os seguintes podem ser recebidos prop radix então pr é a raiz b do conjunto F prop digits então pr é o número de dígitos de p prop huge então pr é o maior float positivo de F prop tiny então pr é o menor float normalizado positivo de F prop denorm então pr é um booleano t se números denormalizados são utilizados prop tiniest então se denorm t pr é o número positivo denormalizado mínimo Em outro caso pr tiny prop eps então pr é a máquina epsilon geralmente b1p2 que é o erro máximo relativo entre um real x tal que x está em tiny huge e flx sua aproximação em ponto flutuante em F prop minexp então pr é emin numberproperties 325 prop maxexp então pr é emax Observações Esta função usa uma rotina de LAPACK dlamch para receber os parâmetros máquinas os nomes radix digits huge etc são aqueles recomendados pelo padrão LIA 1 e são diferentes daqueles cor respondentes em LAPACK CUIDADO às vezes você poderá encontrar a seguinte para a máquina epsilon eps b1p mas nesta função nós usamos a definição tradicional ver prop eps acima e então eps b1p2 se o arredondamento normal acontecer e eps b1 p se não acontecer Exemplos b numberpropertiesradix eps numberpropertieseps Ver Também nearfloat frexp Autor Bruno Pincon 326 Name oct2dec conversão de octais para inteiros doct2deco Parâmetros d matriz de inteiros o matriz de strings correspondentes às representações octais Descrição oct2decx retorna a matriz de número correspondentes à representação octal Exemplos oct2dec1 756115 0 23 Ver Também base2dec bin2dec hex2dec dec2bin dec2oct dec2hex 327 Name ones matriz de entradas todas iguais a 1 yonesm1m2 yonesx yones Parâmetros xy matrizes m1 m2 inteiros Descrição Retorna uma matriz cujas entradas são todas iguais a 1 onesm1m2 retorna uma matriz m1m2 cujas entradas são todas 1 onesm1m2mn retorna uma matriz m1m2mn cujas entradas são todas 1 onesx retorna uma matriz cujas entradas são todas 1 com o mesmo tamanho que x onesx também é válido para x uma lista syslin Perceba que ones3 é onesa com a3 ie NÃO é uma matriz 3x3 ones é equivalente a ones11 Exemplos ones3 ones33 ones232 Ver Também eye zeros 328 Name or ou lógico orA orA orAr orA1 orAc orA2 AB Descrição orA fornece o or dos elementos da matriz de valores booleanos A orA é verdadeira t se e só se pelo menos uma entrada de A é t yorAr ou equivalentemente yorA1 é o or linha a linha Retorna em cada en trada do vetor linha y o or das linhas de x o or é realizado no índice de linhas yj orAiji1m yorAc ou equivalentemente yorA2 é o or colunaacoluna Retorna em cada en trada do vetorcoluna y o or das colunas de x o or é realizado no índice de colunas yi orAijj1n AB fornece o or elemento a elemento das matrizes A e B A e B devem ser matrizes de mesmas dimensões ou uma delas deve ser um único booleano Exemplos ort t f t t ff t t t t ff Ver Também and not find 329 Name pen2ea conversão de feixe em matrizes E e A EApen2eaFs Parâmetros Fs feixe de matrizes sEA EA duas matrizes tais que FssEA Descrição Função utilitária Dado o feixe FssEA retorna as matrizes E e A Exemplos E10A12spoly0s EApen2easEA 330 Name perms retorna todas as permutações dos componentes de um vetor ypermsx Parâmetros x um escalar ou um vetor y um escalar ou uma matriz Descrição Dado um vetor x de comprimento n perms retorna todas as permutações dos n componentes de x ie n permutações O tamanho de y é n x n Exemplos x4 7 10 ypermsx x1 5 2 5 ypermsx 331 Name permute permuta as dimensões de um array ypermutexdims Parâmetros dims um escalar ou um vetor de números reais positivos x um escalar um vetor uma matriz ou um multiarray Descrição ypermutexdims Exemplos exemplo 1 x1 2 34 5 6 ypermutex2 1 exemplo 2 xmatrix112232 ypermutex3 1 2 Ver Também pertrans quote cat Autor Farid Belahcene 332 Name pertrans matriz pertransposta YpertransX Parâmetros X matriz de reais ou complexos Y matriz de reais ou complexos Descrição YpertransX retorna a matriz pertransposta de X ie a matriz simétrica a X em relação à segunda diagonal função utilitária Exemplos A1234 pertransA 333 Name primes função dos primos yprimesx Parâmetros x escalar real y vetor Descrição Dado um real x primesx retorna em um vetor y todos os números primos entre 1 e x Se x2 então primesx retorna uma matriz vazia Exemplos x35 yprimesx Ver Também factor 334 Name prod produto yprodx yprodxr ou yprodx1 yprodxc ou yprodx2 yprodxm Parâmetros x matriz ou vetor de reais ou complexos y matriz ou vetor de reais ou complexos Descrição Para um vetor ou uma matriz x yprodx retorna no escalar y o produtório de todas as entradas de x ex prod1n é n yprodxr ou equivalentemente yprodx1 computa os produtórios dos elementos das linhas de x y é o vetor linha y1jprodxj yprodxc ou equivalentemente yprodx2 computa os produtórios dos elementos das colunas de x y é o vetor coluna yi1prodxi yprodxm é o produtório ao longo da primeira dimensão nãosingleton de x para compat ibilidade com o Matlab prod não é implementado para matrizes esparsas Exemplos A120100 prodA prodAc prodAr Ver Também sum cumprod 335 Name rand gerador de números randômico randm1m2 key randx key rand randkey randseed n randinfo Parâmetros mi inteiros key string com valor uniform ou normal x uma matriz Apenas suas dimensões são levadas em conta Descrição Gerador de matriz randômico Sem argumento key as sintaxes abaixo produzem matrizes randômicas com o gerador randômico corrente o padrão é uniform randm1m2 é uma matriz randômica de dimensão m1 por m2 randm1m2mn é uma matriz randômica de dimensão m1 por m2 por mn randa é uma matriz randômica com mesmo tamanho que a randaé de complexos se a é uma matriz de complexos rand sem argumentos fornece um escalar cujo valor muda a cada vez que é referenciado Se presente o argumento key permite especificar uma outra distribuição randômica randuniform o gerador corrente é acertado como gerador randômico uniforme Números aleatórios são dis tribuidos uniformemente e pertencem ao intervalo 01 randnormal o gerador corrente é acertado como gerador de números randômico gaussiano com média 0 e variância 1 strrandinfo retorna o tipo do gerado randômico padrão uniform ou normal É possível reinicializar o seed do gerador randômico randseed retorna o valor corrente do seed rand 336 randseedn define o seed como n o padrão é n0 numa primeira chamada Observação Use a função mais poderosa grand ao invés Exemplos xrand1010uniform randnormal randinfo yrandxnormal xrand222 Ver Também grand ssrand 337 Name rat aproximação racional de pontoflutuante NDratx tol yratx tol Parâmetros x vetor ou matriz de reais n vetor ou matriz de inteiros d vetor ou matriz de inteiros y vetor ou matriz de reais Descrição ND ratxtol retorna duas matrizes de inteiros tais que ND é próxima a x no sentido de que absND X tolabsx As aproximações racionais são geradas truncandose expansões de frações contínuas tol 1e6normX1 é o padrão y ratxtol retorna o quociente ND Exemplos ndratpi ndratpi1d12 ndpi Ver Também int round 338 Name real parte real yrealx Parâmetros x vetor ou matriz de reais ou complexos y matriz de reais Descrição realx é a parte real de x ver i para entrar com números complexos Ver Também imag 339 Name resizematrix cria uma nova matriz com tamanho diferente resMat resizematrixmatnbRownbColtypeOfMat Parâmetros mat matriz de entrada da qual a matriz redimensionada será criada nbRow número de linhas da matriz redimensionada nbCol número de colunas da matriz redimensionada typeOfMat string nome do tipo da matriz redimensionada resMat matriz redimensionada Descrição Cria uma matriz de tamanho nbRow x nbCol e cujos elementos ij são matij se ij está ao alcance da matriz de entrada De outro modo ij são 0 para matrizes de reais ou de inteiros f para matrizes de booleanos e um string vazio para matrizes de strings O tipo da matriz de saída pode ser modificado especificandose o argumento typeOfMat Neste caso esteja certo de que o tipo da matriz de entrada é compatível com este Por enquanto apenas matrizes de reais inteiros booleanos e strings são suportadas Isto significa que typeOfMat deve ser escolhido dentre constant boolean string ou qualquer tipo inteiro int8 int16 Exemplos matriz de números myMat 5 rand 3 4 myMat resizematrix myMat 3 3 reduzindo tamanho da matriz myMatInteger resizematrix myMat 4 4 int32 criando uma matriz de inteiros myMatBoolean resizematrix myMat 2 2 boolean myMatBoolean resizematrix myMatBoolean 3 5 Matriz de strings myMatString ScilabtheOpen SourceScientificSoftwarePackage myMatString resizematrix myMatString 3 1 Ver Também matrix size typeof Autor JeanBaptiste Silvy 340 Name round arredondamento para inteiro mais próximo yroundx Parâmetros x matriz de reais ou complexos y matriz de inteiros ou complexos com partes reais e imaginárias inteiras Descrição roundx arredonda os elementos de x para os inteiros mais próximos Exemplos round19 2523 round1621i22i roundinf xrand1020roundxx Ver Também int floor ceil 341 Name sec computa a secante elemento a elemento do argumento y secx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa a secante elemento a elemento do argumento A secante é uma função periódica definida como 1cos Para dados reais os resultados são reais em inf 1 U 1 inf Exemplos x0 pi3 2pi3 pi4 3pi4 pi6 5pi6 pi secx xlinspacepipi100 plotxsecx Ver Também cos secd Autor Serge Steer INRIA Função Usada Esta função usa a função cos 342 Name secd computa a secante elemento a elemento do argumento em graus y secdx Parâmetros x array de reais y array de reais Descrição as entradas de y são as secantes 1cos das entradas de x dadas em graus Os resultados são reais e estão em inf 1 U 1 inf para entradas iguais a n180 com n inteiro o resultado é exatamente 1 ou 1 para entradas iguais a n90 com n inteiro e ímpar o resultado é infinito ou um erro dependendo do modo ieee Exemplos secd90 secpi2 Ver Também cosd sec Autor Serge Steer INRIA 343 Name sech computa a secante hipertbólica do argumento elemento a elemento y sechx Parâmetros x array de reais ou complexos y array de reais ou complexos Descrição Computa a secante hipertbólica do argumento elemento a elemento A secante hiperbólica é definida como 1cosh Para dados reais os resultados são reais em 0 1 Exemplos xlinspace10101000 plotxsechx Ver Também cosh asech Autor Serge Steer INRIA 344 Name setdiff retorna componentes de um vetor que não pertecem a outro vetor vsetdiffab vkasetdiffab Parâmetros a vetor de números reais ou strings b vetor de números reais ou strings v vetor de números reais ou strings com a mesma orientação de a ka vetor linha de inteiros kai é a localização de vi em a Descrição setdiffab retorna um vetor ordenado que retém as entradas de a que não estão em b vkasetdiffab retorna um vetor ordenado que retém as entradas de a que não estão em b e a localização destas entradas em a Exemplos a 2231112422 b 232122312322 setdiffab vksetdiffstringastringb Ver Também unique gsort union 345 Name sign função de sinal Descrição XsignA retorna a matriz feita dos sinais de Aij Para A feita de complexos signA AabsA Exemplos signrand23 sign1i Ver Também abs 346 Name signm função do sinal da matriz Descrição Para matrizes quadradas e Hemitianas XsignmA é a função do sinal da matriz Exemplos Arand44BAAXsignmBspecBspecX Ver Também sign 347 Name sin função seno tsinx Parâmetros x vetor ou matriz de reais ou complexos Descrição Para um vetor ou matriz sinx é o seno de seus elementos Para o seno da matriz matriz seno use a função sinmX Exemplos asinsin10i Ver Também sinm 348 Name sinc função sinc seno cardinal tsincx Parâmetros x vetor ou matriz de reais ou complexos t vetor ou matriz de reais ou complexos Descrição Se x é um vetor ou uma matriz tsincx é o vetor ou matriz tal que tisinxixi if xi0 e ti1 se xi0 Exemplos xlinspace10103000 plot2dxsincx Ver Também sin cos 349 Name sind função seno argumento em graus tsindx Parâmetros x array de reais ou complexos t array de reais ou complexos com as mesmas dimensões que x Descrição Para um vetor ou uma matriz x sindx é o seno de seus elementos que se supõe estar em graus Os resultados estão em 1 1 Para inteiros n sindn180 é exatamente zero Exemplos x030 45 60 90 360 sindx Ver Também sin Autor Serge Steer INRIA 350 Name sinh seno hiperbólico tsinhx Parâmetros xt vetores ou matrizes de reais ou complexos Descrição Os elementos do vetor t são os senos hiperbólicos dos elementos do vetor x Exemplos asinhsinh01i Ver Também asinh 351 Name sinhm seno hiperbólico da matriz matriz seno hiperbólico tsinhmx Parâmetros xt matriz quadrada de reais ou complexos Descrição sinhmx é o seno hiperbólico da matriz x matriz seno hiperbólico de x texpmxexpm x2 Exemplos A1223 asinhmsinhmA A11isinhmAexpmAexpmA2 Caso para complexos Ver Também sinh 352 Name sinm matriz seno tsinmx Parâmetros x matriz quadrada de reais ou complexos Descrição sinmx é o seno da matriz x matriz seno de x Exemplos A1224 sinmA05iexpmiAexpmiA Ver Também sin asinm 353 Name size tamanho de objetos ysizex sel nrncsizex Parâmetros x matrix incluindo matriz de transferência lista ou sistema linear syslin y 1x2 vetor de inteiros ou número inteiro sel um escalar ou um string nrnc dois inteiros Descrição Aplicado a uma matriz de constantes de polinômios de strings de booleanos ou de razões de polinômios x com apenas um argumento LHS Left Hand Side ou do lado esquerdo size retorna um vetor 1x2 número de linhas número de colunas Chamado com LHS 2 retorna nrnc número de linhas número de colunas sel pode ser usado para especficar a dimensão a ser recebida 1 ou r para receber o número de linhas 2 ou c para receber o número de colunas para receber o produto de linhas e números de colunas Aplicado a uma lista retorna o número de elementos Neste caso apenas a sintaxe ysizex pode ser usada Aplicado a um sistema linear ysizex retorna em y o vetor linha número de saídas número de entradas ie a dimensão da matriz de transferência correspondente A sintaxe nrncsizex também é válida com nrncy1y2 Se x é um sistema lin ear em forma de estadoespaço então nrncnxsizex retorna ainda a dimensão nx da matriz A de x Aplicado a uma hipermatriz ysizex retorna o vetor de dimensões da hipermatriz n1n2nnsizex retorna as dimensões da hipermatriz nisizexi re torna a iésima dimensão e sizex retorna o produto de dimensões Exemplos size 354 nmsizerand32 nmsizeabcd xssrand324nynusizex nynusizess2tfx nynunxsizex Ver Também length syslin 355 Name solve Solucionador simbólico de sistemas lineares xsolveAb Parâmetros Abx matrizes respectivamente vetores de strings Descrição Resolve Ax b quando A é uma matriz triangular superior feita de strings Exemplos A1a02 Triangular superior bxy wsolveAb a1x2y5 evstrw inv110225 Ver Também trianfml 356 Name sort ordenamento decrescente DEPRECATED see gsort s ksortv s ksortvr s ksortvc Parâmetros v vetor esparso vetor ou matriz de reais complexos ou strings s vetor esparso vetor ou matriz de reais complexos ou strings k vetor ou matriz de inteiros Descrição sort will be removed in Scilab 53 see gsort A função sort está obsoleta Ela pode ser substituída por gsort ssortv põe v em ordem decrescente Se v é uma matriz a ordenação é feita coluna a col una v sendo visto como o vetor empilhado v Se v é um string a ordenação é crescente sksortv retorna ainda os índices de entradas de s em v ie vk é o vetor s ssortvr põe as linhas de v em ordem decrescente ie cada coluna de s é obtida de cada coluna de v por reordenação decrescente sksortvr retorna ainda em cada coluna de k os índices tais que vkiisi para cada índice de coluna i ssortvc põe as colunas de v em ordem decrescente ie cada linha de s é obtida de cada linha de v por reordenação decrescente sksortvc retorna ainda em cada linha de k os índices tais que vikisi para cada índice de linha i Matrizes ou vetores de complexos são ordenados de acordo com suas magnitudes Ordenação por colunaslinhas não é implementada para matrizes complexas ysortA é válido quando A é um vetor esparso Ordenação de linhascolunas não é implementado para matrizes esparsas Limitação se v inclui elementos nan a matriz não será ordenada Por favor use gsort neste caso Exemplos spsortrand110 p é uma permutação aleatória de 110 A125342 AsortedqsortAAqAsorted v110 sortv sortv sortvr Não faz nada para vetoreslinha sortvc Ver Também find gsort 358 Name sp2adj converte uma matriz esparsa para forma de adjacência Parâmetros A matriz esparsa de reais ou complexos nz entradas nãonulas xadj vetor de inteiros de comprimento n1 adjncy vetor de inteiros de comprimento nz contendo os índices de linha para os elementos correspon dentes em anz anz vetor coluna de comprimento nz contendo os elementos nãonulos de A Descrição sp2adj converte uma matriz esparsa para usa forma de adjacência função utilitária A matriz esparsa n x m xadj adjncy anz representação em adjacência de A ie xadjj1xadjj número de entradas nãonulas na linha j adjncy índice de coluna das entradas nãonulas nas linha 1 linha 2 linha n anz valores de entradas nãonulas nas linha 1 linha 2 linha n xadj é um vetor coluna de tamanho n1 e adjncy é um vetor coluna de inteiros de tamanho nznnzA anz é um vetor de reais de tamanho nznnzA Exemplos A sprand1005005 xadjadjncyanz sp2adjA nmsizeA p adj2spxadjadjncyanznm Ap Ver Também adj2sp sparse spcompack spget 359 Name speye matriz identidade esparsa Ispspeyenrowsncols IspspeyeA Parâmetros nrows inteiro número de linhas ncols inteiro número de colunas A matriz esparsa sp matriz identidade esparsa Descrição Ispspeyenrowsncols retorna uma matriz identidade esparsa Isp com nrows linhas e ncols colunas matrizes identidades nãoquadradas têm um número máximo de algarismos 1 na diagonal principal IspspeyeA retorna uma matriz identidade esparsa com as mesmas dimensões de A SemnsizeA speyemn e speyeA são equivalentes Em particular speye3 não é equivalente a speye33 Exemplos eye33fullspeye33 Ver Também sparse full eye spzeros spones 360 Name spones matriz esparsa spsponesA Parâmetros A matriz esparsa sp matriz esparsa Descrição spsponesA gera uma matriz com a mesma estrutura de espargimento de A mas com 1 em posições nãonulas Exemplos Asprand101201 spsponesA B A0 bool2sB Ver Também sparse full eye speye spzeros 361 Name sprand matriz esparsa randômica spsprandnrowsncolsfill typ Parâmetros nrows inteiro número de linhas ncols inteiro número de colunas fill coeficiente de preenchimento densidade typ string uniform padrão ou normal sp matriz esparsa Descrição spsprandnrowsncolsfill retorna uma matriz esparsa sp com nrows linhas e ncols colunas e aproximadamente fillnrowsncols entradas nãonulas Se typuniform valores uniformemente distribuídos em 01 são gerados Se typnormal valores normalmente distribuídos são gerados média0 e desvio padrão1 Exemplos Wsprand10010000001 Ver Também sparse full rand speye 362 Name spzeros matriz nula esparsa spspzerosnrowsncols spspzerosA Parâmetros nrows inteiro número de linhas ncols inteiro número de colunas A matriz esparsa sp matriz nula esparsa Descrição spspzerosnrowsncols retorna uma matriz nula esparsa sp com nrows linhas e ncols colunas Equivalente a sparsenrowncols spspzerosA retorna uma matriz nula esparsa com as mesmas dimensões que A Se mnsizeA spzerosmn e spzerosA são equivalentes Em particular spze ros3 não é equivalente a spzeros33 Exemplos sumspzeros10001000 Ver Também sparse full eye speye spones 363 Name sqrt raiz quadrada ysqrtx Parâmetros x escalar real ou complexo ou vetor de reais ou complexos Descrição sqrtx é o vetor de raízes quadradas dos elementos de x O resultado é complexo se x é negativo Exemplos sqrt24 sqrt1 Ver Também hat sqrtm 364 Name sqrtm raiz quadrada da matriz matriz raiz quadrada ysqrtmx Parâmetros x matriz quadrada de reais ou complexos Descrição ysqrtx é a raiz quadrada da matriz x matriz raiz quadrada de x xy2 O resultado pode ser inacurado se x não é simétrica Exemplos x0 12 4 wsqrtmx normwwx x12i wsqrtmxnormwwx1 Ver Também expm sqroot 365 Name squarewave gera uma onda quadrada de período 2pi xsquarewavet percent Parâmetros t vetor de reais discretização do tempo x vetor de reais o valor da onda em cada ponto do tempo no conjunto 11 percent escalar real positivo a porcentagem do período no qual o sinal é positivo O valor padrão é 50 Descrição squarewavet gera o vetor dos valores da onda quadrada de período 2pi em cada data dada no vetor t squarewavet gera uma onda quadrada tal que é a porcentagem do período no qual o sinal é positivo Exemplos t0015pi plot2d1onnt2sint15squarewavetsquarewavet10 Ver Também sin cos 366 Name ssrand gerador de sistema randômico slssrandnoutninnstate slUssrandnoutninnstateflag Parâmetros nout inteiro número de saídas nin inteiro número de entradas nstate inteiro dimensão de espaço de estados flag lista feita de um string ou vários inteiros sl lista lista syslin U matriz quadrada nãosingular nstate x nstate Descrição slssrandnoutninnstate retorna um sistema em espaço de estado randômico estrita mente próprio D0 de tamanho noutnint representado por uma lista syslin e com nstate variáveis de estado slUssrandnoutninnstateflag retorna um sistema linear teste com dadas pro priedades especificadas por flag flag pode ser um dos seguintes flaglistcodimcontsubs flaglistuodimunobssubs flaglistncnodimcnodimncnodimcodimnco flagliststdimcontsubsdimstabsubsdimstab0 flaglistdtdiminstunobdiminstb0dimunobs flaglistonnrngng0nvrk flaglistuinwnwunwuinwuisrk A completa descrição dos Sys é dada no código da função ssrand em SCIDIR macrosutil Por exemplo com flaglistcodimcontsubs um sistema não controlável é retornado e dimcontsubs é a dimensão do subespaço controlável de Sys Os strings couoncnostdtonui significam controlável inobservável nãocontrolávelnãoobservável estabilizável detectável anuladordesaída saídadesconhecida Exemplos flagliststdimcontsubsdimstabsubsdimstab0 ssrand 367 dimcontsubsdimstabsubsdimstab0 par AB Usimilar a 0s 0 A 00i B0 000u 0 A11B1 controlável smatriz estável imatriz neutra umatriz instável SlUssrand238listst255 wss2ssSlinvU desfaz a mudança aleatória de base forma como acima nncuslstilitySlnnc Ver Também syslin 368 Name sub2ind converte matriz de valores subescrtos para índice linear I sub2inddimsi1i2 J sub2inddimsMi Parâmetros dims vetor as dimensões da matriz i1i2 os arrays de valores subescritos de mesma forma que a matriz I Mi matriz cujas colunas contém os valores subescritos I o array de índice linear Descrição sub2ind é usado para determinar o índice único equivalente que corresponde ao dado conjunto de valores subescritos I sub2inddimsi1i2 retorna o índice linear equivalente aos subescritos das linha coluna nos arrays i1 i2 para uma matriz de tamanho dims Neste caso i1 i2 devem ter o mesmo formato e o resultado I tem a mesma forma da matriz I sub2inddimsMi retorna o índice linear equivalente aos subescritos nas colunas da matriz Mi para uma matriz com tamanho dims Neste caso I é um vetor coluna Exemplos i1 2 1 1 2 1 1 j1 2 3 1 2 3 3 k1 2 1 2 1 2 1 sub2ind232ijk sub2ind232ijk Ver Também ind2sub extraction insertion Autor Serge Steer INRIA 369 Name sum soma soma linha soma coluna de entradas de um vetor ou matriz ysumx ysumxr ou ysumx1 ysumxc ou ysumx2 ysumxm Parâmetros x vetor ou matriz de reais complexos esparsoa ou de polinômios y escalar ou vetor Descrição Para um vetor ou matriz x ysumx retorna no escalar y a soma de todas as entradas de x ysumxr ou equivalentemente ysumx1 é a soma linha a linha yj sumxj y é um vetor linha ysumxc ou equivalentemente ysumx2 é a soma coluna a coluna Retorna em cada entrada do vetor coluna y a soma yi sumxi ysumxm é a soma ao longo da primeira dimensão nãosingleton de x para compatibilidade com Matlab Exemplos A1234 traceAsumdiagA sumAcAones21 sumAi AsparseAsumAcAones21 spoly0s Msiss21 sumMsumM2 Ver Também cumsum prod 370 Name sysconv conversão de sistema s1s2sysconvs1s2 Parâmetros s1s2 lista sistemas syslin lineares Descrição Converte s1 e s2 para representação comum a fim de que operações de interconexão de sistemas possam ser aplicadas Função utilitária para peritos A regra de conversão é dada na seguinte tabela c sistema de tempo contínuo d sistema de tempo discreto n sistema amostrado com período de amostragem n sistema com domínio de tempo indefinido Para sistemas mistos s1 e s2 são postos em representação de estadoespaço s1s2 c d n2 c nada incompatível c2es1n2 cs2 d incompatível nada es1n2 ds2 n1 c2es2n1 es2n1 n1n2 incomp es2n1 n1n2 nada cs1 ds1 es1n2 nada Com o seguinte significado n1n2 período de amostragem c2esn o sistema de tempo contínuo s é transformado em um sistema amostrado com período de amostragem n cs conversão para tempo contínuo domínio de tempo é c ds conversão para tempo discreto domínio de tempo é d esn conversão para sistema amostrado com período n sysconv 371 Exemplos s1ssrand112 s2ss2tfs1 s1s2sysconvs1s2 Ver Também syslin ss2tf tf2ss 372 Name sysdiag conexão de sistemas diagonais em blocos rsysdiaga1a2an Descrição Retorna um sistema diagonal em blocos feito de subsistemas postos na diagonal principal ai subsistemas ie ganhos ou sistema linear em forma de espaço de estados ou de transferência Usado em particular para interconexões de sistemas Observação No máximo 17 argumentos Exemplos spoly0s sysdiagrand221s11s11s2s3 sysdiagtf2ss1s1s11s11s2s3 Ver Também brackets insertion feedback 373 Name syslin definição de sistemas lineares slsyslindomABC D x0 slsyslindomND slsyslindomH Parâmetros dom string c d ou ou um escalar ABCD matrizes em representação de espaço de estados D opcional com valor padrão matriz nula para sistemas impróprios D é uma matriz de polinômios x0 vetor estado inicial valor padrão é 0 N D matrizes de polinômios H matriz de razões de polinômios ou representação de espaço de estados linear sl tlist lista syslin representando o sistema linear Descrição syslin define um sistema linear como uma lista e verifica a consistência dos dados dom especifica o domínio de tempo do sistema e pode ter um dos seguintes valores domc para um sistema de tempo contínuo domd para um sistema de tempo discreto n para um sistema amostrado com período de amostragem n em segundos dom se o domínio de tempo é indefinido Representação em espaço de estados slsyslindomABC D x0 Representa o sistema s x Ax Bu y Cx Du x0 x0 A saída de syslin é uma lista da seguinte forma sltlistlssABCDX0dtABCDx0dom Note que D pode ser uma matriz de polinômios sistemas impróprios Representação de matriz de transferência syslin 374 slsyslindomND slsyslindomH A saída de syslin é uma lista da seguinte forma sltlistrnumdendtNDdom ou sltlistrnumdendtH2H3dom Sistemas lineares definidos como syslin podem ser manipulados como matrizes usuais concatenação extração transposição multiplicação etc ambos em estadoespaço ou representação de transferência A maior parte das funções de controle de estadoespaço recebem uma lista syslin como entrada ao invés de quatro matrizes definindo o sistema Exemplos A0100B11C11 S1syslincABC Definição de sistema linear S1A Exibição da matriz A S1X0 S1dt Exibição de X0 e domínio de tempo spoly0s Ds S2syslincABCD H112ss2 S1bissyslincH1 H212ss3s2 S2bissyslincH2 S1S2 S1S2 ss2tfS1S1bis S1bisS2bis S1S2bis sizeS1 Ver Também tlist lsslist rlist ssrand ss2tf tf2ss dscr abcd 375 Name tan tangente ttanx Parâmetros x vetor ou matriz t vetor ou matriz Descrição Os elementos de t são as tangentes dos elementos de x Exemplos x1i1i tanx sinxcosx Ver Também atan tanm 376 Name tand tangente com o argumento em graus ttandx Parâmetros x vetor ou matriz de reais t vetor ou matriz de reais Descrição Os elementos de t são as tangentes dos elementos de x Exemplos modieeeieee2 x030 45 60 90 360 tandx ieeemod Ver Também atand tan 377 Name tanh tangente hiperbólica ttanhx Descrição Os elementos de t são as tangentes hiperbólicas dos elementos de x Exemplos x1i1i tanhx sinhxcoshx Ver Também atanh tan tanhm 378 Name tanhm tangente hiperbólica da matriz matriz tangente hiperbólica ttanhmx Parâmetros xt matrizes quadradas de reais ou complexos Descrição tanhm é a tangente hiperbólica da matriz x matriz tangente hiperbólica de x Exemplos A1234 tanhmA Ver Também tan tanm expm sinm cosm atanhm 379 Name tanm tangente da matriz matriz tangente ttanmx Parâmetros x matriz quadrada de reais ou complexos t matriz quadrada Descrição tanmx é a tangente da matriz x matriz tangente de x Exemplos A1234 tanmA Ver Também tan expm sinm atanm 380 Name toeplitz matriz de Toeplitz Atoeplitzc r Parâmetros acr matrizes de constantes polinômios ou strings Descrição Retorna a matriz de Toeplitz cuja primeira linha é r e a primeira coluna é c c1 deve ser igual a r1 toeplitzc retorna a matriz de Toeplitz simétrica Exemplos Atoeplitz15 Ttoeplitz15127T11 3 5 72 1 3 53 2 1 34 3 2 15 4 3 2 TT1 spoly0s ttoeplitzss1s21s t1s1sss1s1ss1sssss1ss1s1sss1ss tt1 ttoeplitz1234 t11234212332124321 Ver Também matrix 381 Name trfmod exibição de zeros e pólos hmtrfmodh job Descrição Visualiza a estrutura pólozero de uma função de transferência SISO h jobp visualização de polinômios padrão jobf visualização de freqüências naturais e amortecimento Simplificação interativa de h trfmod abre uma janela de diálogo Ver Também poly simp 382 Name trianfml triangularização simbólica f sexptrianfmlf sexp Descrição Triangularização simbólica da matriz f a triangularização é executada por transformações ele mentares de linha sexp é um conjunto de expressões comuns aramazenadas pelo algoritmo Exemplos A12ab WtrianfmlAstringeye22 UW34 a5b6 AevstrA UevstrU UA evstrW12 Ver Também addf mulf solve trisolve 383 Name tril parte triangular inferior de uma matriz trilx k Parâmetros x matriz de reais complexos polinômios ou razões de polinômios k inteiro valor padrão 0 Descrição Parte triangular inferior de uma matriz trilxk é formada pelas entradas abaixo da késima diagonal k0 acima da diagonal superior e k0 diagonais abaixo da diagonal principal Exemplos spoly0s trilsss1 tril1s1s1s1 Ver Também triu ones eye diag 384 Name trisolve solucionador simbólico de sistemas lineares x sexp trisolveAb sexp Parâmetros Ab matrizes de strings Descrição Resolve simbolicamente Ax b A sendo assumida como triangular superior sexp é um vetor de subexpressões comuns em A b x Exemplos Axy0zb01 wtrisolveAb x5y2z4 evstrw invevstrAevstrb Ver Também trianfml solve Autores FD SS 385 Name triu triângulo superior da matriz Descrição Triângulo superior da matriz Ver tril Exemplos spoly0s triusss1 triu1s1s1s1 Ver Também tril ones eye diag 386 Name typeof tipo do objeto ttypeofobject Parâmetros object objeto Scilab t string Descrição ttypeofobject retorna um dos seguintes strings constant se o objeto é uma matriz constante de reais ou complexos polynomial se o objeto é uma matriz de polinômios function se o objeto é uma função código Scilab handle se o objeto é um manipulador alça string se o objeto é uma matriz de strings boolean se o objeto é uma matriz de valores booleanos list se o objeto é uma lista rational se o objeto é a é uma martriz de razões de polinômios matriz de transferência statespace se o objeto é um modelo de espaço de estados ver syslin sparse se o objeto é uma matriz de reais esparsa boolean sparse se o objeto é uma matriz de valores booleanos esparsa hypermat se o objeto é uma hipermatriz array Ndimensional N 3 st se o objeto é um array de estrutura ce se o objeto é um array de células typeof 387 the first string in the first list entry se o objeto é um tlist ou mlist fptr se o objeto é intrínseco ao Scilab código C ou Fortran pointer se o objeto é um ponteiro ver lufact size implicit se o objeto é um polinômio de tamanho implícito para indexação Exemplos typeof1 typeofpoly0x typeof1poly0x typeoft wsprand1001000001 typeofw typeofww deffyfxy2x typeoff LtlistVab18Scilab typeofL Ver Também type strings syslin poly 388 Name union extrai componentes da união de um vetor v ka kb unionab v ka kb unionaborient Parâmetros a vetor ou matriz de números ou strings b vetor ou matriz de números ou strings orient flag com valores possíveis 1 ou r 2 ou c v vetor linha ou matriz de números ou strings ka vetor linha de inteiros kb vetor linha de inteiros Descrição unionab retorna um vetor linha ordenado que retém as entradas únicas de ab unionabr ou unionab1retorna a matriz formada pela união das linhas únicas de a e b em ordem lexicográfica ascendente Neste caso as matrizes a e b devem ter o mesmo número de colunas unionabc ou unionab2retorna a matriz formada pela união das colunas únicas de a e b em ordem lexicográfica ascendente Neste caso as matrizes a e b devem ter o mesmo número de colunas vkakbunionab também retorna vetores de índices ka e kb tais que v é uma combinação ordenada das entradas aka e bkb Exemplos Around5rand101 Bround5rand71 unionAB NkakbunionAB unionastringAbstringB Ver Também unique gsort 389 Name unique extrai componentes únicos de um vetor ou de matrizes N kuniqueM N kuniqueM orient Parâmetros M vetor ou matriz de números ou strings orient flag com valores possíveis 1 ou r 2 ou c N vetor ou matriz de números ou strings k vetor de inteiros Descrição uniqueM retorna um vetor que retém as entradas únicas de M em ordem ascendente uniqueMr ou uniqueM1retorna as linhas únicas de M em ordem lexicográfica ascen dente uniqueMc ou uniqueM2retorna as linhas únicas de M em ordem lexicográfica ascen dente Se requerido o argumento de saída k contém a posição das primeiras entradas únicas encontradas Exemplos Mround2rand201 uniqueM NkuniqueM uniquestringM NkuniquestringM A 0011 0111 2011 0222 2011 0011 TxstringA linhas únicas mkuniqueAr uniqueTr unique 390 colunas únicas mkuniqueTc uniqueAc Ver Também union intersect gsort lexsort 391 Name vectorfind acha em uma matriz linhas ou colunas que coincidem com um vetor ind vectorfindmvjob Parâmetros m uma matriz de qualquer tipo v um vetor de qualquer tipo job um string indicador com valores possíveis r para procura de linhas coincidentes ou c para procura de colunas coincidentes ind vetorlinha contendo os índices das linhas ou colunas coincidentes Descrição Acha em uma matriz as linhas ou colunas que coincidem com um dado vetor Exemplos alr122 121 112 111 121 ind vectorfindalr121r ind vectorfindstringalrstring121r Ver Também find gsort Autores R Nikoukhah S Steer INRIA 392 Name zeros matriz feita de zeros yzeros yzerosx yzerosm1m2 Parâmetros xy matrizes m1 m2 inteiros Descrição Cria uma matriz de zeros é o mesmo que 0ones zerosm1m2 para uma matriz m1m2 zerosm1m2mn cria uma matriz m1m2mn preenhida com zeros zerosA para uma matriz de mesmo tamanho que A zeros3 é zerosa com a3 é uma matriz 3x3 zeros retorna um único zero Se x é uma lista syslin sistema linear em forma de espaço de estados ou transferência zerosx também é válido e retorna uma matriz nula Exemplos zeros3 zeros33 zeros232 Ver Também eye ones spzeros 393 Name logical and operator AB Description AB gives the elementwise logical and of the booleans matrices A and B A and B must be matrices with the same dimensions or one from them must be a single boolean See Also not and or operator 394 Nom csgn Returns the sign of a vector of real of complex values s csgnz Parameters z The vector of values on which we want to compute the sign s If the real part is not equal to zero 1 if the real part of an element if positive 1 if the real part of an element if negative If the real part is equal to zero 1 if the imaginary part of an element if positive 1 if the imaginary part of an element if negative if the element is equal to zero then returns nan Description Returns the sign of a vector of real of complex values Examples A 1 1i 0 1 1i 1i dispcsgnA Authors Y Collette 395 Name isvector check if a variable is a vector tisvectorx Parameters x vector or matrix t a boolean Description isvectorx returns true if x is a vector one of its dimension is different from 1 Examples isvectorones101 isvector1 396 Name logical or operator AB Description AB gives the elementwise logical or of the booleans matrices A and B A and B must be matrices with the same dimensions or one from them must be a single boolean Examples t t f f t t t t f f See Also or and and operator not find Parte IV Funções 398 Nom addprofiling adiciona instruções de profiling análise de performance a uma função addprofilingfunname Parâmetros funname string o nome da função Descrição addprofilingfunname adiciona instruções de profiling a uma função de nome funname Então quando esta função é chamada o número de chamadas e o tempo gasto é armazenado para cada linha da função Exemplos function xfooan x0 for i1n if x10 then xxa else xx1 end end xx21 endfunction addprofilingfoo foo01100 executando a função profilefoo extraindo informação de profile Ver Também profile plotprofile removeprofiling resetprofiling Autor Serge Steer INRIA Funções Utilizadas Esta função utiliza as funções Scilab bytecode e walkbytecode 399 Nom bytecode dada uma função retorna bytecode código de bytes da função em um array Scilab e viceversa x bytecodef f bytecodeX Parâmetros f função Scilab x vetor linha int32 Descrição x bytecodef retorna o bytecode da função f no array Scilab de inteiros x f bytecodex retorna em f a função associada ao bytecode dado no array Scilab de inteiros x AVISO a validade de x não é verificada Observação O bytecode da função Scilab evoluirá drasticamente no futuro então o uso dessa função deve se res tringir à manipulação de instruções de profiling Exemplos function afooasin3endfunction bytecodefoo Ver Também addprofiling bytecodewalk macr2lst macr2tree Autor Serge Steer INRIA 400 Nom bytecodewalk caminha no bytecode código de bytes da função aplicando transformação c1 bytecodewalkcodequeryjob Parâmetros code vetor int32 array de bytecode de entrada query inteiro o opcode código de operação a ser procurado job a operação a ser realizada requerida para c1 vetor int32 array de bytecode de saída Descrição caminha no bytecode da função aplicando transformação Ver Também bytecode Autor Serge Steer INRIA 401 Name deff definição online de função deffs1s2newfunctione1e2text opt Parâmetros e1e2 variáveis de entrada s1s2 variáveis de saída text matriz de strings opt string opcional c a função é compilada para ser eficiente padrão p a função é compilada e preparada para profiling ver profile n a função não é compilada Descrição deff pode ser usada para definir funções de seqüências de instruções escritas em strings de textos Objeto função resultante tem as mesmas propriedades que qualquer outra função definida em um arquivo de texto e carregada através de exec ou exec Aspas em instruções delimitando strings ou indicando transposição de matrizes devem ser dobradas para serem interpretadas corretamente ver quote Isto pode tornar a escrita um tanto estranha Uma alternativa em tais casos é definir funções em arquivos como de uso para carregálas no Scilab através de exec com a opção n e utilizar sci2exp para uma impressão das instruções deff corre spondentes Exemplos deffxmyplusyzxyz deffxmymacroyza3y1 xazy Ver Também comp exec function profile 402 Name exec execução de arquivo script script significa roteiro execpath mode execfun mode ierrexecpatherrcatch mode ierrexecfunerrcatch mode Parâmetros path string o endereço do arquivo script mode escalar inteiro o modo de execução ver abaixo fun uma função do Scilab ierr inteiro 0 ou número de erro Descrição execpath mode executa seqüencialmente as instruções contidas no arquivo fornecido por path com um modo de execução opcional mode Os casos diferentes para mode são 0 o valor padrão 1 nada é impresso 1 eco de cada linha de comando 2 prompt é impresso 3 ecos prompts 4 pára antes de cada prompt A execução retorna após cada retorno de carro 7 paradas prompts ecos útil para demos execfun mode executa a função fun como um script sem argumentos de entrada ou saída nem ambientes de variáveis específicos Esta forma é mais eficiente porque o código script pode se précompilado ver comp Este método para avaliação de scripts permite armazenar scripts como funções em bibliotecas Se um erro é encontrado durante a execução se o flag errcatch estiver presente exec não imprime mensagem de erro aborta execução de instruções e retorna com ierr e igual ao número de erro Se o flag errcatch não estiver presente a manipulação de erros padrão é utilizada Observação Arquivos executáveis exec files podem agora ser usados para definir funções inline utilizando a sintaxe de definição ver function exec 403 Exemplos criando um arquivo script mputla1b2TMPDIRmeuscript executandoo execTMPDIRmeuscript whos name a criando uma função deffyfooxax1ya2 clear a b chamando a função foo1 a é uma variável criada no ambiente da função foo ela é destruída quando foo retorna whos name a x1 criando x para tornála conhecida pelo script foo execfoo a e y são criadas no ambiente corrente whos name a Ver Também exec execstr evstr comp mode chdir pwd 404 Name execstr executa código Scilab em strings execstrinstr ierrexecstrinstrerrcatch msg Parâmetros instr vetor de strings instrução Scilab a ser executada ierr inteiro 0 ou número de erro msg string com valores m ou n O padrão é n Descrição Executa as instruções Scilab fornecidas pelo argumento instr Note que instr não deve fazer uso de marcas de continuação Se o flag errcatch não estiver presente a manipulação de erros ocorre de maneira usual Se o flag errcatch for ajustado e um erro for encontrado enquanto são executadas as instruções definidas em instr execstr não imprime uma mensagem de erro mas aborta a execução das instruções instr no ponto onde o erro ocorreu e retorna com ierr igual ao número de erro Neste caso a exibição da mensagem de erro é controlada pela opção msg m a mensagem é exibida e registrada n nenhuma mensagem de erro é exibida mas a mensagem de erro é registrada ver lasterror Este é o padrão ierr execstrinstrerrcatch pode manipular erros sintáticos Isto é útil para a avaliação de uma instrução obtida por uma pegunta ao usuário Exemplos execstra1 ajusta a1 execstr11 faz nada enquanto evstr11 retorna 2 execstrif t then a1 ba1 else b0 end execstrazzzzzzzerrcatch execstrazzzzzzzerrcatchm execstr 405 erros de sintaxe execstra102errcatch lasterrort execstra1 2 3errcatch lasterrort Ver Também evstr lasterror error try 406 Name fun2string gera definição ASCII de uma função Scilab txtfun2stringfunname Parâmetros fun variável do tipo função name string o nome da função gerada txt vetor coluna de strings o texto fornecendo as instruções Scilab Descrição Dado um pseudocódigo de função Scilab carregada fun2string permite gerar novamente o código O código gerado é identado e embelezado O mecanismo é similar mas mais simples que o de mfile2sci Também pode ser adaptado para traduções de sintaxe Exemplos txtfun2stringasinhfoo writeio2txta Ver Também exec edit macrovar 407 Name function abre definição de função endfunction encerra definição de função Descrição function lhsargumentsfunctionnamerhsarguments statements endfunction Onde functionname é o nome da função rhsarguments é a lista de argumentos de entrada Pode ser uma seqüência separada por vírgula de nomes de variáveis encerrada por parênteses como x1xm O último nome de variável pode ser a palavrachave varargin ver varar gin a seqüência ou nada se a função não possui argumentos de entrada lhsarguments é a lista de argumentos de saída Pode ser uma seqüência separada por vírgula de nomes de variáveis encerrada por colchetes como y1yn O último nome de variável pode ser a palavrachave varargout ver varar gout a seqüência se a função não possui argumentos de saída neste caso a sintaxe também pode ser function functionnamerhsarguments statements conjunto de instruções Scilab declarações Esta sintaxe pode ser usada para definir funções ver functions inline ou em arquivo script ver exec Para compatibilidade com versões Scilab anti gas as funções podem ser definidas em um arquivo script contendo apenas definições de funções podem ser carregadas no Scilab através da função exec A seqüência function lhsargumentsfunctionnamerhsarguments não pode ser separada em várias linhas Esta seqüência pode ser seguida por declarações na mesma linha se uma vírgula ou pontoevírgula for adicionado ao seu fim Definições de funções podem ser aninhadas Exemplos definição inline ver functions function xymyfctab xab yab endfunction xymyfct32 function 408 uma definição de função de uma linha function ysqxyx2endfunction sq3 definição de função aninhada function yfoox asinx function ysqx yx2endfunction ysqa1 endfunction foopi3 definição em um arquivo script ver exec exec SCImoduleselementaryfunctionsmacrosasinhsci Ver Também functions exec exec 409 Name functions procedimentos Scilab e objetos Scilab Descrição Funções são procedimentos Scilab macro função e procedure possuem o mesmo significado Definição de Função Geralmente elas são definidas em arquivos com um edito e carregadas no Scilab através da função exec ou através de uma biblioteca ver lib ou genlib Mas também podem ser definidas online ver deff ou function Uma função é definida por dois componentes uma parte definição de sintaxe como segue function y1ynfoox1xm function y1ynvarargoutfoox1xmvarargin uma seqüência de instruções Scilab A linha de definição de sintaxe fornece a sintaxe de chamamento completa para esta função As variáveis yi são variáveis de saída calculadas em função das variáveis de entrada xi e variáveis existentes no Scilab quando a função é executada Chamada de Função A sintaxe de chamamento de função usual é y1ynfoox1xm Listas de ar gumentos de entrada ou saída mais curtos que as da definição podem ser usadas Em tais casos apenas as primeiras variáveis da esquerda para direita são usadas ou definidas A função argn pode ser utilizada para se o número total real de argumentos de chamada É possível definir funções com número máximo indeterminado de argumentos de entrada ou saída Isto pode ser feito utilizandose as palavraschave varargin e varargout keywords Veja os links para detalhes Também é possível utilizar argumentos nomeados para especificar argumentos de entrada supon ha que a função fun1 seja definida como function y1fun1x1x2x3 então pode ser chamada com uma sintaxe como yfun1x133x31 2 3 Dentro de fun1 x2 será indefinida Também pode ser chamada com sintaxe como yfun1x133yfoo Em tal caso a variável y estará disponível no contexto da função fun1 Note que o número máximo de argumen tos deve ser menor que ou igual ao número de argumentos de entrada fornais utilizados na parte de sintaxe da função É possível buscar por variáveis definidas através da função exists Quando uma função não possui argumento de lado esquerdo e é chamada apenas com argumentos strings a sintaxe de chamamento pode ser simplificada funatotoa string is equivalent to functions 410 fun a toto a string Miscelânea Funções Scilab são objetos com números de tipo 13 ou 11 Elas podem ser manipuladas construídas salvas carregadas passadas como argumentos como outros tipos de variáveis Coleções de funções podem ser reunidas em bibliotecas Funções que começam pelo sinal ex foo são geralmente utilizadas para operações de sobrecarga ver overloading ou são funções para novos tipos de dados Exemplos definição inline ver function function xymyfctab xab yab endfunction xymyfct32 definição inline ver deff deffxymyfctabxab yab definição em um arquivo ASCI ver exec exec SCImoduleselementaryfunctionsmacrosasinhsci Ver Também function deff exec comp lib getd genlib exists varargin varargout 411 Name genlib constrói biblioteca a partir de funções em um diretório genliblibname dirname Force verb Names genliblibname pathdirname verboseverb forceForce namesNames Parâmetros libname string O nome da variável biblioteca a ser recriada dirname string O nome do diretório onde se deve procurar arquivos sci Force booleano o padrão é f Para forçar recompilação de arquivos sci ajusteo para t verb booleano o padrão é f Para obter informações ajusteo para t Names vetor de strings os nomes das funções a serem inclusas na bibilioteca Por padrão todos os ar quivos sci são levados em conta Descrição Para cada arquivo sci em dirname ou apenas para aqueles especificados pelo argumento Names genlib executa um exec e salva as funções no arquivo bin correspondente O arquivo sci só pode conter instruções Scilab Se um arquivo bin for mais novo que o arquivo sci as sicuadi genlib não traduz nem salva o arquivo O comportamento padrão pode ser modificado se force for fornecido e ajustado para t Neste último caso a recompilação é sempre feita para cada arquivo sci Quando todos os arquivos sci tiverem sido processados genlib cria uma biblioteca nomeada libname e a salva arquivo lib em dirname Se a variável Scilab libname não estiver pro tegida ver predef esta variável é atualizada Se verb estiver ajustado para t informações são exibidas durante o processo de construção Seo argumento dirname não for fornecido e se a variável Scilab libname existe e é uma variável dirname é tomado como sendo igual a o endereço de bibilioteca libname modo de atualização Restrições Scilab assume implicitamente que foosci define pelo menos uma função de nome foo Se funções subsidiárias estiverem inlusas elas são tornadas conhecidas ao Scilab apenas depois que função foo tiver sido referencida Ver Também getd exec save lib 412 Name getfunctionpath retorna o endereço do arquivo fonte de uma função de biblioteca pathgetfunctionpathfunname Parâmetros funname string o nome da função path string o nome absoluto do endereço do arquivo fonte da função sci ou Descrição Dadi o nome de uma uma função getfunctionpath o nome absoluto do endereço do arquivo fonte da função se a função estiver definida em uma biblioteca Scilab ver lib ou se nenhum nome cor responde a uma função de biblioteca Exemplos getfunctionpathmedian Ver Também lib string 413 Name getd retorna todas as funções definidas em um diretório getdpath Parameters path string Scilab O endereço do diretório Descrição Carrega todos os arquivos sci contendo funções Scilab definidos no diretório path Exemplos getdSCImodulescacsdmacros Ver Também exec lib pwd chdir 414 Name headcomments exibe comentários do cabeçalho da função Scilab headcommentsname headcommentsnamepaths Parâmetros name string nome da função paths vetor de strings endereços onde se deve procurar o arquivo sci Descrição commentsname exibe comentários do cabeçalho da função como a ajuda do Matlab Os comentários são lidos do arquivo sci associado Se name for uma função em uma biblioteca o endereço do arquivo sci é aquele dado pelo endereço da biblioteca ver lib Se name for uma função que não está na biblioteca um arquivo de nome namesci é procurado nos outros diretórios forneci dos pela variável paths AVISO a maior parte das funções Scilab predefinidas não possui comentários de cabeçalho Exemplos headcomments sinc Ver Também help Autor Serge Steer INRIA 415 Name lib definição de biblioteca xlib liblibdir Parameters libdir string Descrição libdir é um string definindo um diretório que contém arquivos de funções compiladas do Scilab bin Em adição a esses arquivos libdir deve conter um arquivo chamado names que contém os nomes das funções definidas em libdir Com sucesso todas as funções em libdir estarão disponíveis dentro do Scilab Elas são carregadas em demanda quando são chamadas pela primeira vez Arquivos binários podem ser criados de dentro do Scilab com o comando save As bibliotecas padrões do Scilab são definidas utilizandose lib nos subdiretórios SCIDIR macros Uma variável biblioteca geralmente é salva para carregamento posterior tanto online quanto do ar quivo de inicialização específico do usuário ver startup Restrições O Scilab assume tacitamente que cada arquivo xxxxbin define uma variável chamada xxxx Exemplos define some variables function z myplusx y z x yendfunction function z yourplusx y x x yendfunction A110 create the bin files in libdir libdirTMPDIR savelibdir myplusbin myplus savelibdir yourplusbin yourplus savelibdir Abin A create the name file mputlmyplusyourplusATMPDIRnames build the library containing myplus and yourplus xlib liblibdir erase the variables clear myplus yourplus A Automatic loading and execution myplus12 lib 416 A Ver Também library genlib save deff exec whereis 417 Name librarieslist retorna as bibliotecas do Scilab slibrarieslist Parâmetros s uma matriz de strings Descrição Retorna em s todas as bibliotecas na pilha Scilab Exemplos librarieslist Ver Também libraryinfo 418 Name library descrição de tipo de dado bibilioteca Descrição Uma bibilioteca é um tipo de dado com número 14 Contém um nome de endereço e um conjunto de nomes Permite o carregamento automático de variáveis utilizando o seguinte algoritmo Suponha o usuário Scilab referencie a variável de nome foo O Scilab procura primeiro se foo é o nome de uma primitiva ou de uma variável já definida Se naõ for procura por foo seqüencialmente a mais nova em toda a biblioteca definida Suponha que foo pertence ao conjunto de nomes da biblioteca xlib Então o Scilab tenta carregar o arquivo xlibpathnamefoobin xlibpathnamefoobin deve ter sido criado utilizandose a função save Bibliotecas geralmente são utilizadas para coleções de funções mas também podem ser utilizadas para coleções de variáveis Scilab Se uma função estiver definida em mais de uma biblioteca o algoritmo de busca padrão carrega aquela contida na mais nova É possível forçar o uso de uma biblioteca específica utilizando a notação de ponto xlibfoo carrega a variável foo contida em xlib if foo for uma função e xlibfooargs executa as funções Exemplos elemlib é uma biblioteca predefinida elementaryfunctionlib exibindo o conteúdo da biblioteca Arand33 cosmA carregando cosm e executandoo whos name cosm agora cosm é uma variável elementaryfunctionlibsinm carregando sinm da biblioteca elementaryfunctionlibcosmA carregando novamente cosm e executandoo Ver Também lib string load save 419 Name libraryinfo retorna macros e endereço de uma biblioteca Scilab macros libraryinfolibraryname macrospath libraryinfolibraryname Parâmetros macros uma matriz de strings todas as funções principais da biblioteca path um string endereço da biblioteca libraryname string nome da biblioteca Descrição Retorna nomes de funções e o endereço de uma biblioteca Scilab Os nomes de funções são aqueles que correspondem aos nomes de arquivo associados sci ou bin Os outros são funções subsidiárias Exemplos mplibraryinfocorelib Ver Também librarieslist 420 Name listfunctions propriedades de todas as funções no espaço de trabalho flistcompiledprofilablecalled listfunctionsscope Parâmetros scope string local padrão ou global flist array de strings names nomes de todas as variáveis funções especificadas no espaço de trabalho compiled array de booleanos verdadeiro se o elemento correspondente de flist for do tipo 13 profilable array de booleanos verdadeiro se o elemento correspondente de flist for do tipo 13 e adicional mente informações sobre profiling forem encontradas no pseudocódigo da função called array uint32 número de vezes que o elemento correspondente de flist foi chamado nãozero apenas se a função possuir profiling Descrição Esta função verifica todas as variáveis do espaço de trabalho dadas por who e coleta aquelas de tipo 11 ou 13 para as últimas lstmacr2lstfun é chamada de modo a verificar a entrada para magic profiling ao fim da primeira linha de código ie lst5125 Exemplos recompilefunctionasinhp flistcompiledprofilablecalled listfunctions flistprofilable Ver Também function exec deff comp fun2string profile recompilefunction Autor Enrico Segre Bibliografia httpwikiscilaborgScilabfunctionvariables3Arepresentation2Cmanipulation 421 Name macro Procedimento Scilab e objeto Scilab Descrição Macros são procedimentos Scilab macro função e procedimento possuem o mesmo significa do Geralmente eles são definidos em arquivos com um editor e carregados no Scilab com exec ou através de uma biblioteca Também podem ser definidos online ver deff Um arquivo que contém uma macro deve começar como segue function y1ynfoox1xm Os yi são variáveis de saída calculadas como funções de variáveis de entrada e variáveis existentes no Scilab quando o macro é executado Um macro pode ser compilado para uma execução mais rápida Coleções de macros podem ser armazenadas em bibliotecas Macros que começam pelo símbolo ex foo e cujos argumentos são listas são usadas para executar operações específicas por exemplo zrmrxy é equivalente a zxy quando x e z são racionais ie xlistrnd com n e d polinômios Ver Também deff getf comp lib 422 Name macrovar variáveis de uma função varsmacrovarfunction Parâmetros vars list listinoutglobalscalledlocals function nome de uma função Descrição Retorna em uma lista o conjunto de variáveis utilizadas por uma função vars é uma lista feita de cinco vetores colunas de strings in variáveis de entrada vars1 out variáveis de saída vars2 globals variáveis globais vars3 called nomes de funções chamadas vars4 locals variáveis locais vars5 Exemplos deffyfx1x2loc1yax1x2loc varsmacrovarf Ver Também string macr2lst 423 Name plotprofile extrai e exibe execução de profiles dossiês de uma função Scilab plotprofilefun Parâmetros fun função Scilab compilada ou nome de função string ou array de nomes de funções Descrição Para utilizar plotprofile a função Scilab deve ter sido preparada para profiling análise de de sempenho ver exec Quando tal função é executada o sistema conta quantas vezes cada linha foi executada e quanto tempo de cpu foi gasto para cada linha Estes dados são armazenados dentro da estrutura de dados da função A função plotprofile é um comando interativo que exibe os resultados em uma janela gráfica Quando uma linha é clcada a fonte da função é exibida com a linha selecionada realçada NOTA você deve clicar no item Exit na janela de gráficos para sair de plotprofile O código da função é gerado com fun2string e guardado em um arquivo temporário Exemplos definindo função e preparandoa para profiling deffxfoonif n0 then x else x0 for k1n ssvdrandn10n10 xxs1 end endp chamando a função foo30 obtendo profiles de execução plotprofilefoo clique em Exit para sair Ver Também profile showprofile fun2string 424 Name profile extrai profiles dossiês de execução de uma função do Scilab cprofilefun Parâmetro fun função Scilab c uma matriz nx3 contendo os profiles de execução Descrição Para utilizar profile a função Scilab deve ter sido preparada para profiling análise de desempenho ver exec Pata tal função quando tal função é executada o sistema conta quantas vezes cada linha foi executada e quanto tempo de cpu foi gasto para cada execução da linha Estes dados são armazenados na estrutura de dados da função A função profile permite extrair esses dados e retornálos nas duas primeiras colunas de c A terceira coluna de c fornece a medida do esforço do interpretador para a execução da linha correspondente A iésima linha de c corresponde à iésima linha da função inclusa primeiro Note que devido à precisão do clock do processador tipicamente um microssegundo algumas lin has executadas aparecem com tempo de execução 0 mesmo que o tempo de execução de cpu total realmente gasto seja grande Exemplos definindo a função e preparandoa para profiling deffxfoonif n0 then x else x0 for k1n ssvdrandn10n10 xxs1 end endp chamando a função foo10 obtendo profiles de execução profilefoo chamando a função foo20 profilefoo a execução de profiles é acumulada Ver Também exec deff plotprofile showprofile 425 Name recompilefunction recompila uma função Scilab modificando o seu tipo recompilefunctionfunname kind force Parâmetros funname string nome da função a ser recompilada kind string n não compilado tipo 11 c compilado tipo 13 or p compilado tipo 13 preparado para profiling Pardrão c force booleano Se falso a função é recompilada apenas se seu tipo mudar se verdadeiro é recompi lada ainda que mantenha o tipo notavelmente útil para compilar uma função p function para reiniciar as estatísticas de profiling Descrição Esta função compila reversamente uma variável função via fun2string e a recompila para o tipo desejado através de deff Exemplos recompilefunctionasinhp for i1100 asinhrand100100 end showprofileasinh Ver Também function exec deff comp fun2string profile Autor Enrico Segre Bibliografia httpwikiscilaborgScilabfunctionvariables3Arepresentation2Cmanipulation 426 Nom removeprofiling remove instruções de profiling análise de performance de uma função removeprofilingfunname Parâmetros funname string o nome da função Descrição removeprofilingfunname remove instruções de profiling se houver alguma da função de nome funname Exemplos function xfooan x0 for i1n if x10 then xxa else xx1 end end xx21 endfunction addprofilingfoo foo01100 executando a função profilefoo extraindo informação de profile removeprofilingfoo Ver Também profile plotprofile removeprofiling resetprofiling Autor Serge Steer INRIA Funções Utilizadas Esta função utiliza as funções Scilab bytecode e walkbytecode 427 Nom resetprofiling reinicia contadores de profiling de uma função resetprofilingfunname Parâmetros funname string o nome da função Descrição resetprofilingfunname reinicia contadores de profiling se houver da função de nome funname Exemplos function xfooan x0 for i1n if x10 then xxa else xx1 end end xx21 endfunction addprofilingfoo foo01100 executando a função profilefoo extraindo informação de profile resetprofilingfoo profilefoo extraindo informação de profile Ver Também profile plotprofile addprofiling resetprofiling removeprofiling Autor Serge Steer INRIA Funções Utilizadas Esta função utiliza as funções Scilab bytecode e walkbytecode 428 Name showprofile extrai e exibe profiles dossiês de execução de uma função Scilab showprofilefun Parâmetros fun função Scilab Descrição Para utilizar showprofile a função Scilab deve ter sido preparada para profiling análise de per formance ver exec Para tal funçãoQuando tal função é executada o sistema conta quantas número de vezes que cada linha é executada e quanto tempo de cpu é gasto para execução de cada linha Estes dados são armazenados dentro da estrutura de dados da função A função showprofile retorna resultados de profiling ver profile com o texto das linhas da função O texto da função é reconstruído com fun2string Exemplos definindo função e preparandoa para profiling deffxfoonif n0 then x else x0 for k1n ssvdrandn10n10 xxs1 end endp chamada à função foo30 obtendo profiles showprofilefoo Ver Também profile plotprofile fun2string 429 Name varargin variável do número de argumentos de saída em uma lista de argumentos de entrada Descrição Uma função cujo último argumento de entrada é varargin pode ser chamada com mais argumentos de entrada que os indicados pela lista de argumentos de entrada Os argumentos de chamada passados da palavrachave varargin em diante podem ser recuperados em uma lista chamada varargin Suponha que a palavrachave varargin é o nésimo argumento da lista de argumentos de entrada formal então se a função é chamada com n1 argumentos de entrada a lista varargin não é definida Se a função for chamada com n1 argumentos então varargin é uma lista vazia y function exvarargin pode ser chamada com qualquer número de argumentos de entrada Dentro da função ex argumentos de entrada podem ser recuperados em varargini i1lengthvarargin Se não for o último argumento de entrada da função varargin é um argumento de entrada normal sem nenhum significado especial O número de argumentos de entrada real é dado por argn2 Observações Sintaxe de argumento nomeada como fookeyvalue é incompatível com o uso de varargin A razão é que os nomes ie keys associados aos valores value não são armazenados na lista varargin Considere por exemplo function foovarargindispvarargin1varargin2endfunction fooa1b2 O Scilab responde 1 2 foob1a2 O Scilab responde 1 2 O resultado é o mesmo mas os argumentos foram invertidos Exemplos deffexamplavararginlhsrhsargn0 if rhs1 then dispvararginend exampl1 exampl exampl123 llistast exampl1l23 Ver Também function varargout list 430 Name varargout variável do número de argumentos de saída em uma lista de argumentos de saída Descrição Uma função cuja lista de argumentos de saída contém varargout deve ser chamada com mais argumentos de saída que indicado na lista de argumentos de saída A chamada de argumentos passados da palavrachave varargout em diante são extraídos da lista varargout definida na função varargout function ex pode ser chamado com qualquer número de argumentos de saída Dentro da função ex argumentos de saída podem ser armazenados em varargouti X1Xnvarargout function ex também pode ser usado Neste caso as variáveis Xi devem estar atribuídas na função tanto quanto varargouti O número total real de argumentos de saída é dado por argn1 Observação A variável varargout deve ser criada dentro de uma função e atribuída a uma list Se varargout for a única variável de saída formal a lista deve conter pelo menos uma entrada Exemplos function varargoutexampl varargoutlist1234 endfunction xexampl xyexampl xyzexampl function abvarargoutexampl1 afirst bsecond varargoutlist1234 endfunction exampl1 abexampl1 abcexampl1 Ver Também function varargin list 431 Name whereis ome da biblioteca contendo a função librnamewhereisfunctionname Descrição Retorna um string correspondente ao nome da biblioteca onde a função functionname se encon tra O endereço da biblioteca é retornado digitandose librname Ver Também lib 432 Name getf defining a function from a file getffilename opt Parameters filename Scilab string opt optional character string c loaded functions are compiled to be more efficient default n loaded functions are not compiled p loaded functions are compiled and prepared for profiling see profile Description WARNING this function has been deprecated see exec as a replacement of getf getf will be removed in Scilab 53 loads one or several functions see functions defined in the file filename The string optn means that the functions are not compiled preinterpreted when loaded This can be use ful for some debugging purpose see comp By default functions are compiled when loaded ie optc is used In the file a function must begin by a syntax definition line as follows function y1ynfoox1xm The following lines contain a sequence of scilab instructions The syntax definition line gives the full calling syntax of this function The yi are output variables calculated as functions of input variables xi and variables existing in Scilab when the function is executed Shorter input or output argument list may be used Many functions may be written in the same file A function is terminated by an endfunction keyword For compatibility with previous versions a function may also be terminated by the following function keyword or the EOF mark For that reason it is not possible to load function containing nested function definition using the getf function getf is an obsolete way for loading functions into scilab from a file It is replaced by the function exec Note that functions in a file should be terminated by an endfunction keyword The exec function supposes optc To prepare a function for profiling please use the addprofiling function Examples getf 433 getfSCImodulesgraphicsmacrosplotsci getf SCImodulesgraphicsmacrosplotsci See Also functions function genlib getd exec edit comp addprofiling Parte V Arquivos funções de EntradaSaída 435 Name chdir muda o diretório corrente do Scilab cd muda o diretório corrente do Scilab bchdirpath realpathcdpath cd path Parâmetros b um booleano t se a operação chdir estiver ok path um string realpath um string o nome real do endereço após a conversão do nome do endereço ver abaixo Descrição Muda o diretório corrente do Scilab para aquele dado por path Note que a conversão de endereço é realizada e por exemplo SCImodulescoremacros é um padrão válido tanto pra Unix quanto para Windows Se path for vazio muda para diretório home Exemplos chdirTMPDIR pwd cd cd SCI Ver Também pwd 436 Name fileinfo Fornece informações sobre um arquivo xierrfileinfofile Parâmetros file string o endereço do arquivo x um vetor de inteiros de tamanho 13 contendo informações ou uma matriz vazia se o arquivo não existir ierr indicador de erro 0 se não for encontrado nenhum erro Descrição xfileinfofile retorna x1 O tamanho do arquivo x2 O modo do arquivo valor decimal x3 O id do usuário x4 O id do grupo x5 O número do dispositivo x6 A data da última modificação x7 A data da última mudança x8 A data do último acesso x9 O tipo de dispositivo se o dispositivo for inode x10 O tamanho de bloco para a entradasaída do sismtema de arquivos sempre 0 no Windows x11 O número de blocos alocados sempre 0 no Windows x12 O inode x13 O número de hard links fileinfo 437 Referência Esta função é uma interface para a função C stat Permissões são tipicamente especificadas como números octais dec2octx2 para conversão O modo numérico possui de um a quatro dígitos octais 07 derivados através da soma de bits com os valores 4 2 e 1 Quaisquer dígitos omitidos são supostos como zeros à esquerda O primeiro dígito seleciona o ID de usuário 4 e ajusta o ID do grupo 2 e atributos sticky 1 O segundo dígito seleciona permissões para o usuário que possui o arquivo leitura 4 escrita 2 e execução 1 o terceiro dígito seleciona permissões para os outros usuários no grupo do arquivo com os mesmos valores e o quarto seleciona permissões para outros usuários que não estão no grupo do arquivo com os mesmos valores Exemplos w fileinfoSCIetcscilabstart permisso do arquivo dec2octw2 data do arquivo getdatew6 Verificando a permisso de escrita em um arquivo w fileinfoSCIetcscilabstart SIWRITE 128 mascarando a permisso de escrita SIEXEC 64 mascarando a permisso de execuo SIREAD 256 mascarando a permisso de leitura SIFCHR 8192 mascarando a permisso de diretrio if bitand w2 SIWRITE 0 then dispPERIMISSO DE ESCRITA neste arquivo else dispNO H PERIMISSO DE ESCRITA neste arquivo end Ver Também getdate file dispfiles newest isdir Autores S Steer INRIA AC 438 Name getabsolutefilepath fornece o nome de endereço absoluto de um arquivo aberto no Scilab pathname getabsolutefilepathfilename Parâmetros filename string nome do arquivo pathname string o nome de endereço absoluto Descrição Fornece o nome de endereço absoluto de um arquivo já aberto no Scilab getabsolutefilepath procura na lista interna de arquivos abertos correntemente do Scilab filename e retorna seu endereço Se o arquivo não for aberto um erro é retornado Aviso na versão anterior Scilab 50x o diretório corrente era retornado se o arquivo não fosse encontrado Esta função pode ser utilizada para encontrar de onde endereço um script Scilab é executado Exemplos executando este script amopenTMPDIRtestscewt dispgetabsolutefilepathtestsce mclosea Ver Também getshortpathname getlongpathname pwd Autores Allan CORNET 439 Name getrelativefilename dado um nome de diretório absoluto e um nome de arquivo relativo retorna um nome de arquivo relativo relfile getrelativefilenameabsdirabsfile Parâmetros absdir string o diretório absoluto absfile string o nome de arquivo absoluto relfile string o nome de arquivo relativo Descrição dado um nome de diretório absoluto e um nome de arquivo relativo retorna um nome de arquivo relativo Por exemplo se o diretório corrente é Cscilabbin e o nome de arquivo Cscilabmoduleshelp toolsreadmetxt é dado getrelativefilename retornará moduleshelptoolsreadmetxt Exemplos if MSDOS then getrelativefilenameCprogram filescilab40binCprogram filescilab40moduleshelptoolshelpdtd getrelativefilenameCprogram filescilab40binCprogram filescilab40moduleshelptoolshelpdtd getrelativefilenameSCIbinSCImoduleshelptoolshelpdtd getrelativefilenameWSCIbinWSCImoduleshelptoolshelpdtd getrelativefilenamepwdWSCIbinWscilex else getrelativefilenameusrlocalscilab40binusrlocalscilab40moduleshelptoolshelpdtd getrelativefilenameusrlocalscilab40binusrlocalscilab40moduleshelptoolshelpdtd getrelativefilenameSCIbinSCImoduleshelptoolshelpdtd getrelativefilenamepwdSCIbinscilex end Ver Também getshortpathname getlongpathname pwd Autor Pierre MARECHAL 440 Name newest retorna o arquivo mais novo de um conjunto de arquivos knewestpaths knewestpath1path2pathn Parâmetros k o índice do arquivo mais novo paths vetor de strings pathsi é o endereço do iésimo arquivo pathi string o endereço do iésimo arquivo Descrição Dado um conjunto de endereços newest retorna o índice do mais novo Arquivos não existentes são supostos como mais antigos Exemplos newestSCImodulesgraphicsmacrosbodesciSCImodulesgraphicsmacrosbodebin newestSCImodulesgraphicsmacrosbodesciSCImodulesgraphicsmacrosbodebin newestSCImodulesgraphicsmacrosbodescibin Ver Também fileinfo 441 Name sscanf converte entrada formatada fornecida por um string v1vnsscanf stringformat Parameters format especifica a conversão de formato string especifica a entrada a ser lida Descrição Esta função está obsoleta use a função msscanf de preferência que é mais eficiente mais compatível com o procedimento C sscanf A função sscanf intepreta um string de acordo com um formato e retorna os resultados convertidos O parâmetro de formato contém especificações de conversão utilizadas para interpretar a saída O parâmetro de formato pode conter caracteres em branco espaços tabulações novas linhas quebra de página os quais exceto nos dois casos seguintes lê a entrada até o próximo caractere preenchido A menos que haja uma correspondência no string de controle espaços em branco incluindo caractere de nova linha vindo por último não são lidos Qualquer caractere exceto sinal de porcento que deve corresponder ao próximo caractere do fluxo de entrada Uma especificação de conversão que direciona a conversão do próximo campo de entrada Ver scanfconversion para detalhes Ver Também mprintf msscanf mfscanf scanfconversion 442 Name basename strip directory and suffix from filenames files basenamefilesflag flagexpand Parameters files a string matrix giving a set of file names flagflagexpand boolean optional parameters default value t files a string matrix Description basename return the basename of the file entries given in files If flag is true the files are first converted to the target type given by the MSDOS variable Moreover if flagexpand is true leading strings like HOME SCI or are expanded using environment variables Examples filesbasenameSCImodulesfileiomacrospoosci filesbasenameSCImodulesfileiomacrospoosci filesbasenameSCImodulesfileiomacrospooscik See Also listfiles pathconvert fileparts 443 Name copyfile Copy file copyfilesourcedestination statusmessage copyfilesourcedestination Description copyfilesourcedestination copies the file or directory source and subdirectories to the file or directory destination If source is a directory destination can not be a file copyfile replaces existing files without warning status message copyfilesourcedestination copies source to destination returning the status and a message Whatever the operating system if the copy succeeds the status is 1 and the message is empty if the copy fails the status is 0 and the message is not empty The timestamp given to the destination file is identical to that taken from source file Examples copyfileSCIetcscilabstartTMPDIRscilabstart statusmessage copyfileSCIetcscilabstartTMPDIR See Also movefile mdelete Authors Allan CORNET 444 Name createdir Make new directory createdirdirname status createdirdirname Description createdirdirname creates the directory dirname in the current directory if dirname is not in the current directory specify the relative path to the current directory or the full path for dirname status createdirdirname creates the directory dirname in the existing directory parentdir return ing the status a message Here status is T for success and F otherwise createdir is used by mkdir Examples createdirSCIHOMEDirectorytest removedirSCIHOMEDirectorytest See Also mkdir rmdir Authors AC 445 Name deletefile delete a file f deletefilefilename Parameters filename a file name existing or not f t or f Description delete a file if file has been deleted it will return t else f Examples fd mopenTMPDIRfiletodeletetxtwt mclosefd if fileinfoTMPDIRfiletodeletetxt then deletefileTMPDIRfiletodeletetxtend deletefileTMPDIRnotexistingfile Authors AC 446 Name dir get file list dir path Sdirpath Parameters path a string matrix giving a directory pathname eventually ended by a pattern built with Default value is S a tlist of type dir with fields name date and isdir Description dir can be used to get the files which match the patterns given by the path argument Patterns are given to the unix ls or to the windows dir commands in order to get information on files Thus in order to write portable Scilab script valid wildcard patterns for both os are to be given Note that Pathname conversion is performed and for example SCImodulescoremacrossci is a valid pattern for both unix and windows The name field of the returned variable is the column vector of the file names The date field of the returned variable is the column vector of integers containing a last modification date coded in second from 1 Jan 1970 The isdir field of the returned variable is the column vector of boolean true if the corresponding name is a directory The default display of the returned structure is a column formatted list of files It can be changed redefining the function dirp Examples dir dir SCImodulescoremacrosbin xdirSCImodulescoremacrosbin dtgetdatexdate mprintfs 04d02d02d 02d02d02d xnamedt1 2 6 79 See Also listfiles findfiles ls fileinfo date 447 Name dirname get directory from filenames dirs dirnamefilesflag flagexpand Parameters files a string matrix giving a set of file names flagflagexpand boolean optional parameters default value t filesdir string matrices Description dirname return the dirname of the file entries given in files If flag is true the files are first converted to the target type given by the MSDOS variable Moreover if flagexpand is true leading strings like HOME SCI or are expanded using environment variables Note that dirnamefilesf can give erroneous results if pathnames given in files do not follow the convention given by the MSDOS variable Examples filesdirnameSCImodulesfileiomacrospoosci filesdirnameSCImodulesfileiomacrospoosci filesdirnameSCImodulesfileiomacrospooscik See Also basename listfiles pathconvert 448 Name dispfiles display opened files properties dispfilesunits Parameters units a vector of numbers the files logical units By default all opened files Description dispfiles displays properties of currently opened files Examples dispfiles See Also file mopen Authors S Steer 449 Name fileext returns extension for a file path extension fileextfullpath Parameters fullpath a character string the given file path extension a character string the extension part is any or Description extensionfileextfullpath splits the fullpath character string in the extension part in cluding the dot Examples extension fileextSCIetcscilabstart extension fileextSCIetcscilabstartSCIetcscilabquit See Also fileparts Authors Allan CORNET 450 Name fileparts returns the path filename and extension for a file path pathfnameextensionfilepartsfullpath vfilepartsfullpathsel Parameters fullpath a character string the given file path sel a optional character string selector with posible values path fname or extension path a character string the path of the directory pointed to by fullpath fname a character string the filename part is any or extension a character string the extension part is any or value a character string depending on sel value Description pathfnameextensionfilepartsfullpath splits the fullpath character string in its three parts the path of the directory pointed to the filename part the extension part including the dot Examples pathfnameextensionfilepartsSCIetcscilabstart filepartsSCIetcscilabstartextension See Also pathconvert basename fullfile Authors Serge Steer INRIA 451 Name filesep returns directory separator for current platform s filesep Parameters s a string Description returns directory separator on Linux or on Windows Examples filesep Authors AC 452 Name findfiles Finding all files with a given filespec f findfiles ffindfilespath ffindfilespathfilespec Parameters path a path filespec a spec file example sce f returns a string matrix of filenames Description Finding all files with a given filespec Examples ffindfiles ffindfilesSCI ffindfilesSCImodulescoremacrossci See Also listfiles Authors AC 453 Name fprintf Emulator of C language fprintf function fprintffileformatvalue1valuen Parameters format a Scilab string Specifies a character string combining literal characters with conversion specifi cations valuei Specifies the data to be converted according to the format parameter str column vector of character strings file a Scilab string specifying a file name or a logical unit number see file Note that is file0 the message will be display on standard error stream stderr Description Obsolete function use preferabily the mfprintf function which is much more compatible with the C fprintf functionalities The fprintf function converts formats and writes its value parameters under control of the format parameter to the file specified by its file parameter The format parameter is a character string that contains two types of objects Literal characters which are copied to the output stream Conversion specifications each of which causes zero or more items to be fetched from the value parameter list see printfconversion for details If any values remain after the entire format has been processed they are ignored Examples ufileopenresultsunknown open the result file t0012pi for tkt fprintfutime 63f value 63ftksintk write a line end filecloseu close the result file fprintf0My error which is going to be displayed on the stderr See Also mfprintf string print write format disp file printf sprintf printfconversion 454 Name fprintfMat Write a matrix in a file fprintfMatfileM formattext Parameters fil a string the pathname of the file to be written M A matrix of real numbers format a character string a C like format This is an optional parameter the default value is f text a string matrix giving non numerical comments stored at the beginning of the file Description The fprintfMat function writes a matrix in a formated file Each row of the matrix give a line in the file If text is given then the elements of text are inserted columnwise at the beginning of the file one element per line Examples n50 arandnnu fprintfMatTMPDIRMata52f a1fscanfMatTMPDIRMat See Also mclose meof mfprintf mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 455 Name fscanf Converts formatted input read on a file v1vnfscanf fileformat Parameters format Specifies the format conversion file Specifies the input file name or file number Description The fscanf functions read character data on the file specified by the file argument interpret it according to a format and returns the converted results The format parameter contains conversion specifications used to interpret the input The format parameter can contain whitespace characters blanks tabs newline or formfeed that except in the following two cases read the input up to the next nonwhitespace character Unless there is a match in the control string trailing white space including a newline character is not read Any character except percent sign which must match the next character of the input stream A conversion specification that directs the conversion of the next input field see scanfconversion for details See Also printf read scanf sscanf mfscanf scanfconversion 456 Name fscanfMat Reads a Matrix from a text file MfscanfMatfilename MtextfscanfMatfilename Parameters filename a character string giving the name of the file to be scanned M Output variable A matrix of real numbers text Output variable A string matrix Description The fscanfMat function is used to read a scalar matrix from a text file The first nonnumeric lines of the file are returned in text if requested and all the remaining lines must have the same number of columns column separator are assumed to be white spaces or tab characters The number of columns of the matrix will follow the number of columns found in the file and the number of lines is fetched by detecting eof in the input file This function can be used to read back numerical data saved with the fprintfMat Examples fdmopenTMPDIRMatw mfprintffdSome text mfprintffdSome text again arand66 for i16 for j16 mfprintffd52f aijend mfprintffd end mclosefd a1fscanfMatTMPDIRMat See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 457 Name fullfile Build a full filename from parts f fullfilevarargin Parameters varargin all directories and filename used to build the full filename at least one directory and filename f full filename Description f fullfilevarargin builds a full filename taking care of platform on which it is run and handling the cases when the directories begin or end with a directory separator Examples ffullfilehomescilabmacrosutilfullfilesci ffullfileCscilabmacrosutilfullfilesci See Also pathconvert fileparts Authors VC 458 Name fullpath Creates an full path name for the specified relative path name res fullpathrelativepath Parameters res a string relativepath a string Description Creates an full path name for the specified relative path name On linux relativepath needs to exist Examples mkdirTMPDIRniv1 mkdirTMPDIRniv1niv2 mputl TMPDIRniv1testtxt cdTMPDIRniv1niv2 fullpathtesttxt Authors AC 459 Name getdrives Get the drive letters of all mounted filesystems on the computer drives getdrives Parameters drives a matrix of strings Description Get the drive letters of all mounted filesystems on the computer returns the roots of all mounted filesystems on the computer as a matrix of strings For Linux this list consists solely of the root directory Examples getdrives Authors AC 460 Name getlongpathname get long path name Only for Windows longpathgetlongpathnameshortpath longpathbOKgetlongpathnameshortpath Parameters shortpath A character string or matrix of strings the short path longpath A character string or matrix of strings the long path bOK A boolean T or a matrix of boolean if path has been converted else F Description The getlongpathname primitive converts the specified path to its long form It no long path is found this primitive returns the specified name Examples longpathbOKgetlongpathnameSCI longpathsbOKsgetlongpathnameSCISCI See Also getshortpathname Authors Allan CORNET 461 Name getshortpathname get short path name Only for Windows shortpathgetshortgpathnamelongpath shortpathbOKgetshortpathnamelongpath Parameters longpath A character string or matrix of strings the long path shortpath A character string or a matrix of strings the short path bOK A boolean T or a matrix of boolean if path has been converted else F Description The getshortpathname primitive converts the specified path to its short form Examples shortpathbOKgetshortpathnameSCI shortpathsbOKsgetshortpathnameSCISCI See Also getlongpathname Authors Allan CORNET 462 Name io variable returns standard input and standard output file descriptor io1 io2 Description io1 returns standard input file descriptor 5 io2 returns standard ouput file descriptor 6 file descriptor 0 is the standard error Examples mfprintfio2Scilab stdout C mfprintf0Scilab stderr C writeio2Scilab stdout Fortran write0Scilab stderr Fortran unitstypnamesfile See Also write mfprintf file 463 Name isdir checks if argument is a directory path risdirpath Parameters path a character string or a matrix of strings the file pathname r a boolean true if path is a path to a directory Description risdirpath checks if path is a path to a directory Reference This function is based on the C function stat The SCI and shortcuts for Scilab directory and home directory are handled Examples isdirTMPDIR isdir SCIetcscilabstart See Also fileinfo Authors S Steer INRIA 464 Name isfile checks if argument is a file b isfilefilenames Parameters files a character string or a string matrix x an matrix of boolean t is filename exists Description x isfilefilename checks if filename is existing file or not a directory is not a file see isdir Examples cd SCI filenames ls isfilefilenames isfilefilenames isfileSCI etc isdirSCI etc See Also fileinfo isdir Author AC 465 Name listfiles list files files listfilespaths flagflagexpand Parameters paths a string matrix giving a set of pathnames eventually ended by a pattern built with flagflagexpand boolean optional parameters default value t files a string matrix Description listfiles can be used to list the files which match the patterns given by one of the paths entries Patterns are given to the unix ls or to the windows dir commands in order to get information on files Thus in order to write portable Scilab script valid wildcard patterns for both os are to be given Note that Pathname conversion is performed and for example SCIcoremacrossci is a valid pattern for both unix and windows if flag is true the pathnames given by paths are converted according to the MSDOS value See pathconvert Moreover if flagexpand is true leading strings like HOME SCI or are ex panded using environment variables Examples fileslistfilesSCImodulescoremacrossciSCImodulescoremacrosbin See Also findfiles basename pathconvert 466 Name listvarinfile list the contents of a saved data file listvarinfilefilename namstypsdimsvolslistvarinfilefilename Parameters filename character string the pathname of the file to be inspected nams character array names of the variables saved in the file dims list dimensions of the variables saved in the file typs numeric array types of the variables saved in the file vols numeric array size in bytes of the variables saved in the file Description This utility function lists a la whos the variables contained in a Scilab data file produced by save Remark hypermatrices are reported as plain mlists rationals and statespaces are reported as plain tlists graphic handles are not recognized Examples aeye22 bint16onesa crand233 savevalsdatabc listvarinfilevalsdat See Also whos save load saveformat type Authors Serge Steer 31 Jan 2001 reediting by Enrico Segre 467 Name ls show files ls path options filesls path Parameters path a string matrix giving a directory pathname eventually ended by a pattern built with Default value is files a string column vector By default it contains a column formatted output if one of the option is 1 files contains an entry for each files Description ls can be used to list the files which match the patterns given by the path argument Patterns are given to the unix ls or to the windows dir commands in order to get information on files Thus in order to write portable Scilab script valid wildcard patterns for both os are to be given Note that Pathname conversion is performed and for example SCImodulescoremacrossci is a valid pattern for both unix and windows If you want to get a vector of all files matching a pattern use preferabily the listfiles or the dirfunction Please note that starting from the version 50 of Scilab the second input argument has been removed a sequence of strings which can be added under Unix systems the Unix ls command options This option has been removed mainly for security and portability reasons Examples ls ls SCImodulescoremacrossci xlsSCImodulescoremacrossci See Also listfiles findfiles dir fileinfo 468 Name maxfiles sets the limit for the number of files a scilab is allowed to have open simultaneously r maxfilesnewnumbermax Parameters newnumbermax a integer the new value r effective new value Description sets the limit for the number of files a scilab is allowed to have open simultaneously Minimum 20 Maximum 100 Default 20 Examples rmaxfiles50 See Also mopen 469 Name mclearerr reset binary file access errors mclearerrfd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 Description The function clearerr is used to resets the error indicator and EOF indicator to zero See Also merror mclose mopen mput mget mgetstr mputstr meof mseek mtell 470 Name mclose close an opened file errmclosefd mcloseall Parameters fd scalar The fd parameter returned by the function mopen is used as a file descriptor its a positive integer err a scalar Error indicator vector Description mclose must be used to close a file opened by mopen If fd is omitted mclose closes the last opend file mcloseall closes all files opened by fileopen or mopen Be careful with this use of mclose because when it is used inside a Scilab script file it also closes the script and Scilab will not execute commands written after mcloseall See Also meof mfprintf fprintfMat mfscanf fscanfMat mget mgetl mgetstr mopen mprintf mput mputl mputstr mscanf mseek mtell file mdelete 471 Name mdelete Delete files mdeletefilename Parameters filename a character string The pathname of the files to delete Description mdelete may be used to delete a file or a set of files if filename contains metacharaters Note that mdelete does not ask for confirmation when you enter the delete command To avoid accidentally losing files make sure that you have accurately specified the items you want deleted See Also mopen mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell 472 Name meof check if end of file has been reached errmeoffd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 err scalar Error indicator Description The function meof will return a non null value if end of file has been reached in a previous call to mget or mgetstr The function clearerr is used to reset the error flag and EOF flag to zero See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 473 Name merror tests the file access errors indicator err merrorfd errmsg merrorfd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 err scalar returns the error status number errnum of the most recent file IO operation associated with the specified file If the most recent IO operation performed on the specified file was successful the value of msg is empty and merror returns an err value of 0 msg string returns the error string message Description The function merror is used to tests the file access errors indicator returning nonzero if it is set The error indicator can only be reset by the mclearerr function A nonzero err indicates that an error occurred in the most recent file IO operation The value of message is a string that can contain information about the nature of the error If the message is not helpful consult the C runtime library manual for your host operating system for further details Examples fd mopenTMPDIR filetxttxtwt errmsg merrorfd if err 0 then printfProblem end mclosefd See Also mclearerr mclose mopen mput mget mgetstr mputstr meof mseek mtell 474 Name mfprintf converts formats and writes data to a file mfprintffdformata1an Parameters fd scalar file descriptor given by mopen its a positive integer if fd equals 0 redirection in stderr if fd equals 6 redirection in stdout OBSOLETE The value 1 refers to the default file ie the last opened file format a Scilab string describing the format to use to write the remaining operands The format operand follows as close as possible the C printf format operand syntax str a character string string to be scanned a1an Specifies the data to be converted and printed according to the format parameter Description The mfprintf function is a interface for Ccoded version of fprintf functions The mfprintf function writes formatted operands to the file specified by the file desciptor fd The argument operands are formatted under control of the format operand this function may be used to output column vectors of numbers and string vectors without an explicit loop on the elements In that case this function iterates on the rows The shortest vector gives the number of time the format has to be iterated An homogeneous sequence of identical type parameters can be replaced by a matrix Examples fd mopenTMPDIRtexttxtwt mfprintffdhello s d world1 mfprintffdhello s d scilab2 mclosefd if isdefeditor funptreditor0 then editorTMPDIRtexttxt end mfprintf0stderr output mfprintf6stdout output See Also mclose meof fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete printfconversion 475 Name mscanf reads input from the standard input interface to the C scanf function mfscanf reads input from the stream pointer stream interface to the C fscanf function msscanf reads its input from the character string interface to the C sscanf function nv1vnmfscanfniterfdformat Lmfscanfniter fdformat nv1vnmscanfniter format Lmscanfniterformat nv1vmmsscanfniterstrformat Lmsscanfniter strformat Parameters format a Scilab string describing the format to use to write the remaining operands The format operand follows as close as possible the C printf format operand syntax as described in scanfconversion fd The fd parameter returned by the function mopen is used as a file descriptor its a positive inte ger The value 1 refers to the last opened file str a Scilab string or string vector niter an integer the number of times the format as to be used n an integer the number of data read or 1 if EOL has been encountered before any datum has been read vi Each function reads characters interprets them according to a format and stores the results in its output arguments If more than n output arguments are provided the last ones vn1vm are set to empty matrices L if all data are homogeneous they are stored in a unique vector which is returned otherwise subse quences of same data type are stored in matrices and an mlist with type cblock containing all the built matrices is returned Description The mfscanf function reads characters from the stream fd The mscanf function reads characters from Scilab window The msscanf function reads characters from the Scilab string str The niter optional argument specifies how many time the format has to used One iteration produces one line in the output matrix If niter1 the function iterates up to the end of file The niter default value is 1 comments about precision mscanf 476 mfscanf is based on C function fscanf If you use f g e as format your datas will be cast to float and returned in a scilab variable This scilab variable is a double then you can have some precision errors In this case it is better to use lg format Examples Simple use s1 13 a string nabmsscanfsi e Lmsscanfsi e Formats samples msscanf 12 cccc scan characters msscanf0xabcx scan with hexadecimal format msscanf012345abczoo09abcs notation reading float and double msscanf4345988g4345988 scan as float msscanf4345988lg4345988 scan as double scanning multiline data files create a file with data umopenTMPDIRfoow t001pimfprintfu63f 63f tsint mcloseu umopenTMPDIRfoor open the file for reading read the file line by line nabmfscanfue e first line using mutiple LHS syntax lmfscanfue e second one using single LHS syntax use niter to read 5 more lines lmfscanf5ue e use niter1 to read up to the end of file lmfscanf1ue e mcloseu close the file scanning multiline strings vectors use niter to scan a string vector nNamesAgesmsscanf1Alain 19Pierre 15Tom 12s d Dmsscanf1Alain 19Pierre 15Tom 12s d typeofD NamesD1 strings mscanf 477 AgeD2 numerical values See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mput str mscanf mseek mtell mdelete scanfconversion 478 Name mget reads byte or word in a given binary format and convert to double mgeti reads byte or word in a given binary format return an int type xmgetntypefd xmgetintypefd Parameters n a positive scalar The number of items to be read fd a scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 type a string Give the binary format used to write all the entries of x x a vector of floating point or integer type numbers Description The mget function reads data in the input specified by the stream parameter fd and returns a vector of floating point data The mgeti function reads data in the input specified by the stream parameter fd and returns a vector of integer data Data is read at the position at which the file pointer is currently pointing and advances the indicator appropriately The type parameter is a conversion specifier which may be set to any of the following flag characters with default value l Note On Windows default behavior is to skip byte 13 0x0D mopen should be called with the b option eg fd1mopenfile1rb so that all bytes will be read without exception Data type d double f float l long i int s short c character Optional flag mget 479 u unsigned in combination with one of the above types l little endian in combination with one of the above types b big endian in combination with one of the above types Bytes read are automatically swapped if necessary by checking littleendian status This default swapping behavior can be suprressed by adding a flag in the mopen function Formats l d and f are only valid with the mget function Examples file1 test1bin file2 test2bin fd1mopenfile1wb fd2mopenfile2wb mput1996ullfd1 mput1996ullfd2 mclosefd1 mclosefd2 fd1mopenfile1rb if 1996mget1ullfd1 writeio2Bugend fd2mopenfile2rb if 1996mget1ullfd2 writeio2Bugend mclosefd1 mclosefd2 See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mgetl mgetstr mopen mprintf mput mputl mputstr mscanf mseek mtell mdelete 480 Name mgetl read lines from an ascii file txtmgetlfiledesc m Parameters filedesc a character string giving the file name or a logical unit returned by mopen m an integer scalar number of lines to read Default value is 1 txt a column vector of string Description mgetl function allows to read a lines from an ascii file If m is omitted or is 1 all lines till end of file occurs are read If m is given mgetl tries to read exactly m lines This option is useful to sequentialy read part of a file In this case if an end of file EOF occurs before m lines are read the read lines are returned it is possible to check if EOF had occured using the meof function issued mgetl allows to read files coming from Unix Windows or Mac operating systems Examples mgetlSCIetcscilabstart5 mgetl SCImoduleselementaryfunctionsmacroserfsci fdmopenSCIetcscilabstartr mgetlfd10 mclosefd See Also mputl mclose mfscanf mget mput mgetstr mopen read Authors S Steer 481 Name mgetstr read a character string strmgetstrn fd Parameters n a positive scalar The number of character to read fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 str a character string Description mgetstr function allows to read a character string in a binary file If EOF is reached before read com pletion only the properly read values will be returned Examples open file descriptor as text with read mode fdr mopenSCIACKNOWLEDGEMENTSrt get 100 characters of fdr strs1 mgetstr100 fdr get 200 next characters of fdr strs2 mgetstr200 fdr close file descriptor mclosefdr See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mput str mscanf mseek mtell mdelete 482 Name mkdir Make new directory mkdirdirname mkdirparentdirnewdir statusmkdir statusmsgmkdir Description mkdirdirname creates the directory dirname in the current directory if dirname represents a rela tive path Otherwise dirname represents an absolute path and mkdir attempts to create the absolute directory dirname mkdirparentdirdirname creates the directory dirname in the existing directory parentdir where parentdir is an absolute or relative pathname statusmessage mkdirdirname creates the directory dirname in the existing directory parentdir returning the status a message Here status is 1 for success 2 if it already exists 2 if it is a filename and 0 otherwise Examples Absolute pathname mkdirTMPDIRmkdirexample1 status2 mkdirTMPDIRmkdirexample2 status3msg3 mkdirTMPDIRmkdirexample3 Absolute pathname parentdir dirname status4msg4 mkdirTMPDIRmkdirexample4 Relative pathname cd TMPDIR status5msg5 mkdirmkdirexample5 status6msg6 mkdirmkdirexample5mkdirexample6 See Also cd dir rmdir Authors AC 483 Name mopen open a file fderrmopenfile mode swap Parameters file a character string The pathname of the file to open mode a character string that controls whether the file is opened for reading r writing w or appending a and whether the file is opened for updating The mode can also include a b parameter to indicate a binary file swap a scalar If swap is present and swap0 then automatic bytes swap is disabled err a scalar Error indicator see merror fd scalar The fd parameter returned by the function mopen is used as a file descriptor its a positive integer Description mopen may be used to open a file in a way compatible with the C fopen procedure Without swap argument the file is supposed to be coded in little endian IEEE format and data are swaped if nec essary to match the IEEE format of the processor The mode parameter controls the access allowed to the stream The parameter can have one of the following values In this list of values the b character indicates a binary file r Opens the file for reading rb Opens a binary file for reading rt Opens a text file for reading w Creates a new file for writing or opens and truncates a file to zero length wb Creates a new binary file for writing or opens and truncates a file to zero length wt Creates a text binary file for writing or opens and truncates a file to zero length a or ab Appends opens a file for writing at the end of the file or creates a file for writing r or rb Opens a file for update reading and writing mopen 484 w or wb Truncates to zero length or creates a file for update a or ab Appends opens a file for update writing at the end of the file or creates a file for writing When you open a file for update you can perform both input and output operations on the resulting stream However an output operation cannot be directly followed by an input operation without a filepositioning operation mseek function Also an input operation cannot be directly followed by an output operation without an intervening file positioning operation unless the input operation encounters the end of the file When you open a file for append that is when the mode parameter is a or a it is impossible to overwrite information already in the file You can use the fseek function to reposition the file pointer to any position in the file but when output is written to the file the current file pointer is ignored All output is written at the end of the file and the file pointer is repositioned to the end of the output To open files in a way compatible with Fortran like functions use function file open a SCIACKNOWLEDGEMENTS as text and read only fdr mopenSCIACKNOWLEDGEMENTSrt read five lines of fdr mgetlfdr 5 another way to read file here read five words mfscanf5fdrs close file descriptor associated to SCIACKNOWLEDGEMENTS as text and read only mclosefdr open a file as text with write property fdw mopenTMPDIRwritetxtwt write a line in fdw mputlThis is a line of text fwdw mclosefdw read text fdr2 mopenTMPDIRwritetxtrt mgetlfdr2 mclosefdr2 read write a file as binary first we write file fdwb mopenTMPDIRwritereadbinwb put values as binary mput2003lfdwb mput2008ifdwb mput2012sfdwb mput98cfdwb close file descriptor associated to TMPDIRwritereadbin mclosefdwb mopen 485 we read file fdrb mopenTMPDIRwritereadbinrb mgetfdrb l mgetfdrb i mgetfdrb s mgetfdrb c mclosefdrb See Also mclose merror meof mfprintf fprintfMat mfscanf fscanfMat mget mgetl mgetstr mopen mprintf mput mputl mputstr mscanf mseek mtell mdelete 486 Name movefile Move file or directory movefilesourcedestination statusmessage movefilesourcedestination Description movefilesourcedestination moves the file or directory source and subdirectories to the file or directory destination If source is a directory destination can not be a file movefile replaces existing files without warning status message movefilesourcedestination moves source to destination returning the status and a message Whatever the operating system if the move succeeds the status is 1 and the message is empty if the move fails the status is 0 and the message is not empty Examples copyfileSCIetcscilabstartTMPDIRscilabstart statusmessage movefileTMPDIRscilabstartTMPDIRrenamedscilabstart See Also copyfile Authors Allan CORNET 487 Name mput writes byte or word in a given binary format mputx typefd Parameters x a vector of floating point or integer type numbers fd scalar The fd parameter returned by the function Default value is 1 which stands for the last mopen opened file type a string Give the binary format used to write all the entries of x Description The mput function writes data to the output specified by the stream parameter fd Data is written at the position at which the file pointer is currently pointing and advances the indicator appropriately The type parameter is a conversion specifier which may be set to any of the following flag characters with default value l lisuluiusdfcuc for writing respectively a long an int a short an unsigned long an unsigned int an unsigned short a double a float a char and an unsigned char The bytes which are wrote are automatically swapped if necessary by checking littleendian status in order to produce machine independent binary files in littleendian mode This default swapping mode can be suppressed by adding a flag in the mopen function l or b It is also possible to write in littleendian or bigendian mode by adding a l or b character at the end of a type specification For example db will write a double in bigendian mode Examples filen testbin mopenfilenwb mput1996lmput1996imput1996smput98c force littleendian mput1996llmput1996ilmput1996slmput98cl force bigendian mput1996lbmput1996ibmput1996sbmput98cb mclose mopenfilenrb if 1996mget1l then pauseend if 1996mget1i then pauseend if 1996mget1s then pauseend if 98mget1c then pauseend mput 488 force littleendian if 1996mget1ll then pauseend if 1996mget1il then pauseend if 1996mget1sl then pauseend if 98mget1cl then pauseend force bigendian if 1996mget1lb then pauseend if 1996mget1ib then pauseend if 1996mget1sb then pauseend if 98mget1cb then pauseend mclose See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetl mgetstr mopen mprintf mputl mputstr mscanf mseek mtell mdelete 489 Name mputl writes strings in an ascii file r mputltxt filedesc Parameters r returns t or f to check if function has correctly written on the file filedesc A character string giving the name of the file or a logical unit returned by mopen txt a vector of strings Description mputl function allows to write a vector of strings as a sequence of lines in an ascii file Examples fd mopenTMPDIRtextmputltxtwt mputlHello Worldfd mclosefd fd mopenTMPDIRtextmputltxtrt dispmgetlfd mclosefd See Also mget mgetl mclose mfprintf mput mputstr mopen write Authors S Steer Allan CORNET 490 Name mputstr write a character string in a file mputstrstr fd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 str a character string Description mputstr function allows to write a character string in a binary file See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 491 Name mseek set current position in binary file mseekn fd flag Parameters n a positive scalar The offset from origin in number of bytes fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 flag a string specifies the origin Default value set Description The function mseek sets the position of the next input or output operation on the stream fd The new position is at the signed distance given by n bytes from the beginning from the current position or from the end of the file according to the flag value which can be set cur or end mseek allows the file position indicator to be set beyond the end of the existing data in the file If data is later written at this point subsequent reads of data in the gap will return zero until data is actually written into the gap mseek by itself does not extend the size of the file Examples file3test3bin fd1 mopenfile3wb for i110 mputid end mseek0 mput678d mseek0fd1end mput932d mclosefd1 fd1 mopenfile3rb resmget11d res1111 res11678res1932 if res1res writeio2Bugend mseek0fd1set trying to read more than stored data res1mget100dfd1 if res1res writeio2Bugend meoffd1 mclearerrfd1 mclosefd1 See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 492 Name mtell binary file management mtellfd Parameters fd scalar The fd parameter returned by the function mopen 1 stands for last opened file Default value is 1 Description The function mtell returns the offset of the current byte relative to the beginning of the file associated with the named stream fd See Also mclose meof mfprintf fprintfMat mfscanf fscanfMat mget mgetstr mopen mprintf mput mputstr mscanf mseek mtell mdelete 493 Name pathconvert pathnames convertion between posix and windows pathspathconvertpaths flagtrail flagexpand type Parameters paths a string matrix giving a set of pathnames flagtrail boolean optional parameters Its default value is TRUE flagexpand boolean optional parameter Its default value depends on the MSDOS variable type a string u or w Description pathconvert can be used to convert a set of pathnames given by a string matrix paths from windows native filename to posixstyle pathnames and back The target style is given by the optional string type which can be u for Unix or w for Windows The default style is set according to the value of MSDOS If MSDOS is TRUE resp FALSE then default type is w resp u Windows pathnames starting with name are converted to pathnames starting with cyg drivename using the cygwin convention flagtrail is an optional boolean parameter When its value is TRUE default value a trailing separator or is added at the end of the path if it was missing If flagtrail is set to FALSE the trailing separator is removed flagexpand is an optional boolean parameter When its value is TRUE leading strings like HOME SCI or are expanded using environment variables Examples pathconvertSCImodulesfileiomacrosfoosciffu pathconvertSCImodulesfileiomacrosfoosciffw pathconvertSCImodulesfileiomacrosfoosciftw pathconvertHOMEmodulesfileiomacrosfooscittw pathconvertctmpftu pathconvertcygdrivectmpffw See Also basename listfiles 494 Name pathsep returns path separator for current platform s pathsep Parameters s a string Description returns path separator on Linux or on Windows Examples pathsep Authors AC 495 Name pwd print Scilab current directory pwd get Scilab current directory pwd xpwd Description pwd returns in ans the Scilab current directory xpwd returns in x the Scilab current directory Examples pwd xpwd See Also chdir cd 496 Name removedir Remove a directory removedirdirname status removedirdirnames Description removedirdirname removes the directory dirname from the current directory If the directory is not empty files and subdirectories are removed If dirname is not in the current directory specify the relative path to the current directory or the full path for dirname status removedirdirname removes the directory dirname and its contents from the current direc tory returning the status Here status is T for success and is F for error removedir is used by rmdir Examples createdirSCIHOMEDirectorytest removedirSCIHOMEDirectorytest See Also mkdir rmdir Authors AC 497 Name rmdir Remove a directory rmdirdirname rmdirdirnames statusmessage rmdirdirnames Description rmdirdirname removes the directory dirname from the current directory If the directory is not emp ty you must use the s argument If dirname is not in the current directory specify the relative path to the current directory or the full path for dirname rmdirdirnames removes the directory dirname and its contents from the current directory status message rmdirdirnames removes the directory dirname and its contents from the current directory returning the status and a message Here status is 1 for success and is 0 for error Examples mkdirSCIDirectory rmdirSCIDirectory See Also cd dir mkdir Authors AC 498 Name saveformat format of files produced by save Description Variables are saved by Scilab with the save function in the following format each variable record is appended consecutively to the file The variable record begins with 6 long integer holding the variable name in encoded format see the Remarks section below After that comes the variable type long integer then depending on it for Floating matrices type 1 rowsize m a long integer columnsize n a long integer realcomplex flag it a long integer in 01 data nmit1 doubles Polynomials type 2 and Size implicit indices type 129 rowsize m a long integer columnsize n a long integer realcomplex flag it long integer in 01 formal variable name 16 bytes indextable mn1 long integers data N1it1 doubles where N is the value of the last entry of the indextable Booleans type 4 rowsize m a long integer columnsize n a long integer data nm long integers Floating sparse matrices type 5 rowsize m a long integer columnsize n a long integer realcomplexflag it a long integer in 01 totalnumberofnonzeroelements nel a long integer numberofnonzeroelementsperrow m long integers columnindexnonzeroelements nel long integers nonzerovalues nelit1 doubles Boolean sparse matrices type 6 rowsize m a long integer columnsize n a long integer unused it a long integer saveformat 499 totalnumberofnonzeroelements nel a long integer numberofnonzeroelementsperrow m long integers columnindexnonzeroelements nel long integers Matlab sparse matrix type 7 rowsize m a long integer columnsize n a long integer realcomplexflag it a long integer in 01 totalnumberofnonzeroelements nel a long integer numberofnonzeroelementspercolumn n long integers rowindexnonzeroelements nel long integers nonzerovalues nelit1 doubles Integer matrices type 8 rowsize m a long integer columnsize n a long integer integertype a long integer 124 or 111214 for signed and unsigned 124 bytes integers data nm bytes for integertype 1 or 11 nm short integers for integertype 2 or 12 nm long integers for integertype 4 or 14 handles type 9 version 4 bytes rowsize m a byte columnsize n a byte data mn serializationrecords A serializationrecord is a flat representation of the C data structure associated with the corre sponding graphic object Each graphic object is defined by a recursive set of properties see the get function The saved serializationrecord of a graphic object is structured as follow typelength n a byte type n bytes the ascii codes of the type name propertyvalues record variable length Strings type 10 rowsize m a long integer columnsize n a long integer indextable nm1 long integers data N long integers the Scilab encoding of the characters see code2str where N is the value of the last entry of the indextable Uncompiled functions type 11 nout long integer saveformat 500 lhsnames 6nout long integers see the Remarks section below nin long integer rhsnames 6nin long integers see the Remarks section below codelength N a long integer code N long integers Compiled functions type 13 nout long integer lhsnames 6nout long integers see the Remarks section below nin long integer rhsnames 6nin long integers see the Remarks section below pseudocodelength N a long integer pseudocode N long integers Libraries type 14 pathlength np a long integer pathname np long integers the path character codes sequence see code2str number of names nn long integer names 6nn long integers see the Remarks section below Lists type 15 tlists type 16 mlists type 17 number of fields n a long integer index n1 long integers variablessequence n variables each one written according to its format Pointers type 128 Not handled Function pointers type 130 functionptr a long integersee funptr functionnamecode 6 long integerssee the Remarks section below Remarks Numbers long interger short integers double are stored using the little endian convention The variable names are stored as a sequence of 6 long integers with a specific encoding see the cvnamef file for details See Also save load listvarinfile type typeof Authors compiled by Enrico Segre 501 Name scanf Converts formatted input on standard input v1vnscanf format Parameters format Specifies the format conversion Description The scanf functions get character data on standard input io1 interpret it according to a format and returns the converted results The format parameter contains conversion specifications used to interpret the input The format parameter can contain whitespace characters blanks tabs newline or formfeed that except in the following two cases read the input up to the next nonwhitespace character Unless there is a match in the control string trailing white space including a newline character is not read Any character except percent sign which must match the next character of the input stream A conversion specification that directs the conversion of the next input field see scanfconversion for details See Also printf read fscanf sscanf scanfconversion 502 Name scanfconversion scanf sscanf fscanf conversion specifications Description Each conversion specification in the format parameter contains the following elements The character percent sign The optional assignment suppression character An optional numeric maximum field width A conversion code The conversion specification has the following syntax widthsizeconvcode The results from the conversion are placed in vi arguments unless you specify assignment suppres sion with asterisk Assignment suppression provides a way to describe an input field that is to be skipped The input field is a string of nonwhitespace characters It extends to the next inappropriate character or until the field width if specified is exhausted The conversion code indicates how to interpret the input field You should not specify the vi param eter for a suppressed field You can use the following conversion codes Accepts a single percent sign input at this point no assignment is done d i Accepts a decimal integer u Accepts an unsigned decimal integer o Accepts an octal integer x Accepts a hexadecimal integer efg Accepts a floatingpoint number The next field is converted accordingly and stored through the corresponding parameter which should be a pointer to a float The input format for floatingpoint numbers is a string of digits with the following optional characteristics It can be a signed value It can be an exponential value containing a decimal point followed by an exponent field which consists of an E or an e followed by an optionally signed integer It can be one of the special values INF NaN scanfconversion 503 s Accepts a string of characters c character value is expected The normal skip over white space is suppressed lg get value as a double See Also scanf scanf fscanf Parte VI Biblioteca de Gráficos 505 Name GlobalProperty Customização de aparência dos objetos curvas superfícies num comando plot ou surf Nenhuma GlobalProperty é um argumento opcional que pode ser utilizado dentro de um comando plot ou surf Permite uma customização global de todas as novas linhas esboçadas respectivamente superfícies Deve ser fornecido como o parPropertyName PropertyValue Vários pares podem ser ajustados ao mesmo tempo PropertyName deve ser um string definido a propriedade a ser ajustada PropertyValue pode ser um real um inteiro ou um string um escalar ou matriz de dependendo do tipo de propriedade usada Por exemplo para especificar um estilo de linha traço longo vermelho cor com marca diamante marca a seqüência deve ser ColoredLineStMarkerdiam Como você pode ver uma escrita completa dos nomes e valores das propriedades não é necessária mas os argumentos especificados em qualquer ordem não podem ser ambíguos Além disso a especificação dos strings não diferencia letras minúsculas de maiúsculas GlobalProperty é predominante em todos os LineSpec anteriormente citados Descrição Aqui está uma lista completa dos PropertyName que você pode especificar utilizando plot ou surf e seus associados disponíveis PropertyValue Se não forem especificadas estas propriedades estão disponíveis para ambos objetos Polyline e Fac3d criados respectivamente por plot e surf e como dito anteriormente eles são aplicados aos novos objetos criados linhas ou superfícies Algumas vezes você pode ter dois PropertyName correspondentes a uma propriedade o primeiro é o nome Matlab equivalente O segundo é o nome padrão utilizado pelo Scilabie Color ou Foreground para uma linha ver abaixo CData or ColorData uma matriz de reais especificando as cores em todos os pontos definidos pela matriz Z TEsta propriedade esta ligada à propriedade datacolor do objeto ver surfaceproperties Note que esta propriedade está disponível para superfícies apenas CDataMapping ou ColorDataMapping um string com valor scaled ou direct Se um datacolor estiver ajustado ca da índice de cor especifica um único valor para cada vértice cdatamapping determina se estes índices estão em escala para serem mapeados linearmente no mapa de cores corrente modoscaled ou aponta diretamente para este mapa de cores modo direct Esta pro priedade é útil quando colorflag é igual a 23 ou 4 Note que esta propriedade só existe em entidades Fac3d Note também que plot3d tem modo direct por padrão e surf tem modo scaled por padrão Clipping um string on ou off definindo o modo de recorte on por padrão É equivalente à propriedade clipstate property Este campo contém a propriedade ver polylineproperties Note que esta propriedade ainda não está disponível para entidades de superfícies Color ou Foreground um string definindo uma cor conhecida ver colorlist ou um vetor 1x3 ou 3x1 RGB defin do um número de cor O número de cor é dado como uma tripla R G B correspondendo respec tivamente a to às intensidades de vermelho verde e azul entre 0 e 1 Esta propriedade está lig ada à propriedade foreground do objeto ver polylineproperties Aviso Color não está disponível para objetos superfícies A propriedade Foregroundexiste para objetos superfícies mas está ligada à propriedade do Matlab EdgeColor ver surfaceproperties EdgeColor or Foreground um string definindo uma cor conhecida ver colorlist ou um vetor 1x3 or 3x1 RGB definindo um número de cor O número de cor é dado pela tripla R G B correspondendo respectivamente a to às intensidades de vermelho verde e azul entre 0 e 1 Esta propriedade está ligada à propriedade foreground da superfície ver surfaceproperties Aviso para poligonais a propriedade Foreground existe com um signficado diferente ver acima e EdgeColor não existe FaceColor um string com valor none flat ou interp especificando o modo como as cores das facetas são renderizadas Quando none é selecionado uma malha da superfície é desenhada se flat modo padrão é selecionado os valores Fac3d colordata determinam uma cor GlobalProperty 506 por faceta utilizando a cor do vértice da faceta Se o valor é interp uma gradação interpolada é feita na faceta utilizando colordata para determinar a cor em cada vértice da faceta LineStyle esta propriedade deve ser um string definindo um estilo de linha Esta propriedade está ligada à propriedade linestyle do objeto ver polylineproperties ou surfaceproperties Especificador Estilo de linha linha sólida padrão linha tracejada linha pontilhada linha tracejadapontilhada none nenhuma linha Marker or MarkStyle um string definindo um tipo de marca Note que se você especificar uma marca sem um es tilo de linha ambas linhas com valor padrão sólido hablitado e marcas são desenhadas Esta propriedade está ligada às propriedades markstyle e markmode do objeto ver polylineproperties ou surfaceproperties Especificador Tipo de marca sinal de mais o círculo asterísco ponto x cruz square or s quadrado diamond or d rombo diamante triângulo para cima v triângulo para baixo triângulo para direita triângulo para esquerda pentagram estrela de cinco pontas pentagrama none sem marca padrão MarkerEdgeColor ou MarkForeground um string definindo uma cor conhecidaver colorlist ou um vetor 1x3 ou 3x1 RGB definindo um número de cor O número de cor é dado pela tripla R G B correspondendo respectivamente às intensidades de vermelho verde e azul entre 0 e 1 esta propriedade está ligada à propriedade markforeground do objeto ver polylineproperties ou surfaceproperties MarkerFaceColor ou MarkBackground um string definindo uma cor conhecida ver colorlist ou um vetor 1x3 ou 3x1 RGB definindo um número de cor O número de cor é dado pela tripla R G B correspondendo respectivamente às intensidades de vermelho verde e azul entre 0 e 1 Esta propriedade esta ligada à propriedade markbackground do objeto ver polylineproperties ou surfaceproperties MarkerSize ou MarkSize um escalar definindo o tamanho do marcador em unidade point Esta propriedade está ligada a propriedade marksize do objeto com marksizeunit habilitado para point ver polylineproperties ou surfaceproperties GlobalProperty 507 Visible um string on ou off definindo o modo de visibilidade on por padrão Esta propriedade está ligada à propriedade visible do objeto ver polylineproperties ou surfaceproperties X data um vetor ou matriz de reais redefinindo os dados fornecidos para todas as linhas ou superfícies esboçadas A respeito das dimensões note que estes novos dados devem corresponder a todos os anteriores especificados por X isto é todas as matrizes devem ter as mesmas dimensões Esta propriedade está ligada à propriedade datax do objeto ver polylineproperties ou surfaceproperties Y data um vetor ou matriz de reais redefinindo os dados fornecidos para todas as linhas ou superfícies esboçadas A respeito das dimensões note que estes novos dados devem corresponder a to dos os anteriores especificados por Y data isto é todas as matrizes devem ter as mesmas dimensões Esta propriedade está ligada à propriedade datay do objeto ver polylineproperties ou surfaceproperties Z data quando usado com plot um vetor ou matriz de reais adicionando dados Z para todas as lin has esboçadas com surf uma matriz de reais redefinindo os dados fornecidos para todas as superfícies A respeito das dimensões note que estes novos dados devem corresponder a todos os anteriores especificados por X e Y data Esta propriedade está ligada à propriedade dataz do objeto ver polylineproperties ou surfaceproperties Exemplos com o comando plot x110 Init plotxsinxcoloredlinestmarkermarkeredgcyanmarkerFaceyellowmarkersize5 clf a ordem das combinações e PropertyNamePropertyValue não importa plotxsinxmarkerpmarkerfaccyanmarkersiz10 clf a combinação de LineSpec com GlobalProperty mostra a predominância de Global Property plotxxxcyacolorgrlinestylemarkersqmarkersize6markforegrounredmarkbackgro02 05 06 clf múltiplos esboços com diferentes LineSpecs e finalmente alguns GlobalProperty clf t0pi202pi plottsintrotcostcyatabssintmomarkstyldiam com o comando surf Z 00001 00013 00053 00299 01809 02465 01100 00168 00008 00000 00005 00089 00259 03673 18670 24736 10866 01602 00067 00000 00004 00214 01739 03147 40919 64101 27589 02779 00131 00020 00088 00871 00364 18559 14995 22171 02729 08368 02016 00130 00308 04313 17334 01148 30731 04444 26145 24410 04877 00301 GlobalProperty 508 00336 04990 23552 21722 08856 00531 26416 24064 04771 00294 00137 01967 08083 02289 33983 31955 24338 12129 02108 00125 00014 00017 03189 27414 71622 71361 31242 06633 00674 00030 00002 00104 01733 10852 26741 26725 11119 01973 00152 00005 00000 00012 00183 01099 02684 02683 01107 00190 00014 00000 clf fgcf ffiguresize 610724 subplot211 surfZfacecolinterpydat101110edgecolmage subplot212 surfZedgecobmarkerdmarkersiz9markerfackxdata5041 Ver Também LineSpec plot surf clf polylineproperties surfaceproperties Autor FLeray 509 Name Graphics Resumo da biblioteca de gráficos Desenhos 2d plot2d esboço 2d plot2d2 esboço 2d funções de degraus plot2d3 esboço 2d barras veticais plot2d4 esboço 2d setas fplot2d esboço 2d de uma curva definida por uma função champ esboço de campo vetorial 2d champ1 campo vetorial 2d com setas coloridas fchamp campo direcional de uma EDO 2d de primeira ordem contour2d curvas de nível de uma superfície em um esboço 2d fcontour2d curvas de nível de uma superfície definida por uma função em um esboço 2d grayplot esboço 2d de uma superfície utilizandose cores fgrayplot esboço 2d de uma superfície definida por uma função utilizando cores Sgrayplot esboço 2d suave de uma superfície utilizando cores Sfgrayplot esboço 2d suave de uma superfície definida por uma função utilizando cores xgrid adiciona um grid em um esboço 2d errbar adiciona barras de erro veriticais a um esboço 2d histplot esboça um histograma Matplot esboço 2d de uma matriz utilizandose cores Graphics 510 Desenhos 3d plot3d esboço 3d de uma superfície plot3d1 esboço 3d em níveis de cinza ou de cores de uma superfície fplot3d esboço 3d de uma superfície definida por uma função fplot3d1 esboço 3d em escala de cinza ou colorido de nível de uma superfície definida por uma função param3d esboço 3d de uma curva parametrizada param3d1 esboço 3d de curvas parametrizadas contour curvas de nível em uma superfície 3d fcontour curvas de nível sobre uma superfície 3d definida por uma função hist3d representação 3d de um histograma genfac3d computa facetas de uma superfície 3d eval3dp computa facetas 3d de uma superfície parametrizada geom3d projeção 3d para 2d após um esboço 3d Desenho de linhas e poligonais xpoly desenha uma poligonal ou um polígono xpolys desenha um conjunto de poligonais ou polígonos xrpoly desenha um polígono regular xsegs desenha segmentos desconexos xfpoly preenche um polígono xfpolys preenche um conjunto de polígonos Desenho de retângulos xrect desenha um retângulo Graphics 511 xfrect preenche um retângulo xrects desenha ou preenche um conjunto de retângulos Desenho de arcos xarc esboça parte de uma elipse xarcs desenha partes de um conjunto de elipses xfarc preenche parte de uma elipse xfarcs preenche partes de um conjunto de elipses Desenho de setas xarrows desenha um conjunto de setas Strings xstring imprime strings xstringl computa uma caixa que cerca strings xstringb escreve strings em uma caixa xtitle adidciona títulos a janelas de gráficos titlepage adiciona título no meio de uma janela de gráficos xinfo escreve um string de informação na subjanela de mensagens Molduras e eixos graduate graduação de eixos plotframe esboça uma moldura com escalas e grides Esta função está obsoleta Transformações de coordenadas isoview ajusta escalas para esboço isométrico não muda o tamanho da janela square ajusta escalas para esboço isométrico muda o tamanho da janela Graphics 512 scaling transformação afim de um conjunto de pontos rotate rotação de um conjunto de pontos xsetech ajusta a subjanela de uma janela de gráficos para esboço subplot divide uma janela de gráficos em uma matriz de subjanelas xgetech retorna a escala de gráficos corrente xchange conversão de coordenadas reais para coordenadas pixeis Cores colormap mapa de cores getcolor abre um diálogo que exibe as cores no mapa de cores corrente addcolor adiciona cores novas ao mapa de cores corrente graycolormap mapa de cores linear cinza hotcolormap mapa de cores de vermelho para amarelo Contexto gráfico xset ajusta valores para o contexto gráfico Função obsoleta xget retorna valores correntes do contexto gráfico xlfont carrega uma fonte em um contexto gráfico ou pergunta a fonte carregada getsymbol Diálogo para a seleção de um símbolo e seu tamanho Gravação e carregamento xsave salva gráficos em um arquivo xload carrega gráficos salvos xs2fig envia gráficos para um arquivo em sintaxe Xfig Graphics 513 xs2gif envia gráficos a um arquivo em sintaxe GIF xs2ppm envia gráficos para um arquivo em sintaxe PPM Primitivas gráficas xbasc limpa uma janela de gráficos xclear limpa janela de gráficos driver seleciona um driver gráfico xinit inicialização de um driver de gráficos xend termina uma sessão de gráficos xbasr desenha novamente uma janela de gráficos replot redesenha a janela de gráficos corrente com novas fronteiras xpause suspende o Scilab xselect restaura a janela de gráficos corrente xdel deleta uma janela de gráficos winsid retorna a lista de janelas de gráficos xname muda o nome da janela de gráficos corrente Posição do mouse xclick espera por um clique do mouse locate seleção pelo mouse de um conjunto de pontos xgetmouse retorna os eventos de mouse e posição corrente Editor interativo editcurv editor interativo de curvas gráficas Graphics 514 grmenu editor gráfico interativo simples sd2sci estrutura grmenu para conversor de instrução Scilab Funções gráficas e controle automático bode diagrama de Bode gainplot esboço de magnitude nyquist diagrama de Nyquist mcircle esboço de um Mcírculo chart carta de Nichols black diagrama de Black evans lugar geométrico das raízes Evans sgrid esboça linhas de grid de um splano plzr esboço de pólozero zgrid esboço de um zgrid 515 Name LineSpec Customização rápida de linhas que aparecem em um esboço Nenhuma LineSpec é um argumento opcional que pode ser utilizado dentro de um comando plot para customizar os aspectos de cada linha nova Deve ser fornecido um string concatenado contendo as informações sobre cor estilo de linha e marcas É muito útil para especificar de forma rápida estas propriedades de linha básicas Para especificar uma linha vermelha de traço longo com marcas de rombo o string pode ser rdiam Como você pode ver não é necessário escrita completa de cada de cada valor de propriedade mas o string que é uma concatenação em qualquer ordem destas três propriedades não pode conter ambigüidade Além disso a especificação de strings não diferencia letras maiúsculas de minúsculas Descrição Aqui está uma lista completa dos tipos LineSpec que você pode especificar utilizando plot LineStyle um string definindo o estilo de linha Esta propriedade está ligada à propriedade linestyle do objeto ver polylineproperties especificador estilo de linha linha sólida padrão linha tracejada linha pontilhada linha tracejadapontilhada Color um string definindo a cor da linha Esta propriedade está ligada à propriedade foreground do objeto ver polylineproperties especificador cor r vermelho g verde b azul c ciano m magenta y amarelo k preto w branco Uma tabela de cores padrão é utilizada para colorir curvas esboçadas se você não especificar as cores nem com LineSpec nem com GlobalProperty Quando linhas múltiplas são desenhadas o comando plot automaticamente atribui em ciclos as cores a seguir R G B 0 0 1 0 05 0 1 0 0 0 075 075 075 0 075 075 075 0 025 025 025 LineSpec 516 Marker type um string definindo o tipo do marcador Note que se você especificar um marcador ou marca sem um estilo de linha apenas o marcador é desenhado Esta propriedade está ligada à propriedade do objeto markstyle e markmode do objeto ver polylineproperties especificador tipo de marcador sinal de mais o círculo asterísco ponto x cruz square ou s quadrado diamond ou d rombo ou diamante triângulo para cima v triângulo para baixo triângulo para a direita triângulo para a esquerda pentagram estrela de cinco pontas pentagrama none nenhum marcador padrão Exemplos x10110 inicialização plotxsinxr esboçando um linha de traços e pontos com um truângulo apontando para a direita centrado em cada ponto clf se você especificar um marcador sem um estilo de linha apenas a marca é desenhada plotxsinxd esboçando um linha de traços e pontos com um truângulo apontando para a direita centrado em cada ponto x110 Init a ordem das combinações não importa plotxxxcya múltiplos esboçoes com diferentes LineSpecs clf t0pi202pi plottsintrotcostcyatabssintmo Ver Também GlobalProperty plot clf Autor FLeray 517 Name Matplot esboço 2d de uma matriz utilizandose cores Matplotastrfrectnax Matplotaoptargs Parâmetros a matriz de reais de tamanho n1n2 optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes rect ajusta as fronteiras do esboço Se esta chave é fornecida nem frameflag ou strf é fornecido então o caractere y de strf é suposto como 7 Ver valores abaixo nax ajusta a definição dos grides Se esta chave é fornecida nem axesflag ou strf é forneci do então o caractere z cd strf é suposto como 1 Ver valores abaixo frameflag especifica como a moldura do esboço é computado O valor é um inteiro entre 0 e 8 Corre sponde ao caractere y de strf Ver abaixo axesflag especifica que tipo de eixos são desenhados ao redor do esboço O valor é um inteiro entre 0 e 5 Corresponde ao caractere z de strf Ver abaixo strf é um string de comprimento 3 xyz default o padrão é 081 x controls the display of captions x0 sem legendas x1 legendas são exibidas Elas são dadas pelo argumento opcional leg y controla a computação dos intervalos de coordenadas reais a partir dos valores mínimos re queridos Intervalos reais podem ser maiores que os requerimentos mínimos y0 sem computação o esboço utiliza a escala anterior ou padrão y1 a partir do argumento rect y2 a partir dos valores mínimomáximo dos dados x e y Matplot 518 y3 constrói uma escala isométrica a partir do argumento rect y4 constrói um esboço em escala isométrica a partir dos valores mínimomáximo dos dados x e y y5 aumentados para obtenção de bons eixos a partir do argumento rect y6 aumentados para obtenção de bons eixos a partir dos valores mínimomáximo dos dados x e y y7 como y 1 mas os anteriores são redesenhados para se utilizar a nova escala y8 como y 2 mas os anteriores são redesenhados para se utilizar a nova escala z controla a exibição de informação na moldura ao redor do esboço Se eixos são requeridos o número de tiques pode ser especificado pelo argumento opcional nax z0 nada é desenhado ao redor do esboço z1 eixos são desenhados o eixo y é exibido à esquerda z2 o esboço é cercado por uma caixa sem tiques z3 eixos são desenhados o eixo y é exibido à direita z4 eixos são desenhados centrados no meio da caixa de moldura z5 eixos são desenhados cruzandose no ponto 00 Se o ponto 00 não estiver den tro da moldura os eixos não aparecerão no gráfico rect este argumento é utilizado quando o segundo caractere y do argumento strf é 1 3 ou 5 É um vetor linha de tamanho quatro e fornece a dimensão da moldura rectxminyminxmaxymax nax este argumento opcional é utilizado quando o terceiro caractere z do argumento strf é 1 É um vetor linha de quatro entradas nxNxnyNy onde nx ny é o número de subgraduações no eixo x y axis e Nx Ny é o número de graduações no eixo x y Descrição As entradas da matriz inta são utilizadas como entradas do mapa de cor no mapa de cores corrente A cor associada a aij é utilizada para desenhar um pequeno quadrado de lado 1 com centro localizado em xjyn1i1 Entre com o comando Matplot para visualizar uma demonstração Matplot 519 Exemplos Matplot1 2 34 5 6 clf desenhando o mapa de cores corrente Matplot1xgetlastpattern Ver Também colormap plot2d Matplot1 Matplotproperties Autor JPhC 520 Name Matplot1 Esboço 2d de matrizes utilizando cores Matplot1arect Parâmetros a matriz de reais de tamanho n1n2 rect xminyminxmaxymax Descrição As entradas da matriz inta são utilizadas como entradas de mapa de cores no mapa de cores cor rente rect especifica um retângulo na escala corrente e a matriz é desenhada dentro deste retângulo Cada entrada da matriz será renderizada como um pequeno retângulo preenchido com sua cor asso ciada Exemplos primeiro exemplo clf axgcaobtendo o manipulador dos eixos correntes axdatabounds001010set the databounds axboxon desenha uma caixa a5ones1111 a2102104 a57572 primeira matriz no retângulo 1133 Matplot1a1133 aones1010 a 3trila 2a segunda matriz no retângulo 5678 Matplot1a5678 segundo exemplo animação n100 clf fgcfobtendo o manipulador da figura corrente fpixmaponmodo de buffer duplo axgcaobtendo o manipulador dos eixos corrente axdatabounds001010ajustando the databounds axboxon desenhando uma caixa showpixmap for knn aonesnn a 3trilak 2a a a a k1 3k100200 if kn then deletegceend Matplot1ak12k179 showpixmap enviando o buffer duplo para a tela end Matplot1 521 Ver Também colormap plot2d Matplot grayplot Matplotproperties Autor JPhC 522 Name Matplotproperties Descrição das propriedades da entidade Matplot Descrição A entidade Matplot é uma folha na hierarquia de entidades gráficas Representa esboços 2d de superfícies utilizando cores e imagens ver Matplot e Matplot1 parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Matplot deve ser do tipo Axes children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores Mat plot handles correntemente não possuem galhos visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o esboço é visível o valor da propriedade é on Se off o esboço não é desenhado na tela data este campo define uma matriz de cores mxn color utilizando o mapa de cores corrente A cor associada a colorij é utilizanda para se esboçar um pequeno quadrado de lado 1 com centro localizado em xjymi1 clipstate este campo contém o valor da propriedade clipstate para o Matplot o valor de clipstate pode ser off significa que o Matplot não é recortado clipgrf significa que o Matplot é recortado fora da caixa dos eixos on significa que o Matplot é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquer do largura altura define as porções do retângulo a ser exibido contudo o valor da propriedade clipstate será alterado userdata este campo pode armazenar qualquer variável Scilab na estrutura de dados do Matplot e recu perála Exemplos Matplot1xgetlastpattern egce obtendo a entidade corrente edataedata11 ordem inversa Ver Também set get delete grayplot Matplot Matplot1 graphicsentities grayplotproperties Matplotproperties 523 Autor FLeray 524 Name Sfgrayplot esboço 2d suave de uma superfície definida por uma função utilizando cores Sfgrayplotxyfoptargs Sfgrayplotxyf strf rect nax zminmax colminmax mesh colout Parâmetros xy vetores linhas de reais de tamanhos n1 e n2 f função do Scilab zfxy optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes strf rect nax zminmax colminmax mesh colout ver plot2d para os três primeiros e fec para os quatro últimos strfrectnax ver plot2d zminmax colminmax mesh colout ver fec Descrição Sfgrayplot é o mesmo que fgrayplot mas o esboço é suavizado A função fec é utilizada para suavização A superfície é esboçada assumindose que é linear em um conjunto de triângulos construídos a partir do grid aqui com n15 n23 A função colorbar pode ser utilizada para se visualizar a escala de cores mas você deve saber ou computar os valores mínimo e máximo Ao invés de Sfgrayplot você pode usar Sgrayplot este pode ser um pouco mais rápido Entre com o comando Sfgrayplot para visualizar uma demonstração Exemplos exemplo 1 esboço de 4 superfícies function zsurf1xy zxy endfunction function zsurf2xy zx2y2 endfunction function zsurf3xy zx3y2 endfunction function zsurf4xy zx2y2 endfunction xbasc xsetcolormapjetcolormap64hotcolormap64 x linspace1160 y linspace1160 Sfgrayplot 525 drawlater subplot221 colorbar11164 Sfgrayplotxysurf1strf041colminmax164 xtitlefxy xy subplot222 colorbar1165128 Sfgrayplotxysurf2strf041colminmax65128 xtitlefxy x2y2 subplot223 colorbar1265128 Sfgrayplotxysurf3strf041colminmax65128 xtitlefxy x3y2 subplot224 colorbar02164 Sfgrayplotxysurf4strf041colminmax164 xtitlefxy x2y2 drawnow xselect exemplo 2 esboço de surf3 e adição de algumas linhas de contorno function zsurf3xy zx3y2 endfunction xbasc x linspace1160 y linspace1160 xsetcolormaphotcolormap128 drawlater colorbar12 Sfgrayplotxysurf3strf041 fcontour2dxysurf301 0025 04style1 1 1strf000 xtitlefxy x3y2 drawnow xselect exemplo 3 esboço de surf3 e uso dos argumentos opcionais zminmax e colout para restringir o esboço em 05lt z lt 1 function zsurf3xy zx3y2 endfunction xbasc x linspace1160 y linspace1160 xsetcolormapjetcolormap128 drawlater zminmax 05 1 colors32 96 colorbarzminmax1zminmax2colors Sfgrayplotx y surf3 strf041 zminmaxzminmax colout0 0 colminmaxcolors fcontour2dxysurf305 1style1 1 1strf000 xtitlefxy x3y2 com partes abaixo de z 05 e acima de z 1 removidas drawnow xselect Ver Também fec fgrayplot grayplot Sgrayplot Autor JPhC 526 Name Sgrayplot esboço 2d suave de uma superfície utilizando cores Sgrayplotxyzoptargs Sgrayplotxyz strf rect nax zminmax colminmax mesh colout Parâmetros xy vetores linhas de reais de tamanhos n1 e n2 z matriz de reais de tamanho n1n2 zij é o valor da superfície no ponto xiyj optargs representa uma seqüência de declarações key1value1key2value2 onde key1 key2 podem ser um dos seguintes strf rect nax zminmax colminmax mesh colout strf é um string de comprimento 3 xyz por padrão strf 081 x controla a exibição de legendas x0 sem legendas x1 legendas são exibidas Elas são dadas pelo argumento opcional leg y controla a computação dos intervalos de coordenadas reais a partir dos valores mínimos re queridos Intervalos reais podem ser maiores que os requerimentos mínimos y0 sem computação o esboço utiliza a escala anterior ou padrão y1 a partir do argumento rect y2 a partir dos valores mínimomáximo dos dados x e y y3 construídos para uma escala isométrica a partir do argumento rect y4 construídos para uma escala isométrica a partir dos valores mínimomáximo dos dados x e y y5 aumentados para obtenção de bons eixos a partir do argumento rect y6 aumentados para obtenção de bons eixos a partir dos valores mínimomáximo dos dados x e y y7 como y 1 mas os anteriores são redesenhados para se utilizar a nova escala Sgrayplot 527 y8 lcomo y 2 mas os anteriores são redesenhados para se utilizar a nova escala z controla a exibição de informação na moldura ao redor do esboço Se eixos são requeridos o número de tiques pode ser especificado pelo argumento opcional nax z0 nada é desenhado ao redor do esboço z1 eixos são desenhados o eixo y é exibido à esquerda z2 o esboço é cercado por uma caixa sem tiques z3 eixos são desenhados o eixo y é exibido à direita z4 eixos são desenhados centrados no meio da caixa de moldura z5 eixos são desenhados cruzandose no ponto 00 Se o ponto 00 não estiver den tro da moldura os eixos não aparecerão no gráfico rect este argumento é utilizado quando o segundo caractere y do argumento strf é 1 3 ou 5 É um vetor linha de tamanho quatro e fornece a dimensão da moldura rectxminyminxmaxymax nax este argumento opcional é utilizado quando o terceiro caractere z do argumento strf ié 1 É um vetor linha de quatro entradas nxNxnyNy onde nx ny é o número de subgraduações no eixo x y axis e Nx Ny é o número de graduações no eixo x y zminmax colminmax mesh colout ver fec Descrição Sgrayplot é o mesmo que grayplot mas o esboço é suavizado A função fec é utilizada para suavização A superfície é esboçada assumindose que é linear em um conjunto de triângulos construídos a partir do grid aqui com n15 n23 A função colorbar pode ser utilizada para se visualizar a escala de cores O parâmetro zminmax é útil para propósitos de animação veja um exemplo depois e o parâmetro colminmax permite que o usuário escolha uma parte do mapa de cores corrente ver a página de ajuda de fec Entre com o comando Sgrayplot para visualizar uma demonstração Sgrayplot 528 Exemplos exemplo 1 x1010 y1010m rand2121 clf xsetcolormaphotcolormap64 Sgrayplotxym strf011 rect20202020 exemplo 2 tpi01pi msintcost clf xsetcolormapjetcolormap64 colorbar11 Sgrayplotttm strf041 exemplo 3 exibindo animação de costsinxsiny n 30 nt 100 x linspace02pin y linspace0pin2 z sinxsiny t linspace04pint xselect clf fgcf fcolormapjetcolormap64 fpixmapon colorbar11 Sgrayplotxycost1z strf042 zminmax11 cgceecchildren xtitleOlhos de Kaa for i 1nt edata3matrixcostiz11 showpixmap end fpixmapoff Ver Também fec fgrayplot grayplot Sfgrayplot colorbar Autor JPhC 529 Name addcolor adiciona cores novas ao mapa de cores corrente newaddcolorc Parâmetros new identificadores das cores definidas em c em uma nova tabela de cores c matriz com 3 colunas definição de cores RGB vermelho verde e azul Descrição addcolor adiciona novas cores fornecidas no argumento c ao mapa de cores corrente c deve ser uma matriz com três colunas R G B R é o componente vermelho G é o componente verde B é o componente azul cada entrada em c deve ser um número nãonegativo menor do que ou igual a 1 Os identificadores das novas cores são retornados em new Se uma cor definida em c já está presente no mapa de cores ela não será adicionada Examplos plot3d h gcf hcolormap jetcolormap16 addcolorname2rgbgrey255 Ver Também colormap name2rgb 530 Name alufunctions Funções de desenho de pixel Descrição src is the source ie the value of the pixel which we want to draw dst is the destination ie value of the pixel which is already drawn 0 clear ie 0 limpo 1 and ie src AND dst E 2 and reverse ie src AND NOT dst E NÃO e reverso 3 copy ie src cópia 4 and inverted ie NOT src AND dst NÃO E e invertido 5 noop ie dst 6 xor ie src XOR dst UM OU OUTRO 7 or ie src OR dst OU 8 nor ie NOT src AND NOT dst NÃO E NÃO nem um nem outro 9 equiv ie NOT src XOR dst NÃO UM OU O OUTRO equivalência 10 invert ie NOT dst NÃO 11 or reverse ie src OR NOT dst OU NÃO ou reverso 12 copy inverted ie NOT src cópia invertida 13 or inverted ie NOT src OR dst NÃO OU invertido 14 nand ie NOT src OR NOT dst NÃO OU NÃO pelo menos um não 15 set ie 1 ajustado 531 Name arcproperties Descrição das propriedades da entidade Arc arco Descrição A entidade Arc é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para elipses e partes de elipses preenchidas ou não parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Arc deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores arc não possuem galhos correntemente thickness este campo contém a propriedade de linha thickness espessura Deve ser um inteiro positivo linestyle o valor da propriedade linestyle deve ser um inteiro em 1 6 1 significa linha sólida e os demais valores significam tipos diferentes de tracejados linemode esta propriedade permite que se exiba ou não a linha representando o arco O valor pode ser on ou off fillmode se o valor da propriedade fillmode é on o arco é preenchido com a cor background de plano de fundo foreground este campo contém o valor padrão da propriedade foreground primeiro plano para desenhar ou preencher o arco Deve ser um índice de cor relativo ao mapa de cores corrente background este campo contém a cor usada para preencher o arco Deve ser um índice de cor relativo ao mapa de cores corrente data esta propriedade retorna as coordenadas do ponto superior esquerdo a largura e a altura do retângulo envolvente bem como os ângulos de froenteira do setor É a matriz xleftyup zupwidthheighta1a2 onde a1 e a2 são os ângulos de fronteira dados em graus Aviso nas versões do Scilab até a 412 a1 e a2 são dados em degree64 visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Se on o arco é desenhado se off o arco não é exibido na tela arcdrawingmethod Este campo controla o tipo de discretização utilizado para renderizar o arco Seu valor deve ser nurbs ou lines Se nurbs for selecionado o arco é renderizado utilizandose superfícies e curvas nurbs Isto resulta na exibição de uma superfície perfeita não importa qual o ponto de vista seja Se lines é selecionado então o arco é aproximado com um número constante de linhas Isto reduz o tempo de desenho mas pontas agudas podem aparecer em uma ampliação O uso do valor lines é desencorajado e só deve ser utilizado se for notada alguma perda na velocidade dos quadros ao se utilizar o valor nurbs arcproperties 532 clipstate este campo contém o valor da propriedade clipstate para o arco O valor de clipstate pode ser off significa que o arco não é recortado clipgrf significa que o arco é recortado fora da caixa dos eixos on significa que o arco é recortado fora do arco dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox property Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura e altura define as porções do arco a serem exibidas contudo o valor da pro priedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade arco e recuperála Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds2222 xarc151533036064 arcgethdl obtendo o manipulador da entidade corrente aqui é a entidade Arc arcfillmodeon arcforeground5 arcdata3 62 27064 xfarc5146036064 arcvisibleoff Ver Também set get delete xarc xarcs xfarc xfarcs graphicsentities Autor Djalel ABDEMOUCHE JeanBaptiste SILVY 533 Name autumncolormap Mapa de cores com tons do outono vermelho laranja amarelo cmapautumncolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição autumncolormap computa um mapa de cores com n cores com tons do outono Exemplos f scf plot3d1 fcolormap autumncolormap32 Ver Também colormap bonecolormap coolcolormap coppercolormap graycolormap hotcolormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 534 Name axesproperties descrição das propriedades de entidades Axes de eixos Descrição A entidade Axes é o segundo nível da hierarquia das entidades de gráfico Esta entidade define os parâmetros que permitem a mudança de coordenadas e o esboço dos eixos tanto quanto os valores padrões dos parâmetros para criação de entidades galhos Propriedades dos eixos parent este campo contém o manipulador da figura raiz children Fvetor FA contendo os manipuladores de todos os objetos gráficos galhos dos eixos Estes objetos gráficos são do tipo Com pound Rectangle Polyline Segs Arc Grayplot ver Compoundproperties rectangleproperties champproperties axisproperties polylineproperties segsproperties grayplotproperties surfaceproperties param3dproperties fecproperties textproperties legendproperties visible este campo contém o valor da propriedade visible visível para os eixos O valor pode ser on ligado ou off desligado Por padrão os eixos são visíveis on caso todos os galhos visíveis sejam exibidos na tela Se off os eixos e seus galhos não são esboçados axesvisible um vetor de strings 1x3 string vector Esta propriedade especifica se o eixo deve ser desen hado ou não Seu valor pode ser on ou off para um ajuste global Para agir em um único eixo a sintaxe é axesvisibleN onde N é 12 ou 3 correspondentes aos eixos xy ou zO dado de escala e se requerido os grides são desenhados se o valor for on Note que ao criar uma simples entidade de eixo usando os comandos gca atalho para getcurrentaxes ou gcf atalho para getcurrentfigure a visibil idade dos eixos é ajustada para off axesreverse um vetor de strings 1x3 correspondentes aos três eixos XYZ Para cada eixo a pro priedade especifica a direção dos valores crescentes Se off a direção padrão é usada Se on a direção é invertida Também é possível utilizar apenas um string on ou off para ajustar simultaneamente os três dados grid o valor do campo é um vetor xgridygridzgrid onde xgrid controla o esboço para o eixo x e ygrid zgrid respectivamente para os eixos y e z O valor padrão é 1 os grides não são desenhados caso contrário os grides são desenhados utilizan do a cor dada indexada pelo valor do grid gridposition Este string determina a posição do grido comparada às outras entidades gráficas Seu valor pode ser foreground para desenhar o grid à frente das outras entidades ou back ground para desenhar o grid atrás xlocation especifica a localização do eixo y Os valores possíveis são bottom Neste caso o eixo y é desenhado na parte direita do retângulo de eixos axesproperties 535 top Neste caso o eixo y é desenhado na parte esquerda do retângulo de eixos middle Neste caso o eixo y é desenhado na posição mais próxima da coordenada 0 do eixo x ylocation especifica a localização do eixo y Os valores possíveis são left Neste caso o eixo y é desenhado na parte direita do retângulo de eixos right Neste caso o eixo y é desenhado na parte esquerda do retângulo de eixos middle Neste caso o eixo y é desenhado na posição mais próxima da coordenada 0 do eixo x title um objeto anexado à entidade de eixos que retorna um manipulador gráfico de uma estrutura label rótulo ver labelproperties Este campo define um título com opções sobre este label xlabel um objeto anexado à entidade de eixos que retorna um manipulador gráfico de uma estrutura label ver labelproperties Este campo define um label sobre o eixo x com opções sobre este label ylabel um objeto anexado à entidade de eixos que retorna um manipulador gráfico de uma estrutura label ver labelproperties Este campo define um label sobre o eixo y com opções sobre este label zlabel um objeto anexado à entidade de eixos que retorna um manipulador gráfico de uma estrutura label ver labelproperties Este campo define um label sobre o eixo z com opções sobre este label autoticks um vetor de strings 1x3 fornecendo o status autoticks para cada eixo Esta propriedade especifica se cada eixo é graduado utilizandose um algoritmo computacional ou não graduações feitas pelo usuário Os valores podem ser on ou off para ajuste glob al Para agir em um único eixo a sintaxe é autoticksN onde N é 12 ou 3 corre spondentes aos eixos xy ou z Note que a edição de tiques textos eou localizações via xticks yticks ou zticks ajusta automaticamente autoticks para off para os eixos correspondentes xtickslocations um vetor de reais contendo a localização das graduações sobre o eixo x Esta propriedade pode ser editada especificandose um novo vetor de reais de mesmo tamanho Para especificar graduações maiores ou menores podese agir no tlist xticks definindo também um vetor de strings xtickslabels ytickslocations um vetor de reais contendo a localização das graduações sobre o eixo y Esta propriedade pode ser editada especificandose um novo vetor de reais de mesmo tamanho Para especificar graduações maiores ou menores podese agir no tlist yticks definindo também um vetor de strings ytickslabels ztickslocations um vetor de reais contendo a localização das graduações sobre o eixo z Esta propriedade pode ser editada especificandose um novo vetor de reais de mesmo tamanho Para especificar graduações maiores ou menores podese agir no tlist zticks definindo também um vetor de strings ztickslabels axesproperties 536 xtickslabels um vetor de strings contendo rótulos para as graduações no eixo x Esta propriedade pode ser editada especificandose um novo vetor de mesmo tamanho Para especificar graduações menores ou maiores pode se agir no tlist xticks definindo também um vetor de reais xtickslocations ytickslabels um vetor de strings contendo rótulos para as graduações no eixo y Esta propriedade pode ser editada especificandose um novo vetor de mesmo tamanho Para especificar graduações menores ou maiores pode se agir no tlist yticks definindo também um vetor de reais ytickslocations ztickslabels um vetor de strings contendo rótulos para as graduações no eixo z Esta propriedade pode ser editada especificandose um novo vetor de mesmo tamanho Para especificar graduações menores ou maiores pode se agir no tlist zticks definindo também um vetor de reais ztickslocations box esta propriedade especifica se os eixos devem ser encerrados por uma caixa Seu valor pode ser off hiddenaxes backhalf ou on Se o valor for off a caixa não é desenhada Se a propriedade for hiddenaxes apenas a moldura de trás é de senhada Se o valor for backhalf os eixos X Y e Z são desenhados também Se a propriedade for on a caixa toda é desenhada filled Esta propriedade especifica se o plano de fundo dos eixos devem ser desenhados ou não Seu valor pode ser off ou on Se o valor for off o plano de fundo não é desenhado e a caixa de eixos é transparente Se a propriedade for on o plano de fundo é desenhado utilizandose a cor especificada pela propriedade background subticks esta propriedade determina o número de subtiques a serem desenhados entre dois tiques prin cipais O valor de campo é o vetor nxny onde nx é o número de subtiques para o eixo x e ny é o correspondente para o eixo y fontstyle especifica a fonte a ser utilizada para exibir os rótulos É um inteiro positivo que faz referência a uma das fontes carregadas Seu valor deve estar entre 0 referenciando a primeira fonte e o número de fontes carregadas menos um referenciando a última fonte carregada Para mais informações ver graphicsfonts fontsize um inteiro especificando o tamanho da fonte usada para para os rótulos dos tiques Se a propriedade fractionalfont for off apenas a parte inteira do valor é utilizada Para mais informações ver graphicsfonts fontcolor esta propriedade determina a cor dos rótulos dos tiques fractionalfont esta propriedade especifica se os rótulos dos tiques serão exibidos com tamanhos de fonte fracionários Seu valor pode ser on ou off Se on o valor em ponto flutuante de fontsize é usado para exibição e a fonte não possui outro nome Se off apenas a parte inteira é utilizada e a fonte não é suavizada isoview esta propriedade é utilizada para se obter escalas isométricas para os eixos x y e z por ex emplo para fazer com que a exibição da curva sinx versus cosx seja um círculo não uma elipse Os valores podem ser on ou off Se o valor for on os databounds axesproperties 537 dos eixos mudam automaticamente de acordo com os valores da propriedade de figura cor respondente figuresize cubescaling esta propriedade é utilizada no modo 3d mode para se obter uma nova escala para os eixos x y e z De fato permite que os dados se encaixem em um cubo 1x1x1 o objetivo é uma melhor visualização de gráficos 3d caso as escalas dos eixos se diferenciem muito umas das outras Os valores podem ser on ou off que é o valor padrão Na maior parte dos casos ajuda a gerar uma visualização 3d semelhante a do Matlab view este campo é relacionado ao universo gráfico Toma 3d como valor correspondente a visualizações em três dimensões Em outros casos pode ser 2d para esboço inicial 2d valor padrão Este flag também depende dos esboços com os quais o usuário entra um comando plot3d por exemplo vai alternar o flag view de 2d para 3d rotationangles este campo é o vetor alphatheta Estes dois valores fornecem as coordenadas esféricas de obsevação em graus logflags string de três caracteres que ajusta a escala linear ou logarítmica o longo dos eixos Cada caractere especifica a escala para os eixos x y e z respectivamente Os valores podem ser n para escala linear ou l para escala logarítmica tightlimits se está propriedade for on os eixos se adaptam para se encaixarem dentro dos valores máximos e mínimos de databounds Se o campo for off os eixos podem aumentar os limites de modo a produzir rótulos de tiques convenientes databounds este campo contém os valores de limite para as coordenadas xy e z É a ma triz xminyminzminxmaxymaxzmax ou xminyminxmaxymax Note que para ter estritamente os limites de dados especificados tightlimits deve ser ajus tado para on ver acima zoombox este campo contém a caixa de zoom corrente se forem fornecidas quaisquer coordenadas É uma matriz vazia sem zoom ou vetor xminyminxmaxymaxzminzmax define um retângulo dado por dois vértices opostos margins um vetor marginleftmarginrightmargintopmarginbottom es pecificando a porção das margens para estes eixos Este vetor é composto de números em 0 1 com valores padrões 0125 0125 0125 0125 estes números são razões relativas aos valores correspondentes da propriedade de figura figuresize axesbounds um vetor xleftyupwidthheight especificando a porção da figura usada por estes eixos onde xleft yup width e height são números em 0 1 fornecendo respectivamente a posição do canto superior esquerdo e a dimensão dos eixos testes números são razões relativas aos valores correspondentes da propriedade de figura figuresize hiddenaxiscolor esta propriedade define a cor do eixo escondido É um índice relativo ao mapa de cores corrente userdata este campo pode armazenar qualquer variável Scilab na estrutura de dados de eixos e recu perála axesproperties 538 Propriedades para funções de altonível As funções plot plot2dx grayplot e matplot utilizam as propriedades seguintes para decidir como misturar esboços consecutivos se isto não for declarado pelo argumento de chama da frameflag calling argument O resultado da mistura é decidido através destas duas pro priedades autoclear se esta propriedade for on uma chamada a um gráfico de altonível reinicializa os eixos correntes e apaga todos os seus galhos antes de realizar o esboço Se for off os esboços serão adicionados aos eixos correntes de acordo com a propriedade autoscale autoscale uma propriedade para atualizar os limites de dados dos eixos Se o valor for on um novo esboço adaptará as propriedades de eixos correntes para se adequar aos esboços anteriores e correntes Se o valor for off o novo esboço será esboçado nos limites de dados correntes Valores padrões dos galhos hiddencolor esta propriedade controla as cores das partes escondidas Toma como valor um índice relativo ao mapa de cores corrente Em outro caso se for um valor negativo as partes escondidas tomam a mesma cor que a superfície linemode este campo contém o valor padrão da propriedade linemode para objetos Segs Rectangle Legend Axis Plot3d Fac3d e Polyline Seus valores podem ser on padrão ou off linestyle este campo contém o valor padrão da propriedade linestyle para objetos Segs Arcs Rectangle e Polyline linestyle seleciona o tipo de linha que será utilizado nos desenhos de linhas Seu valor deve ser um inteiro no intervalo 0 6 0 e 1 significam linhas sólidas os outros selecionam linhas tracejadas ver getlinestyle thickness este campo contém o valor padrão da propriedade thickness para todos os objetos que utilizam linhas Seu valor deve ser um inteiro positivo markmode este campo contém o valor padrão da propriedade markmode para os objetos Segs Rect angle Legend Axis Plot3d Fac3d e Polyline Seu valor pode ser on ou off padrão markstyle este campo contém o valor padrão da propriedade markstyle para objetos Segs Rect angle Legend Axis Plot3d Fac3d e Polyline markstyle seleciona o tipo de marca a ser exibida Seu valor deve ser um inteiro no intervalo 0 9 que significa ponto sinal de mais cruz estrela diamante preenchido diamante triângulo para cima triângulo para baixo trevo ou círculo marksizeunit este campo contém o valor padrão da propriedade marksizeunit para objetos Segs Rectangle Legend Axis Plot3d Fac3d e Polyline Se marksizeunit é ajustado para point então o valor de marksize é diretamente fornecido em pontos Quando marksizeunit é ajustado para tabulated marksize é computado de acor do com o array de tamanho de fonte logo seu valor deve ser um inteiro no intervalo 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que plot2d e funções puras do Scilab utilizam o modo tabulated como padrão ao utilizarse a função plot o modo point é automaticamente habilitado marksize este campo contém o valor padrão da propriedade marksize para objetos Segs Rectangle Legend Axis Plot3d Fac3d e Polyline marksize seleciona o tamanho de fonte da marca axesproperties 539 ser exibida Deve ser um valor inteiro entre 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt ver getmark markforeground este campo contém o valor padrão da propriedade markforeground criados sob os eixos Objetos Polyline Rectangle Legend Surface Segment e Axis utilizam esta propriedade para especificar uma cor de primeiro plano borda para suas marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente Note que o valor padrão é 1 preto padrão e mesmo que você mude o colormap este valor 1 sempre apontará para a cor preta padrão markbackground este campo contém o valor padrão da propriedade markbackground para todos os obje tos criados sob os eixos objetos Polyline Rectangle Legend Surface Segment e Axis uti lizam esta propriedade para especificar uma cor de plano de fundo face para suas marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente Note que o valor padrão é 2 branco padrão e mesmo que você mude o colormap este valor 2 sempre apontará para a cor branca padrão foreground este campo contém o valor padrão da propriedade foreground para eixos e para todos os objetos criados sob os eixos O valor deve ser um índice de cor relativo ao mapa de cores cor rente Note que o valor padrão é 1 preto padrão e mesmo que você mude o colormap este valor 1 sempre apontará para a cor preta padrão background este campo controla o valor padrão da propriedade background para os eixos e para objetos criados sob os eixos O valor deve ser um índice de cor relativo ao mapa de cores corrente Note que o valor padrão é 2 branco padrão e mesmo que você mude o colormap este valor 2 sempre apontará para a cor branca padrão arcdrawingmode este campo controla o valor padrão da propriedade default arcdrawingmode para todos os objetos Arc criados sob este objeto Axes Seu valor pode ser nurbs ou lines clipstate este campo contém o valor padrão da propriedade clipstate para todos os objetos Seu valor pode ser off isto indica todos os objetos criados depois que não estão recortados valor padrão clipgrf isto indica todos os objetos criados depois que estão recortados fora das fronteiras dos eixos on isto indica todos os objetos criados depois que estão recortados fora do retângulo através da propriedade clipbox clipbox este campo contém o valor padrão da propriedade clipbox para todos os objetos Deve ser uma matriz vazia se clipstate for off Em outro caso o recorte é dado por xywh ponto superior esquerdo largura altura Nota sobre valores padrões Todas essas propriedades e campos listados herdam de valores padrões armazenados em um modelo de eixos Estes valores podem ser visualizados e modificados Para isto utilize o comando getdefaultaxes command ele retorna o manipulador gráfico do modelo de eixos Note que nenhuma janela de gráficos é criada por este co mando Note que os próximos eixos criados herdarão deste modelo ver exemplo sobre modelo de eixos abaixo axesproperties 540 Exemplos lines0 desabilitando o paginamento vertical agetcurrentaxesobtendo o manipulador dos novos eixos criados aaxesvisibleon tornando os eixos visíveis afontsize3 ajustando o tamanho da fonte dos rótulos dos tiques axlocationtop ajustando a posição do eixo x adatabounds1002110021 ajustando os valores limites para as coordenadas xy e z asubtics50 alabelsfontcolor5 agrid22 aboxoff exemplo com eixos 3d clf limpando a janela de gráficos x01012piplot2dx3sinx72 agca obtendo o manipulador dos eixos correntes agrid1 1 1 make xgrid arotationangles70 250 girando eixos com ângulos dados agrid1 6 1 criando ygrid aview2d retornando a vista 2d aboxbackhalf alabelsfontcolor5 achildrenchildrenthickness4 achildrenchildrenpolylinestyle3 aview3d return te the 3d view achildrenchildrenthickness1 achildrenchildrenforeground2 agrid1 6 3 criando zgrid aparentbackground4 abackground7 plot2dcosx13sinx3 plot2dcosx73sinx3 achildren2childrenpolylinestyle2 achildren1childrenpolylinestyle4 achildren1childrenforeground5 achildren2childrenforeground14 aparentfiguresize 1200800 aboxon alabelsfontsize4 aparentbackground8 aparentfiguresize 400200 arotationangles0 260 deleteachildren2 delete deletando objeto corrente a gca alabelsfontsize1 aautoclear on x00125piplot2d10cosxsinx adatabounds1 115 ajustando limites positivos para o eixo x alogflags lnn ajustando o eixo X para escala logarítmica alogflags nnn voltando para escala linear agca axesproperties 541 arotationangles45 45 adatabounds203220 3 2 xrect4 05 8 1 aautoclear off aisoviewon modo de isovisualização xrect2 025 4 05 achildren1fillmodeon aaxesvisibleoff achildren1data2 025 1 4 05 achildren2data4 05 1 8 1 x2pi078 xv2sinx9sinxyv2cosx9cosx xsegs10xvyv18 sachildren1 sarrowsize1 ssegscolor5 adatabounds os valores limites para as coordenadas xy e z aview2d adatabounds101 101 ajustando os valores limites para vistas bidimensionais exemplo com eixos modelos dagda obtendo manipulador dos eixo modelos para ver e editar campos título padrão datitletextMy DefaultTitle datitleforeground 12 datitlefontsize 4 rótulos x padrões daxlabeltextx daxlabelfontstyle 8 daxlabelfontsize 2 daxlabelforeground 5 daxlocation middle rótulos y padrões daylabeltexty daylabelfontstyle 3 daylabelfontsize 5 daylabelforeground 3 daylocation right dathickness 2 daforeground 7 o esboço x0012pi plot2dxsinxsin2xsin3xstyle123rect022pi2 sda de volta aos eixos modelos padrões Ver Também lines set get gca gda gcf sda sdf scf graphicsentities Autor Djalel ABDEMOUCHE 542 Name axisproperties Descrição das propriedades da entidade Axis eixo Descrição A entidade Axis é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para escala de eixos e aparência Propriedades parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Axis deve ser do tipo Axes ou Compound visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o eixo é visível a propriedade é on Se off o eixo não é exibido na tela ticsdirection especifica a direção dos tiques desenhados sob os eixos horizontal e vertical Os possíveis valores para esta propriedade são top Neste caso os tiques são desenhados na parte de cima do eixo horizontal bottom Neste caso os tiques são desenhados na parte de baixo do eixo horizontal left Neste caso os tiques são desenhados à esquerda do eixo vertical right Neste caso os tiques são desenhados à direita do eixo vertical Os valores padrões são top para o eixo horizontal e right para o eixo vertical xticscoord este campo contém as coordenadas x do eixo É um vetor linha que contém valores crescentes da esquerda para a direita que fornecem as posições dos tiques para um eixo horizontal Em outro caso a entidade é um eixo vertical esta propriedade contém a escala que define a origem x do eixo yticscoord este campo contém as coordenadas y do eixo É um vetor linha que contém valores crescentes do fundo para o topo que fornecem as posições dos tiques para um eixo vertical Em outro caso a entidade é um eixo horizontal esta propriedade contém a escala que define a origem y do eixo ticscolor o valor desta propriedade é o índice da cor utilizada para desenhar as linhas dos eixos e tiques ticssegment este campo contém um flag que controla a exibição do segmento base do eixo O valor padrão é on senão sem exibição a propriedade toma off como valor ticsstyle esta propriedade descreve como os tiques são dados É um flag string que pode ter um desses valores v É o valor padrão Neste caso as posições dos tiques são dadas pelo vetor linha xticscoord para o eixo horizontal yticscoord para o vertical r INeste caso as posições dos tiques são dadas pelo vetor minmaxn onde n é o número de intervalos axisproperties 543 i Neste caso o vetor fornecendo as posições dos tiques tem tamanho 4 k1k2an os valores crescem entre k110a e k210a n é o número de inter valos subtics este campo ajusta o número de tiques a serem desenhados entre dois tiques principais ticslabels este campo é uma matriz de strings que contém strings a serem impressos ao longo dos eixos nas posições dos tiques labelsfontcolor esta propriedade determina a cor dos rótulos dos tiques labelsfontsize um inteiro especificando o tamanho da fonte utilizada para imprimir os rótulos dos tiques Se a propriedade fractionalfont for off Apenas a parte inteira do valor é utilizada Para mais informações veja graphicsfonts fractionalfont esta propriedade especifica se os rótulos dos tiques serão exibidos utilizandose um taman ho de fonte fracionário Seu valor deve ser on ou off Se on o valor em ponto flutuante de fontsize é utilizado para a exibição e retirase o serrilhamento da fonte Se off apenas a parte inteira é utilzada e a fonte não é suavizada clipstate este campo contém o valor da propriedade clipstate para o eixo O valor de clipstate pode ser off significa que o eixo não é recortado clipgrf significa que o eixo é recortado fora da caixa dos eixos on significa que o eixo é recortado fora do arco dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções do eixo a ser exibido contudo o valor da pro priedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade axis e recuperála Exemplos agetcurrentaxesobtendo manipulador dos novos eixos criados adatabounds111010 drawaxisx27y4diru a1achildren1 a1xticscoord1 4 5 8 10 a1ticscolor2 a1labelsfontsize3 a1ticsdirectionbottom a1ticslabels Fevereiro Maio Junho Agosto Outubro drawaxisx12110y5dirutextcolor13 axisproperties 544 a2gethdl a2subtics0 a2ticssegmentoff a2yticscoord4 drawaxisx1y017dirrfontsize10textcolor5ticscolor6subint10 a3gethdl a3ticslabels B string07 a3ticsdirectionleft Ver Também set get delete drawaxis graphicsentities Autor Djalel ABDEMOUCHE 545 Name bar Histograma de barras bary barxy barhxy width color style Parâmetros h manipulador de eixos padrão hgca y escalar real vetor de tamanho N ou uma matriz NxM x escalar real ou um vetor de tamanho N padrão se y é um vetor então x is é um vetor e o comprimento de x é igual ao comprimento de y Se y é uma matriz então x é um vetor e o comprimento de x é igual ao número de linhas de y width opcional escalar real define a largura uma porcentagem do espaço disponível para a barra padrão 08 ie 80 color opcional um string padrão blue especificando a cor da barra style string grouped ou stacked padrão grouped Descrição bary se y é um vetor então a função bar desenha uma poligonal que tem polylinestyle tipo 6 Se y for um vetor desenha o vetor y versus o vetor 1sizey Se y for uma matriz NM bar desenha M poligonais tipo 6 cada poligonal corresponde a uma coluna de y versus o vetor x1sizey1 barxy se y for um vetor então a função bar desenha uma poligonal que tem polylinestyle tipo 6 onde comprimento de x comprimento de y Se y é uma matriz NxM então a função bar desenha M poligonais que possuem tipo 6 Cada poligonal corresponde a uma col una de y versus o vetor x barh define os eixos correntes onde o desenho é feito barwidth define a largura das barras em porcentagem geralmente 0width1 barstyle define como as barras serão desenhadas Se y é uma matriz NxM então temos M poligonais de tipo 6 então há dois modos de se desenhar as M barras A opção style grouped permite centrar as M poligonais versus cada componente de x e a opção style stacked permite empilhálas barcolor define a cor da barra Funções de barra utilizam o mesmo mapa de cores que na função Se há várias chamadas a bar a função barhomogenize permite homogeneizar a largura e estilo de todas as barras ie poligonais do tipo 6 inclusas nos eixos correntes bar 546 Exemplos primeiro exemplo desenhando uma barra ie uma poligonal com polylinestyle 6 com width05 e coloryellow e stylegrouped x1lengthy scf0 y1 3 5 bary05yellow segundo exemplo desenhando 3 barras ie três poligonais com polylinestyle 6 stylegrouped scf1 x1 2 5 y1 5 63 2 74 3 8 barxy terceiro exemplo stylestacked scf2 x1 2 5 y1 4 72 5 83 6 9 barxystacked quarto exemplo width02colorgreen stylegrouped scf3 x1 2 5 y1 4 72 5 83 6 9 barxy02green Ver Também barh barhomogenize plot polylineproperties Autor Farid Belahcene 547 Name barh Exibição horizontal de um histograma de barras barhy barhxy barhhxy width color style Parâmetros h manipulador de eixos padrão hgca y escalar real vetor de tamanho N ou uma matriz NxM x escalar real ou um vetor de tamanho N padrão se y é um vetor então x é um vetor e o compri mento de x é igual ao comprimento de y Se y é uma matriz então x é um vetor e o comprimento de x é igual ao número de linhas de y width opcional escalar real define a largura uma porcentagem do espaço disponível para a barra padrão 08 ie 80 color opcional um string padrão blue especificando a cor interior da barra barra style string grouped ou stacked padrão grouped Descrição barhy se y é um vetor então a função bar desenha uma poligonal que tem polylinestyle tipo 6 Se y for um vetor desenha o vetor y versus o vetor 1sizey Se y for uma matriz NM bar desenha M poligonais tipo 6 cada poligonal corresponde a uma coluna de y versus o vetor x1sizey1 barhxy se y for um vetor então a função desenha uma poligonal que tem polylinestyle tipo 6 onde comprimento de x comprimento de y Se y é uma matriz NxM então a função desenha M poligonais que possuem tipo 6 Cada poligonal corresponde a uma coluna de y versus o vetor x barhh define os eixos correntes onde o desenho é realizado barhwidth define a largura das barras em porcentagem geralmente 0width1 barhstyle define como as barras serão desenhadas Se y é uma matriz NxM então temos M poligonais de tipo 6 então há dois modos de se desenhar as M barras A opção style grouped permite centrar as M poligonais versus cada componente de x e a opção style stacked permite empilhálas barhcolor define a cor da barra Funções de barra utilizam o mesmo mapa de cores que na função plot Se há várias chamadas a barh a função barhomogenize permite homogeneizar a largura e estilo de todas as barras ie poligonais do tipo 6 inclusas nos eixos correntes barh 548 Exemplos primeiro exemplo desenhando uma barra ie uma poligonal com polylinestyle 6stylegrouped width05 coloryellow x1lengthy scf0 y1 3 5 barhy05yellow segundo exemplo desenhando três barras ie três poligonais com polylinestyle 6stylegrouped scf1 x1 2 5 y1 5 63 2 74 3 8 barhxy terceiro exemplo stylestacked scf2 x1 2 5 y1 4 72 5 83 6 9 barhxystacked quarto exemplo width02colorgreen stylegrouped scf3 x1 2 5 y1 4 72 5 83 6 9 barhxy02green Ver Também bar barhomogenize plot polylineproperties Autor Farid Belahcene 549 Name barhomogenize Homogeniza todas as barras inclusas nos eixos correntes barhomogenize barhomogenizehstylewidth Parâmetros h manipulador de eixos padrão hgca style string grouped ou stacked padrão grouped width opcional escalar real define a largura uma porcentagem do espaço disponível para a barra padrão 08 Descrição Se há várias chamadas a bar a função barhomogenize permite homogeneizar a largura e estilo de todas as barras ie que têm polylinestyle tipo 6 inclusas nos eixos correntes Estas barras devem ter os mesmos dados x barhomogenize toma os valores padrões hgca width08 stylegrouped barhomogenizeh define os eixos correntes onde o desenho é realizado barhomogenizewidth define a largura das barras em porcentagemgeralmente 0width1 barhomogenizestyle define como as barras são desenhadas A opção grouped permite centrar as M poligonais versus cada componente de x e a opção stacked permite empilhálas Exemplos Primeiro exemplo criação de uma barra amarela ie uma poligonal com polylinestyle6 e três barras ie três poligonais com polylinestyle6 subplot231 xtitleex1 criação de uma barra amarela e três barras x13 y113 y24 3 56 7 89 10 11 barxy1yellowbarxy2 homogeneização dessas quatro barras subplot232 xtitlehomogenização agrupada x13 y113 y24 3 56 7 89 10 11 barxy1yellowbarxy2 barhomogenize homogenização empilhada dessas quatro barras subplot233 xtitlehomogenização empilhada x13 y113 y24 3 56 7 89 10 11 barxy1yellowbarxy2 barhomogenizestacked1 Segundo exemplo criação de uma barra vermelha ie uma poligonal com polylinestyle6 e duas poligonais com type1 função de chamamento do esboço subplot234 barhomogenize 550 xtitleex2 criação de uma barra e duas poligonais x110 ysinx2 barxyred x1110y1sinxcosx plotx1y1 modificando o polylinestyle da segunda poligonal do esboço esta poligonal se torna em uma barra subplot235 xtitletransformação da segunda poligonal em uma barra x110 ysinx2 barxyred x1110y1sinxcosx plotx1y1 egce e2echildren2 e2polylinestyle6 homogenização da primeira barra da função bar e da segunda barra da modificação subplot236 xtitlehomogeneização em grupo x110 ysinx2 barxyred x1110y1sinxcosx plotx1y1 egce e2echildren2 e2polylinestyle6 barhomogenize mudança de estilo e largura barhomogenizestacked05 barhomogenizestacked1 Ver Também bar polylineproperties Autor Farid Belacehne 551 Name bonecolormap Mapa de cores cinza com um tom claro de azul cmapbonecolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição bonecolormap computa um mapa de cores cinza com um tom azul claro Exemplos f scf plot3d1 fcolormap bonecolormap32 Ver Também colormap autumncolormap coolcolormap coppercolormap graycolormap hotcolormap hsvcol ormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercol ormap whitecolormap wintercolormap 552 Name captions Impressão de legendas de gráficos hlcaptionsh strings location Parâmetros h vetor de manipuladores de entidades Polyline strings nvetor de strings stringsi é a legenda da iésima poligonal hl um manipulador do tipo Legend pontos para a estrutura contendo todas as informações das legendas ver legendproperties location string com possíveis valores inupperright as legendas são exibidas no canto superior direito da caixa de eixos inupperleft as legendas são exibidas no canto superior esquerdo da caixa de eixos inlowerright as legendas são exibidas no canto inferior direito da caixa de eixos inlowerleft as legendas são exibidas no canto inferior esquerdo da caixa de eixos outupperright as legendas são exibidas à direita do canto superior direito da caixa de eixos outupperleft as legendas são exibidas à esquerda do canto superior esquerdo da caixa de eixos outlowerright as legendas são exibidas à direita do canto inferior direito da caixa de eixos outlowerleft as legendas são exibidas à esquerda do canto inferior esquerdo da caixa de eixos uppercaption as legendas são exibidas acima do canto superior esquerdo da caixa de eixos lowercaption as legendas são exibidas abaixo do canto inferior esquerdo da caixa de eixos Esta opção corresponde ao argumento leg de plot2d bycoordinates o canto superior esquerdo da caixa das legendas é dada pelo campo position da estrutura de dados associada As posições x e y são fornecidas como frações dos tamanhos de axesbounds Descrição Coloca legendas no esboço corrente no canto inferior esquerdo da janela gráfica utilizandose os strings especificados como rótulos captions prefixa rótulos por uma nova chamada às poligonais corre spondentes O tipo e propriedades são recuperados do dado manipulador A função captions cria uma estrutura de dados Legend Há no máximo uma Legend associada a cada entidade Axes Se a função caption for chamada nova mente enquanto Legend ainda existe a legenda antiga é apagada captions 553 Exemplos t0012pi agcaadataboundst1 18t 18 amargins402 plot2dtcostcos2tcos3t12 3 egce echildren1thickness3 echildren2linestyle4 hlcaptionsechildrencostcos2tcos3t hlcaptionsechildrencostcos2tcos3tinupperright hllegendlocationinupperright hlfillmodeon Ver Também plot2d legend polylineproperties legendproperties 554 Name champ esboço de campo vetorial 2d champxyfxfyarfactrectstrf champxyfxfyoptargs Parâmetros xy dois vetores que definem o grid fx uma matriz que descreve o componente x do campo vetorial fxij é o componente x do campo vetorial no ponto xiyj fy uma matriz que descreve o componente y do campo vetorial fyijé o componente y do campo vetorial no ponto xiyj optargs representa a seqüência de declarações key1value1key2value2 onde key1 key2 podem ser um dos seguintes arfact rect strf ver abaixo arfact um argumento opcional do tipo real que fornece um fator de escala para a exibição das cabeças das setas no esboço o valor padrão é 10 rect um vetor rectxminyminxmaxymax que fornece as fronteiras da moldura gráfica à ser utilizada strf um string de comprimento 3 xyz que possui o mesmo significado do parâmetro strf de plot2d O primeiro caractere não tem efeito com champ Descrição champ desenha um campo vetorial 2d O comprimento das setas é proporcional é proporcional à intensidade do campo Se você quiser setas coloridas com a cor das setas dependendo da intensidade do campo use champ1 Entre com o comando champ para visualizar uma demonstração Exemplos usando rect como fronteiras do esboço champ5555rand1111rand1111rect10101010arfact2 usando xy para conseguir obter clf champ5555rand1111rand1111210101010021 Ver Também champ1 fchamp plot2d Autor JPhC 556 Name champ1 campo vetorial 2d com setas coloridas champ1xyfxfyarfactrectstrf Parâmetros xy dois vetores que definem o grid fx uma matriz que descreve o componente x do campo vetorial fxij é o componente x do campo vetorial no ponto xiyj fy uma matriz que descreve o componente y do campo vetorial fyij é o componente y do campo vetorial no ponto xiyj arfact um argumento opcional do tipo real que fornece um fator de escala para a exibição das cabeças das setas no esboço o valor padrão é 10 rect um vetor rectxminyminxmaxymax que fornece as fronteiras da moldura gráfica a ser utilizada frameflag ccontrola a computação dos intervalos de coordenadas verdadeiros a partir dos valores mínimos requeridos O valor associado deve ser um inteiro no intervalo de 0 a 8 axesflag especifica como os eixos são desenhados O valor associado deve ser um inteiro no intervalo de 0 a 5 strf um string de comprimento 3 xyz que possui o mesmo significado do parâmetro strf de plot2d O primeiro caractere não tem efeito com champ1 Descrição champ1 desenha um campo vetorial 2d com setas coloridas A cor das setas depende da intensidade do campo Se você quiser setas proporcionais à intensidade do campo use champ Entre com o comando champ1 para visualizar uma demonstração Exemplos champ15555rand1111rand1111rect10101010arfact2 Ver Também champ fchamp plot2d Autor JPhC 558 Name champproperties Descrição das propriedades da entidade campo vetorial 2d Descrição A entidade Champ é uma folha na hierarquia de entidade gráficas Esta entidade define parâmetros para um campo vetorial 2d visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Se on o campo vetorial é desenhado se off o campo vetorial não aparece na tela data este campo define uma estrutura de dados tlist de tipo champdata composto de uma linha e índices de colunas de cada elemento as coordenadas do grid x e y contidas respectiva mente em datax e datay Os campos complementares chamados datafx e datafy são matrizes que descrevem respectivamente os componentes x e y do campo vetorial no ponto xiyj userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade Champ e recuperála linestyle o valor da propriedade linestyle deve ser um valor inteiro no intervalo 0 9 0 significa linha sólida e os outros valores significam estilos de tracejados Esta propriedade aplicase a todas as linhas usadas para desenhar o campo vetorial thickness este campo contém o valor da propriedade thickness espessura para todas as linhas utilizadas no desenho Seu valor deve ser um inteiro nãonegativo colored se o valor desta propriedade for on os vetores são coloridos utilizandose uma cor porporcional à intensidade do campo clipstate este campo contém o valor da propriedade clipstate para a entidade Champ Pode ser off significa que o campo vetorial não é recortado clipgrf siginifica que o campo vetorial é recortado fora da caixa da entidade Axes on significa que o campo vetorial é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo contém o valor da propriedade clipbox Seu valor pode ser uma matriz vazia se a propriedade clipstate é off em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções do campo a serem exibidas contudo o valor da propriedade clipstate será modificado parent esta propriedade contém o manipulador da raiz A raiz de uma entidade campo vetorial 2d deve ser do tipo Axes ou Compound Exemplos champproperties 559 agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds10101010 champ5555rand1111rand1111 cachildren ccoloredon cthickness2 cdata exibindo um tlist do tipo scichampdata adatabounds5555 Ver Também set get delete champ champ1 graphicsentities Autor Djalel ABDEMOUCHE 560 Name clearpixmap Apaga o buffer de pixmap mapa de píxeis clearpixmap Descrição Se a propriedade de uma janela de gráficos pixmap for on as gravuras são enviadas para uma memória pixmap ao invés de serem exibidas na tela A instrução clearpixmap apaga o pixmap mas não a tela O modo pixmap pode ser usado para se obter animações suaves Ver Também figureproperties showpixmap Autor Serge Steer INRIA 561 Name clf Limpa ou reajusta a janela da figura gráfica corrente para valores padrões clfoptjobarg clfhoptjobarg clfnumoptjobarg Parâmetros h o manipulador da figura num identificador da figura figureid optjobarg um string clear ou reset especificando o trabalho de clf Descrição O comando clf é utilizado para reajustar uma figura para seus valores padrões eou deletar todos os seus galhos Se o valor do string optjobarg for clear então todos os galhos da figura especificada são deletados Se o valor do string optjobarg for reset então não só todos os galhos da figura são deletados mas os valores das propriedades da figura são reajustados para seus valores padrões uti lizandose a figura modelo padrão ver gdf As únicas exceções são as propriedades axessize e figuresize que não podem ser reajustadas se a figura está aportada com outros elementos clfnum limpa ou reajusta e limpa a figura com figureidnum clfh limpa ou reajusta e limpa a figura apontada pelo manipulador h clf limpa ou reajusta e limpa a figura existente corrente clf deleta todos os galhos de janelas especificadas incluindo menus e uicontrols adicionados pelo usuário Para evitar que menus e uicontrols sejam deletados o comando deletegca deve ser utilizado ao invés Exemplos f4scf4 criando figura com id4 e tornandoa a figura corrente f4colormap jetcolormap64 f4figuresize 400 200 plot2d clff4reset f0scf0 criando figura com id0 e tornandoa a figura corrente f0colormaphotcolormap128 mudando o mapa de cores tpi03pi plot3d1ttsintcost clf equivalent to clfgcfclear plot3d1ttsintcost colormap inalterado clf 562 clfgcfreset plot3d1ttsintcost colormap alterado de volta ao padrão com 32 cores See Also set get gcf gdf scf graphicsentities Authors S Steer FLeray INRIA 563 Name color Retorna o identificador de uma cor idcolorname idcolorrgb Parâmetros name nome de uma cor rgb valores RGB inteiros de uma cor id identificador da cor Descrição color retorna o identificador de cor correspondente ao seu argumento name deve ser um nome de cor conhecido ver colorlist r g e b devem ser inteiros entre 0 e 255 correspondentes aos componentes de cor vermelho verde e azul Como de uso 0 significa nenhuma intensidade e 255 significa total idensidade para a cor Se a cor requisitada não existe no mapa de cores corrente então ela é adicionada ao mapa de cores Esta função pode ser utilizada para se especificar as cores de plano de fundo e de primeiro plano em esboços Exemplos xlinspace2pi2pi100 utilizando cores existentes plot2dxsinxcosxstylecolorredcolorgreen novas cores adicionadas ao mapa de core egce p1echildren1 p2echildren2 p1foregroundcolorpurple p2foregroundcolornavy blue utilizando valores RGB p1foregroundcolor255128128 Ver Também colormap colorlist getcolor 564 Name colorlist Lista dos nomes das cores Descrição Abaixo você encontrará os nomes das cores conhecidas pelo Scilab Os valores RGB vermelho verde azul são dados após os nomes Note que algumas vezes as cores possuem mais de um nome scilab blue4 azul 0 0 144 scilabblue4 0 0 144 scilab blue3 0 0 176 scilabblue3 0 0 176 scilab blue2 0 0 208 scilabblue2 0 0 208 scilab green4 verde 0 144 0 scilabgreen4 0 144 0 scilab green3 0 176 0 scilabgreen3 0 176 0 scilab green2 0 208 0 scilabgreen2 0 208 0 scilab cyan4 ciano 0 144 144 scilabcyan4 0 144 144 scilab cyan3 0 176 176 scilabcyan3 0 176 176 scilab cyan2 0 208 208 scilabcyan2 0 208 208 scilab red4 vermelho 144 0 0 scilabred4 144 0 0 scilab red3 176 0 0 scilabred3 176 0 0 scilab red2 208 0 0 scilabred2 208 0 0 scilab magenta4 ma genta 144 0 144 scilabmagenta4 144 0 144 scilab magenta3 176 0 176 scilabmagenta3 176 0 176 scilab magenta2 208 0 208 scilabmagenta2 208 0 208 scilab brown4 marrom 128 48 0 scilabbrown4 128 48 0 scilab brown3 160 64 0 scilabbrown3 160 64 0 scilab brown2 192 96 0 colorlist 565 scilabbrown2 192 96 0 scilab pink4 rosa 255 128 128 scilabpink4 255 128 128 scilab pink3 255 160 160 scilabpink3 255 160 160 scilab pink2 255 192 192 scilabpink2 255 192 192 scilab pink 255 224 224 scilabpink 255 224 224 snow branco 255 250 250 ghost white branco 248 248 255 ghostwhite 248 248 255 white smoke branco 245 245 245 whitesmoke 245 245 245 gainsboro cinza 220 220 220 floral white branco 255 250 240 floralwhite 255 250 240 old lace creme 253 245 230 oldlace 253 245 230 linen creme 250 240 230 antique white creme 250 235 215 antiquewhite 250 235 215 papaya whip creme alaranjado 255 239 213 papayawhip 255 239 213 blanched almond creme alaranjado 255 235 205 blanchedalmond 255 235 205 bisque creme alaranja do 255 228 196 peach puff pêssego claro 255 218 185 peachpuff 255 218 185 navajo white pêssego 255 222 173 navajowhite 255 222 173 moccasin pêssego 255 228 181 cornsilk branco creme 255 248 220 ivory marfim 255 255 240 lemon chiffon branco rosa 255 250 205 lemonchiffon 255 250 205 seashell brancorosa 255 245 238 colorlist 566 honeydew branco men ta 240 255 240 mint cream creme de menta 245 255 250 mintcream 245 255 250 azure azulbebê 240 255 255 alice blue azulbebê 240 248 255 aliceblue 240 248 255 lavender lavanda 230 230 250 lavender blush lavanda claro 255 240 245 lavenderblush 255 240 245 misty rose rosa 255 228 225 mistyrose 255 228 225 white branco 255 255 255 black preto 0 0 0 dark slate gray cinza azulado escuro 47 79 79 darkslategray 47 79 79 dark slate grey 47 79 79 darkslategrey 47 79 79 dim gray cinza escuro 105 105 105 dimgray 105 105 105 dim grey 105 105 105 dimgrey 105 105 105 slate gray cinza azula do 112 128 144 slategray 112 128 144 slate grey 112 128 144 slategrey 112 128 144 light slate gray cinza azulado claro 119 136 153 lightslategray 119 136 153 light slate grey 119 136 153 lightslategrey 119 136 153 gray cinza 190 190 190 grey 190 190 190 light grey cinza claro 211 211 211 lightgrey 211 211 211 light gray 211 211 211 lightgray 211 211 211 midnight blue azul meianoite 25 25 112 colorlist 567 midnightblue 25 25 112 navy azul marinho 0 0 128 navy blue 0 0 128 navyblue 0 0 128 cornflower blue azul meio claro 100 149 237 cornflowerblue 100 149 237 dark slate blue púrpura azulado escuro 72 61 139 darkslateblue 72 61 139 slate blue púrpura azu lado 106 90 205 slateblue 106 90 205 medium slate blue púrpura azulado médio 123 104 238 mediumslateblue 123 104 238 light slate blue púrpura azulado claro 132 112 255 lightslateblue 132 112 255 medium blue azul médio 0 0 205 mediumblue 0 0 205 royal blue azul real 65 105 225 royalblue 65 105 225 blue azul 0 0 255 dodger blue azul meio claro 30 144 255 dodgerblue 30 144 255 deep sky blue azul claro 0 191 255 deepskyblue 0 191 255 sky blue azul leve mente esverdiado 135 206 235 skyblue 135 206 235 light sky blue azul lev emente esverdiado 135 206 250 lightskyblue 135 206 250 steel blue azul metálico 70 130 180 steelblue 70 130 180 light steel blue cinza levemente azulado 176 196 222 lightsteelblue 176 196 222 light blue 173 216 230 colorlist 568 lightblue 173 216 230 powder blue turquesa clara 176 224 230 powderblue 176 224 230 pale turquoise turquesa clara 175 238 238 paleturquoise 175 238 238 dark turquoise turquesa escura 0 206 209 darkturquoise 0 206 209 medium turquoise turquesa média 72 209 204 mediumturquoise 72 209 204 turquoise turquesa 64 224 208 cyan ciano 0 255 255 light cyan branco ciano 224 255 255 lightcyan 224 255 255 cadet blue azul cin zaesverdeado 95 158 160 cadetblue 95 158 160 medium aquamarine aquamarine média 102 205 170 mediumaquamarine 102 205 170 aquamarine aquama rine 127 255 212 dark green verde es curo 0 100 0 darkgreen 0 100 0 dark olive green verde oliva escuro 85 107 47 darkolivegreen 85 107 47 dark sea green verde mar claro 143 188 143 darkseagreen 143 188 143 sea green verdemar 46 139 87 seagreen 46 139 87 medium sea green verdemar médio 60 179 113 mediumseagreen 60 179 113 light sea green verde mar claro 32 178 170 lightseagreen 32 178 170 pale green verde pálido 152 251 152 colorlist 569 palegreen 152 251 152 spring green verde pri mavera 0 255 127 springgreen 0 255 127 lawn green verde gra ma 124 252 0 lawngreen 124 252 0 green verde 0 255 0 chartreuse verde claro 127 255 0 medium spring green verde azulado 0 250 154 mediumspringgreen 0 250 154 green yellow verde amarelado 173 255 47 greenyellow 173 255 47 lime green verdelodo 50 205 50 limegreen 50 205 50 yellow green amarelo esverdeado 154 205 50 yellowgreen 154 205 50 forest green verdeflo resta 34 139 34 forestgreen 34 139 34 olive drab verde azeitona 107 142 35 olivedrab 107 142 35 dark khaki cáqui es curo 189 183 107 darkkhaki 189 183 107 khaki 240 230 140 pale goldenrod amarelo queimado pálido 238 232 170 palegoldenrod 238 232 170 light goldenrod yellow bege claro 250 250 210 lightgoldenrodyellow 250 250 210 light yellow amarelo claro 255 255 224 lightyellow 255 255 224 yellow amarelo 255 255 0 gold ouro 255 215 0 light goldenrod amare lo queimado claro 238 221 130 lightgoldenrod 238 221 130 colorlist 570 goldenrod amarelo queimado 218 165 32 dark goldenrod amare lo queimado escuro 184 134 11 darkgoldenrod 184 134 11 rosy brown rosa com tonalidade marrom 188 143 143 rosybrown 188 143 143 indian red vermelho índio 205 92 92 indianred 205 92 92 saddle brown marrom sela 139 69 19 saddlebrown 139 69 19 sienna marrom 160 82 45 peru marrom 205 133 63 burlywood marrom claro 222 184 135 beige bege 245 245 220 wheat trigo 245 222 179 sandy brown marrom arenoso 244 164 96 sandybrown 244 164 96 tan marrom bronzeado 210 180 140 chocolate chocolate 210 105 30 firebrick vermelho sangue 178 34 34 brown marrom 165 42 42 dark salmon salmão es curo 233 150 122 darksalmon 233 150 122 salmon salmão 250 128 114 light salmon salmão claro 255 160 122 lightsalmon 255 160 122 orange laranja 255 165 0 dark orange laranja es curo 255 140 0 darkorange 255 140 0 coral laranja salmon 255 127 80 light coral salmon rosa do 240 128 128 lightcoral 240 128 128 tomato tomate 255 99 71 colorlist 571 orange red laranja aver melhado 255 69 0 orangered 255 69 0 red vermelho 255 0 0 hot pink rosa quente 255 105 180 hotpink 255 105 180 deep pink rosa vivo 255 20 147 deeppink 255 20 147 pink rosa claro 255 192 203 light pink rosa 255 182 193 lightpink 255 182 193 pale violet red violeta avermelhado claro 219 112 147 palevioletred 219 112 147 maroon vinho rosado 176 48 96 medium violet red violeta avermelhado médio 199 21 133 mediumvioletred 199 21 133 violet red violeta aver melhado 208 32 144 violetred 208 32 144 magenta magenta 255 0 255 violet violeta 238 130 238 plum ameixa 221 160 221 orchid orquídea 218 112 214 medium orchid orquídea médio 186 85 211 mediumorchid 186 85 211 dark orchid orquídea escuro 153 50 204 darkorchid 153 50 204 dark violet violeta es curo 148 0 211 darkviolet 148 0 211 blue violet violeta azu lado 138 43 226 blueviolet 138 43 226 purple púrpura 160 32 240 medium purple púrpura claro 147 112 219 mediumpurple 147 112 219 thistle roxo acinzenta do 216 191 216 colorlist 572 daqui em diante são séries de gradações de cores snow1 255 250 250 snow2 238 233 233 snow3 205 201 201 snow4 139 137 137 seashell1 255 245 238 seashell2 238 229 222 seashell3 205 197 191 seashell4 139 134 130 antiquewhite1 255 239 219 antiquewhite2 238 223 204 antiquewhite3 205 192 176 antiquewhite4 139 131 120 bisque1 255 228 196 bisque2 238 213 183 bisque3 205 183 158 bisque4 139 125 107 peachpuff1 255 218 185 peachpuff2 238 203 173 peachpuff3 205 175 149 peachpuff4 139 119 101 navajowhite1 255 222 173 navajowhite2 238 207 161 navajowhite3 205 179 139 navajowhite4 139 121 94 lemonchiffon1 255 250 205 lemonchiffon2 238 233 191 lemonchiffon3 205 201 165 lemonchiffon4 139 137 112 cornsilk1 255 248 220 cornsilk2 238 232 205 cornsilk3 205 200 177 cornsilk4 139 136 120 ivory1 255 255 240 ivory2 238 238 224 ivory3 205 205 193 ivory4 139 139 131 honeydew1 240 255 240 honeydew2 224 238 224 honeydew3 193 205 193 honeydew4 131 139 131 colorlist 573 lavenderblush1 255 240 245 lavenderblush2 238 224 229 lavenderblush3 205 193 197 lavenderblush4 139 131 134 mistyrose1 255 228 225 mistyrose2 238 213 210 mistyrose3 205 183 181 mistyrose4 139 125 123 azure1 240 255 255 azure2 224 238 238 azure3 193 205 205 azure4 131 139 139 slateblue1 131 111 255 slateblue2 122 103 238 slateblue3 105 89 205 slateblue4 71 60 139 royalblue1 72 118 255 royalblue2 67 110 238 royalblue3 58 95 205 royalblue4 39 64 139 blue1 0 0 255 blue2 0 0 238 blue3 0 0 205 blue4 0 0 139 dodgerblue1 30 144 255 dodgerblue2 28 134 238 dodgerblue3 24 116 205 dodgerblue4 16 78 139 steelblue1 99 184 255 steelblue2 92 172 238 steelblue3 79 148 205 steelblue4 54 100 139 deepskyblue1 0 191 255 deepskyblue2 0 178 238 deepskyblue3 0 154 205 deepskyblue4 0 104 139 skyblue1 135 206 255 skyblue2 126 192 238 skyblue3 108 166 205 skyblue4 74 112 139 lightskyblue1 176 226 255 colorlist 574 lightskyblue2 164 211 238 lightskyblue3 141 182 205 lightskyblue4 96 123 139 slategray1 198 226 255 slategray2 185 211 238 slategray3 159 182 205 slategray4 108 123 139 lightsteelblue1 202 225 255 lightsteelblue2 188 210 238 lightsteelblue3 162 181 205 lightsteelblue4 110 123 139 lightblue1 191 239 255 lightblue2 178 223 238 lightblue3 154 192 205 lightblue4 104 131 139 lightcyan1 224 255 255 lightcyan2 209 238 238 lightcyan3 180 205 205 lightcyan4 122 139 139 paleturquoise1 187 255 255 paleturquoise2 174 238 238 paleturquoise3 150 205 205 paleturquoise4 102 139 139 cadetblue1 152 245 255 cadetblue2 142 229 238 cadetblue3 122 197 205 cadetblue4 83 134 139 turquoise1 0 245 255 turquoise2 0 229 238 turquoise3 0 197 205 turquoise4 0 134 139 cyan1 0 255 255 cyan2 0 238 238 cyan3 0 205 205 cyan4 0 139 139 darkslategray1 151 255 255 darkslategray2 141 238 238 darkslategray3 121 205 205 darkslategray4 82 139 139 aquamarine1 127 255 212 colorlist 575 aquamarine2 118 238 198 aquamarine3 102 205 170 aquamarine4 69 139 116 darkseagreen1 193 255 193 darkseagreen2 180 238 180 darkseagreen3 155 205 155 darkseagreen4 105 139 105 seagreen1 84 255 159 seagreen2 78 238 148 seagreen3 67 205 128 seagreen4 46 139 87 palegreen1 154 255 154 palegreen2 144 238 144 palegreen3 124 205 124 palegreen4 84 139 84 springgreen1 0 255 127 springgreen2 0 238 118 springgreen3 0 205 102 springgreen4 0 139 69 green1 0 255 0 green2 0 238 0 green3 0 205 0 green4 0 139 0 chartreuse1 127 255 0 chartreuse2 118 238 0 chartreuse3 102 205 0 chartreuse4 69 139 0 olivedrab1 192 255 62 olivedrab2 179 238 58 olivedrab3 154 205 50 olivedrab4 105 139 34 darkolivegreen1 202 255 112 darkolivegreen2 188 238 104 darkolivegreen3 162 205 90 darkolivegreen4 110 139 61 khaki1 255 246 143 khaki2 238 230 133 khaki3 205 198 115 khaki4 139 134 78 lightgoldenrod1 255 236 139 lightgoldenrod2 238 220 130 colorlist 576 lightgoldenrod3 205 190 112 lightgoldenrod4 139 129 76 lightyellow1 255 255 224 lightyellow2 238 238 209 lightyellow3 205 205 180 lightyellow4 139 139 122 yellow1 255 255 0 yellow2 238 238 0 yellow3 205 205 0 yellow4 139 139 0 gold1 255 215 0 gold2 238 201 0 gold3 205 173 0 gold4 139 117 0 goldenrod1 255 193 37 goldenrod2 238 180 34 goldenrod3 205 155 29 goldenrod4 139 105 20 darkgoldenrod1 255 185 15 darkgoldenrod2 238 173 14 darkgoldenrod3 205 149 12 darkgoldenrod4 139 101 8 rosybrown1 255 193 193 rosybrown2 238 180 180 rosybrown3 205 155 155 rosybrown4 139 105 105 indianred1 255 106 106 indianred2 238 99 99 indianred3 205 85 85 indianred4 139 58 58 sienna1 255 130 71 sienna2 238 121 66 sienna3 205 104 57 sienna4 139 71 38 burlywood1 255 211 155 burlywood2 238 197 145 burlywood3 205 170 125 burlywood4 139 115 85 wheat1 255 231 186 wheat2 238 216 174 wheat3 205 186 150 colorlist 577 wheat4 139 126 102 tan1 255 165 79 tan2 238 154 73 tan3 205 133 63 tan4 139 90 43 chocolate1 255 127 36 chocolate2 238 118 33 chocolate3 205 102 29 chocolate4 139 69 19 firebrick1 255 48 48 firebrick2 238 44 44 firebrick3 205 38 38 firebrick4 139 26 26 brown1 255 64 64 brown2 238 59 59 brown3 205 51 51 brown4 139 35 35 salmon1 255 140 105 salmon2 238 130 98 salmon3 205 112 84 salmon4 139 76 57 lightsalmon1 255 160 122 lightsalmon2 238 149 114 lightsalmon3 205 129 98 lightsalmon4 139 87 66 orange1 255 165 0 orange2 238 154 0 orange3 205 133 0 orange4 139 90 0 darkorange1 255 127 0 darkorange2 238 118 0 darkorange3 205 102 0 darkorange4 139 69 0 coral1 255 114 86 coral2 238 106 80 coral3 205 91 69 coral4 139 62 47 tomato1 255 99 71 tomato2 238 92 66 tomato3 205 79 57 tomato4 139 54 38 colorlist 578 orangered1 255 69 0 orangered2 238 64 0 orangered3 205 55 0 orangered4 139 37 0 red1 255 0 0 red2 238 0 0 red3 205 0 0 red4 139 0 0 deeppink1 255 20 147 deeppink2 238 18 137 deeppink3 205 16 118 deeppink4 139 10 80 hotpink1 255 110 180 hotpink2 238 106 167 hotpink3 205 96 144 hotpink4 139 58 98 pink1 255 181 197 pink2 238 169 184 pink3 205 145 158 pink4 139 99 108 lightpink1 255 174 185 lightpink2 238 162 173 lightpink3 205 140 149 lightpink4 139 95 101 palevioletred1 255 130 171 palevioletred2 238 121 159 palevioletred3 205 104 137 palevioletred4 139 71 93 maroon1 255 52 179 maroon2 238 48 167 maroon3 205 41 144 maroon4 139 28 98 violetred1 255 62 150 violetred2 238 58 140 violetred3 205 50 120 violetred4 139 34 82 magenta1 255 0 255 magenta2 238 0 238 magenta3 205 0 205 magenta4 139 0 139 orchid1 255 131 250 colorlist 579 orchid2 238 122 233 orchid3 205 105 201 orchid4 139 71 137 plum1 255 187 255 plum2 238 174 238 plum3 205 150 205 plum4 139 102 139 mediumorchid1 224 102 255 mediumorchid2 209 95 238 mediumorchid3 180 82 205 mediumorchid4 122 55 139 darkorchid1 191 62 255 darkorchid2 178 58 238 darkorchid3 154 50 205 darkorchid4 104 34 139 purple1 155 48 255 purple2 145 44 238 purple3 125 38 205 purple4 85 26 139 mediumpurple1 171 130 255 mediumpurple2 159 121 238 mediumpurple3 137 104 205 mediumpurple4 93 71 139 thistle1 255 225 255 thistle2 238 210 238 thistle3 205 181 205 thistle4 139 123 139 gray0 0 0 0 grey0 0 0 0 gray1 3 3 3 grey1 3 3 3 gray2 5 5 5 grey2 5 5 5 gray3 8 8 8 grey3 8 8 8 gray4 10 10 10 grey4 10 10 10 gray5 13 13 13 grey5 13 13 13 gray6 15 15 15 grey6 15 15 15 colorlist 580 gray7 18 18 18 grey7 18 18 18 gray8 20 20 20 grey8 20 20 20 gray9 23 23 23 grey9 23 23 23 gray10 26 26 26 grey10 26 26 26 gray11 28 28 28 grey11 28 28 28 gray12 31 31 31 grey12 31 31 31 gray13 33 33 33 grey13 33 33 33 gray14 36 36 36 grey14 36 36 36 gray15 38 38 38 grey15 38 38 38 gray16 41 41 41 grey16 41 41 41 gray17 43 43 43 grey17 43 43 43 gray18 46 46 46 grey18 46 46 46 gray19 48 48 48 grey19 48 48 48 gray20 51 51 51 grey20 51 51 51 gray21 54 54 54 grey21 54 54 54 gray22 56 56 56 grey22 56 56 56 gray23 59 59 59 grey23 59 59 59 gray24 61 61 61 grey24 61 61 61 gray25 64 64 64 grey25 64 64 64 gray26 66 66 66 grey26 66 66 66 gray27 69 69 69 grey27 69 69 69 colorlist 581 gray28 71 71 71 grey28 71 71 71 gray29 74 74 74 grey29 74 74 74 gray30 77 77 77 grey30 77 77 77 gray31 79 79 79 grey31 79 79 79 gray32 82 82 82 grey32 82 82 82 gray33 84 84 84 grey33 84 84 84 gray34 87 87 87 grey34 87 87 87 gray35 89 89 89 grey35 89 89 89 gray36 92 92 92 grey36 92 92 92 gray37 94 94 94 grey37 94 94 94 gray38 97 97 97 grey38 97 97 97 gray39 99 99 99 grey39 99 99 99 gray40 102 102 102 grey40 102 102 102 gray41 105 105 105 grey41 105 105 105 gray42 107 107 107 grey42 107 107 107 gray43 110 110 110 grey43 110 110 110 gray44 112 112 112 grey44 112 112 112 gray45 115 115 115 grey45 115 115 115 gray46 117 117 117 grey46 117 117 117 gray47 120 120 120 grey47 120 120 120 gray48 122 122 122 colorlist 582 grey48 122 122 122 gray49 125 125 125 grey49 125 125 125 gray50 127 127 127 grey50 127 127 127 gray51 130 130 130 grey51 130 130 130 gray52 133 133 133 grey52 133 133 133 gray53 135 135 135 grey53 135 135 135 gray54 138 138 138 grey54 138 138 138 gray55 140 140 140 grey55 140 140 140 gray56 143 143 143 grey56 143 143 143 gray57 145 145 145 grey57 145 145 145 gray58 148 148 148 grey58 148 148 148 gray59 150 150 150 grey59 150 150 150 gray60 153 153 153 grey60 153 153 153 gray61 156 156 156 grey61 156 156 156 gray62 158 158 158 grey62 158 158 158 gray63 161 161 161 grey63 161 161 161 gray64 163 163 163 grey64 163 163 163 gray65 166 166 166 grey65 166 166 166 gray66 168 168 168 grey66 168 168 168 gray67 171 171 171 grey67 171 171 171 gray68 173 173 173 grey68 173 173 173 colorlist 583 gray69 176 176 176 grey69 176 176 176 gray70 179 179 179 grey70 179 179 179 gray71 181 181 181 grey71 181 181 181 gray72 184 184 184 grey72 184 184 184 gray73 186 186 186 grey73 186 186 186 gray74 189 189 189 grey74 189 189 189 gray75 191 191 191 grey75 191 191 191 gray76 194 194 194 grey76 194 194 194 gray77 196 196 196 grey77 196 196 196 gray78 199 199 199 grey78 199 199 199 gray79 201 201 201 grey79 201 201 201 gray80 204 204 204 grey80 204 204 204 gray81 207 207 207 grey81 207 207 207 gray82 209 209 209 grey82 209 209 209 gray83 212 212 212 grey83 212 212 212 gray84 214 214 214 grey84 214 214 214 gray85 217 217 217 grey85 217 217 217 gray86 219 219 219 grey86 219 219 219 gray87 222 222 222 grey87 222 222 222 gray88 224 224 224 grey88 224 224 224 gray89 227 227 227 colorlist 584 grey89 227 227 227 gray90 229 229 229 grey90 229 229 229 gray91 232 232 232 grey91 232 232 232 gray92 235 235 235 grey92 235 235 235 gray93 237 237 237 grey93 237 237 237 gray94 240 240 240 grey94 240 240 240 gray95 242 242 242 grey95 242 242 242 gray96 245 245 245 grey96 245 245 245 gray97 247 247 247 grey97 247 247 247 gray98 250 250 250 grey98 250 250 250 gray99 252 252 252 grey99 252 252 252 gray100 255 255 255 grey100 255 255 255 dark grey cinza escuro 169 169 169 darkgrey 169 169 169 dark gray 169 169 169 darkgray 169 169 169 dark blue azul escuro 0 0 139 darkblue 0 0 139 dark cyan ciano escuro 0 139 139 darkcyan 0 139 139 dark magenta magenta escuro 139 0 139 darkmagenta 139 0 139 dark red vermelho es curo 139 0 0 darkred 139 0 0 light green verde claro 144 238 144 lightgreen 144 238 144 Ver Também color name2rgb rgb2name 585 Name colorbar Desenha uma barra de cores colorbarumin umax colminmax fmt Parâmetros umin escalar real o valor mínimo associado ao esboço umax escalar real o valor máximo associado ao esboço colminmax opcional um vetor com dois componentes inteiros fmt optional um string para se ajustar o formato de exbição para as graduações da barra de cores Descrição Desenha uma barra de cores para um plot3d fec Sgrayplot etc Esta função deve ser chamada BE FORE do plot3d fec Sgrayplot porque ela ajusta e modifica a moldura para o esboço Desta for ma a barra de cores não é parte do esboço associado e assim não é modificada por uma ampliação diminuição ou rotação O argumento opcional colminmax pode ser utilizado para precisar a primeira cor associada a umin e a última cor associada a umax do mapa de cores corrente Por padrão colminmax1 nbcolors onde nbcolors é o número de cores do mapa de cores corrente O argumento opcional fmt é um string com formato C como 2f e etc Para os dois argumentos opcionais você pode utilizar a sintaxe keywordvalue que é útil para fornecer o formato sem fornecer colminmax veja o útilmo exemplo Examples exemplo 1 x linspace0181 z cos2pixsin2pix zm minz zM maxz xbasc xsetcolormapjetcolormap64 colorbarzmzM Sgrayplotxxz xtitleThe function cos2 pi xsin2 pi y exemplo 2 x linspace0181 z cos2pixsin2pix zm minz zM maxz zz abs05cos2pixcos2pix zzm minzz zzM maxzz xbasc xsetcolormapjetcolormap64 colorbar 586 drawlater subplot221 colorbarzmzM Sgrayplotxxz strf031 rect0 0 1 1 xtitleum Sgrayplot com barra de cores subplot222 colorbarzmzM plot3d1xxz xtitleum plot3d1 com barra de cores subplot223 colorbarzzmzzM plot3d1xxzz xtitleum plot3d1 com barra de cores subplot224 colorbarzzmzzM Sgrayplotxxzz strf031 rect0 0 1 1 xtitleum Sgrayplot com barra de cores drawnow exemplo 3 x linspace0181 zz abs05cos2pixcos2pix zzm minzz zzM maxzz xfyfzfgenfac3dxxzz nbcol 64 xbasc xsetcolormaphotcolormapnbcol drawlater colorbarzzmzzMfmt1f nbcol xgetlastpattern zcol dsearchzf linspacezzm zzM nbcol1 plot3dxf yf listzf zcol flag 2 6 4 xtitleum plot3d com cores de gradação interpolada drawnow xselect See Also colormap Authors B Pincon S Steer 587 Name colordef Ajusta os valores de cor padrões para exibição de diferentes esquemas de cores colordefcolorscheme colordeffcolorscheme colordefnewcolorscheme Parâmetros colorscheme string com valores possíveis white blacknone f manipulador para uma figura gráfica Descrição colordefwhite ajusta o mapa de cores padrão da figura ver gdf para jetcol ormap64 a cor de plano de fundo padrão da figura para cinza claro a cor de plano de fundo dos eixos ver gda para branco e as cores de primeiro plano da fonte e das linhas dos eixos para preto colordefblack ajusta o mapa de cores padrão da figura ver gdf para jetcol ormap64 a cor de plano de fundo padrão da figura para cinza escuro a cor de plano de fundo dos eixos ver gda para preto e as cores de primeiro plano da fonte e das linhas dos eixos para branco colordefnone ajusta o mapa de cores padrão da figura ver gdf para hsvcol ormap64 a cor de plano de fundo padrão da figura para cinza escuro a cor de plano de fundo dos eixos ver gda para preto e as cores de primeiro plano da fonte e das linhas dos eixos para branco colordeffcolorscheme ajusta as propriedades de cor da figura fornecida pelo manip ulador f tanto quanto as propriedades de cor de seus eixos correntes colordefnewcolorscheme cria uma nova janela de gráficos e ajusta suas pro priedades de cor bem como as propriedades de seus eixos Exemplos Adicionar aqui instruções Scilab e comentários Ver Também gdf gda figureproperties axesproperties Autor S Steer INRIA 588 Name colormap mapa de cores Descrição Um mapa de cores cmap é definido por uma matriz m x 3 m é o número de cores A cor de número i é dada pela tripla cmapi1 cmapi2 cmapi3 correspondentes às intensidades de ver melho verde e azul entre 0 e 1 De início 32 cores são definidas no mapa de cores Você pode modificar o mapa de cores de uma figura através da opção setfcolormapcmap onde f é o manipulador da figura Cada cor no mapa de cores possui um identificador que você deve utilizar para especificar a cor na maioria das funções de esboço Para visualizar os identificadores use a função getcolor As funções hotcolormap jetcolormap e graycolormap fornecem mapas de cores com variação contínua de cores Você pode obter o mapa de cores padrão através de cmapgetsdfcolormap Exemplos n64 rlinspace01n glinspace10n bonesr cmapr g b fgcf fcolormapcmap plot3d1 fcolormapgetsdfcolormap Ver Também autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcolormap hsv colormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summer colormap whitecolormap wintercolormap color getcolor 589 Name Compoundproperties Descrição das propriedades da entidade compound Descrição A entidade Compound é uma entidade de terceiro nível na hierarquia de entidades gráficas Esta en tidade define interdependências entre várias entidades gráficas e suas propriedades de visibilidade global parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Text deve ser do tipo Axes ou Compound children um vetor contendo manipuladores para os objetos gráficos galhos do Compound Estes obje tos gráficos podem ser do tipo Compound Rectangle Polyline Patch Segs Arc Grayplot visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o valor é on onde as entidades gráficas galhos do Compound são desenhadas Se off nenhum dos galhos do Compound é desenhado na tela userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da figura e recuperála Ver Também glue unglue graphicsentities Autor Djalel ABDEMOUCHE 590 Name contour curvas de nível em uma superfície 3d contourxyznzthetaalphalegflageboxzlev contourxyznzoptargs Parâmetros xy vetores de reais de tamanhos n1 e n2 z matriz de reais de tamanho n1n2 os valores da função sobre o gride ou uma função Scilab que define uma superfície zfxy nz os valores de nível ou o número de níveis Se nz for um inteiro seu valor fornece o número de níveis igualmente espaçados de zmin a zmax como segue z zmin 1nzzmaxzminnz1 Note que os níveis zmin e zmax não são desenhados genericamente eles são reduzidos a pontos mas podem ser adicionados através de imjm findz zmin ou zmax plot2dximyjm9000 Se nz for um vetor nzi fornece o valor da iésima curva de nível Note que isto pode ser útil para se visualizar as curvas de nível zmin e zmax para se adicionar uma tolerância eps nzzminepszmaxeps optargs uma seqüência de declarações key1value1 key2value2 onde keys podem ser thetaalphalegflag eboxzlev ver abaixo Neste caso a ordem não possui significa do especial theta alpha valores reais de dados em graus as coordenadas esféricas do ponto de observação leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho três flagmodetypebox mode string de representação de modo mode0 as curvas são desenhadas na superfície definida por xyz contour 591 mode1 as curvas são desenhadas em um esboço 3d e sobre o plano definido pela equação zzlev mode2 as curvas são desenhadas em um esboço 2D type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados ebox usado quando type em flag é 1 Especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax zlev número real contour 592 Descrição contour desenha curvas de nível de uma superfície z fxy As curvas de nível são desenhadas sobre uma superfície 3d Os argumentos opcionais são os mesmos que os da função plot3d exceto por zleve seus significados são os mesmos Eles controlam o desenho das curva de nível em um esboço 3d Apenas flag1mode tem significado especial mode0 as curvas são desenhadas na superfície definida por xyz mode1 as curvas são desenhadas em um esboço 3d e sobre o plano definido pela equação zzlev mode2 as curvas são desenhadas em um esboço 2D Você pode modificar o formato dos pontos flutuantes impressos sobre os níveis utilizando xsetfpfstring onde string fornece o formato em na sintaxe de formato C por exem plo string3f Use string para voltar ao formato padrão e use string para suprimir a impressão Geralmente é usado contour2d para se esboçar curvas de nível em um esboço 2d Entre com o comando contour para visualizar uma demonstração Exemplos tlinspacepipi30 function zmysurfacexyzxsinx2cosyendfunction contourttmysurface10 mudando o formato da impressão dos níveis xsetfpf1f xbasc contourttmysurface10 3D xbasc zfevalttmysurface plot3dttzcontourttz02absz20flag0 2 4 Ver Também contour2d plot3d Autor JPhC 593 Name contour2d curvas de nível de uma superfície em um esboço 2d contour2dxyznzstylestrflegrectnax contour2dxyznzoptargs Parâmetros xy vetores de reais de tamanhos n1 e n2 o grid z matriz de reais de tamanho n1n2 os valores da função sobre o grid ou uma função Scilab que define uma superfície zfxy nz os valores de nível ou o número de níveis Se nz for um inteiro seu valor fornece o número de níveis igualmente espaçados de zmin a zmax como segue z zmin 1nzzmaxzminnz1 Note que os níveis zmin e zmax não são desenhados genericamente eles são reduzidos a pontos mas podem ser adicionados através de imjm findz zmin ou zmax plot2dximyjm9000 Se nz for um vetor nzi fornece o valor da iésima curva de nível optargs representa uma seqüência de declarações key1value1key2value2 onde key1 key2 pode ser um dos seguintes style leg rect nax strf ou axesflag e frameflag ver plot2d stylestrflegrectnax ver plot2d O argumento style fornece os estilos de tracejado ou cores que serão usadas para as curvas de nível Deve ter o mesmo tamanho que o número de níveis Descrição contour2d desenha curvas de nível de uma superfície zfxy em um esboço 2d Os valores de fxy são dados pela matriz z nos pontos de grid definidos por por x e y Você pode modificar o formato dos pontos flutuantes impressos sobre os níveis utilizando xsetfpfstring onde string fornece o formato em na sintaxe de formato C por exem plo string3f Use string para voltar ao formato padrão e use string para suprimir a impressão Este último recurso é útil em conjunção com legends para exibir os números de nível em uma legenda e não diretamente em curvas de nível como de uso ver Exemplos Os argumentos opcionais stylestrflegrectnax podem ser passados através de uma seqüência de declarações key1value1 key2value2 onde podem ser stylestrflegrectnax Neste caso a ordem não tem significado especial contour2d 594 Use contour para esboçar curvas de nível em uma superfície 3d Exemplos contour2d110110rand10105rect001111 mudando o formato de impressão dos níveis xsetfpf2f clf contour2d110110rand10105rect001111 agora um exemplo com números de níveis desenhados em uma legenda Cuidado há alguns truques aqui x linspace04pi80 z cosxcosx clf fgcf xsetfpf truque 1 isto faz com que alguns números de níveis não sejam impressos sobre as curvas de nível fcolormapjetcolormap7 truque 2 para fazer com que se possa colocar a legenda à direita sem sem interferir com as curvas de nível use rect com um valor xmax grande o suficiente contour2dxxz075025075frameflag3rect005pi4pi truque 3 use legends note que a função mais prática legend não funcionará quando um dos níveis for formado por duas curvas legendsstring07502507517lr xtitleAlgumas curvas de nível da função cosxcosy Ver Também contour contour2di plot2d Autor JPhC 595 Name contour2di Computa curvas de nível em um esboço 2d xcyccontour2dixyznz Parâmetros xy dois vetores de reais de tamanhos n1 e n2 definindo o grid z matriz de reais de tamanho n1n2 os valores da função nz os valores de nível ou o número de níveis Se nz for um inteiro seu valor fornece o número de níveis igualmente espaçados de zmin a zmax como segue z zmin 1nzzmaxzminnz1 Note que os níveis zmin e zmax não são desenhados genericamente eles são reduzidos a pontos mas podem ser adicionados através de imjm findz zmin ou zmax plot2dximyjm9000 Se nz for um vetor nzi fornece o valor da iésima curva de nível xcyc vetores de tamanhos idênticos contendo as definições dos contornos Ver detalhes abaixo Descrição contour2di computa as curvas de nível de uma superfície zfxy em um esboço 2d Os valores de fxy asão dados pela matriz z nos pontos de grid definidos por x e y xc1 contém o nível associado ao primeiro caminho de contorno yc1 contém o número N1 de pontos definindo este caminho de contorno e xc11N1 yc11N1 contém as coordenadas dos pontos do caminho O segundo caminho começa em xc2N1 e yc2N1 e assim por diante Exemplos xcyccontour2di110110rand10105 k1nyckc1 while kycksizexc nyck plot2dxck1nyck1nc cc1 kkn1 end contour2di 596 Ver Também contour fcontour fcontour2d contour2d plot2d xset Autor JPhC 597 Name contourf Curvas de nível preenchidas de uma superfície em um esboço 2d contourfxyznzstylestrflegrectnax Parâmetrtos xy dois vetores de reais de tamanhos n1 e n2 definindo o grid z matriz de reais de tamanho n1n2 os valores da função nz os valores de nível ou o número de níveis Se nz for um inteiro seu valor fornece o número de níveis igualmente espaçados de zmin a zmax como segue z zmin 1nzzmaxzminnz1 Note que os níveis zmin e zmax não são desenhados genericamente eles são reduzidos a pontos mas podem ser adicionados através de imjm findz zmin ou zmax plot2dximyjm9000 Se nz for um vetor nzi fornece o valor da iésima curva de nível stylestrflegrectnax ver plot2d O argumento style fornece as cores a serem utilizadas pelas curvas de nível Deve ter o mesmo tamanho que o número de níveis Descrição contourf pinta a superfície entre duas curvas de nível consecutivas zfxy em um esboço 2d Os valores de fxy são fornecidos pela matriz z nos pontos de grid definidos por x e y Você pode mudar o formato dos pontos flutuantes impressos sobre os níveis utilizando xsetfpfstring onde string fornece o formato em sintaxe de formato C por exemplo string3f Use string para voltar ao formato padrão Entre com o comando contourf para visualizar uma demonstração Exemplos contourf110110rand1010515011 001111 function zpeaksxy x1xones1sizey contourf 598 y1yonessizex1 z 31x12expx12 y112 10x15 x13 y15expx12y12 13expx112 y12 endfunction function zpeakit x4014yxzpeaksxy endfunction zpeakit levels61logspace5010logspace501018 msizelevels n fix38m r 1nn onesmn1 g zerosn1 1nn onesm2n1 b zeros2n1 1m2nm2n h r g b xsetcolormaph xsetfpf xbasc contourfz61logspace5010logspace5010180ones1m xsetfpf xbasc contourfz61logspace5010logspace501018 Ver Também contour fcontour fcontour2d contour2di plot2d xset Autor JPhC 599 Name coolcolormap Mapa de cores de ciano a magenta cmapcoolcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição coolcolormap computa um mapa de cores com n cores variando de ciano a magenta Exemplos f scf plot3d1 fcolormap coolcolormap32 Ver Também colormap autumncolormap bonecolormap coppercolormap graycolormap hotcolormap hsvcol ormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercol ormap whitecolormap wintercolormap 600 Name coppercolormap Mapa de cores de preto a um tom claro de cobre cmapcoppercolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição coppercolormap computa um mapa de cores com n cores que variam de preto a um tom claro de cobre Exemplos f scf plot3d1 fcolormap coppercolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap graycolormap hotcolormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 601 Name copy Copia uma entidade de gráficos copyh copyhhaxes hcopycopyh Parâmetros h manipulador da entidade a ser copiada haxes manipulador da entidade raiz para destino Deve ser uma entidade Axes de eixos hcopy manipulador da entidade copiada Descrição Esta rotina pode ser usada para copiar uma entidade de gráficos com todos os seus valores de pro priedades retornando o manipulador da nova entidade Se haxes for omitido a entidade gráfica é clonada e copiada no mesmo na mesma entidade Axes raiz Exemplos subplot211a1gca plot2d egce p1echildren1 p2copyp1p2data2p2data205 subplot212a2gca a2databoundsa1databounds copyp1a2 Ver Também get set delete move graphicsentities Autor Djalel ABDEMOUCHE 602 Name delete Deleta uma entidade gráfica e seus galhos deleteh deletehcallback delete deleteall Parâmetros h manipulador da entidade gráfica a ser deletada h pode ser um vetor de manipuladores em qual caso todos os objetos identificados por hi serão deletados all palavrachave string opcional Descrição Esta rotina pode ser utilizada para deletar uma entidade gráfica identificada pelo manipulador dado como argumento Neste caso todos os galhos desta entidade gráfica serão deletados Sem qualaquer argumento delete remove a entidade corrente Com o argumento all deleta todas as entidades da figura corrente O argumento callback ainda não é manipulado Exemplos subplot211 t110plot2dtt2 subplot223 plot3d subplot224 plot2d xfrect1031 agetcurrentaxes delete deletando o novo objeto gráfico criado deleteachildren deletando todos os galhos dos eixos corentes deletea deletando os eixos deleteall deletando todos os objetos gráficos da figura Ver Também get set copy move ishandlevalid graphicsentities Autor Djalel ABDEMOUCHE 603 Name dragrect Arrasta retângulos com o mouse finalrectbtndragrectinitialrect Parâmetros initialrect matrtiz 4xn contendo as definições iniciais do retângulo Cada coluna contém xesquerdo ytopo largura altura Se apenas um retângulo estiver presente initialrect pode ser também um vetor finalrect um retângulo xesquerdo ytopo largura altura btn um inteiro o número do botão do mouse clicado Descrição dragrect arrasta um ou mais retângulos para qualquer lugar da tela A matriz rect 4xn define os retângulos Cada coluna de initialrect deve conter a posição inicial do retângulo como valores xesquerdoytopolarguraaltura Quando um botão é clicado dragrect retorna as definições dos retângulos finais em finalRect Exemplos xsetechfrect00100100 rdragrect10103010 xrectr Ver Também xrect xrects xclick xgetmouse 604 Name draw Desenha uma entidade draw drawh Parâmetros h a o manipulador de uma entidade a ser desenhada h pode ser um vetor de manipuladores Neste caso todos os objetos identificados por hi will serão desenhados Descrição Esta função pode ser utilizada para desenhar entidades especificadas por h mesmo se a propriedade de figura raiz immediatedrawing for off Se nenhum argumento for especificado o objeto corrente é desenhado Note que a janela não deve ser redimensionada se for esses objetos serão escondidos Exemplos subplot212 agca plot2d drawlater subplot211 plot2d1 modo de desenho padrão egce drawechildren2 desenhando uma única poligonal dos segundos eixos echildren1visibleoff podemos escolher tornar uma linha invisível drawe desenha o Compound e seus galhos ltgt desenha todas as poligonais visíveis drawnow agora echildren1visibleon Ver Também get set drawnow drawlater graphicsentities Autores Djalel ABDEMOUCHE FLeray 605 Name drawaxis Desenha um eixo drawaxisoptions opções xydirsubintfontsizeformatnsegtextcolorticscolortics Parâmetros dirstring é utilizado para se especificar a direção dos tiques string can pode ser escolhido entre urdl e l é o valor padrão Os valores urdl correspondem respectivamente a para cima para direita para baixo e para esquerda ticsstring um flag definindo como os tiques são fornecidos string pode ser escolhido entre vr e i e v é o valor padrão xy dois vetores que fornecem as posições dos tiques val string matrix uma matriz de strings que quando dada fornece os strings a serem impressos ao longo dos eixos nas posições dos tiques fontsizeint especifica o tamanho de fonte a ser utilizado para se exibir os valores ao longo dos eixos O valor padrão é 1 que corresponde ao tamanho de fonte atual formatnstring formato a ser utilizado para se exibir os números ao longo dos eixos seg 1 ou 0 um flag que controla a exibição do segmento base do eixo o valor padrão é 1 subintinteger um inteiro que fornece o número de subintervalos entre dois tiques maiores textcolorinteger especifica a cor a ser utilizada para a exibição de valores ao longo dos eixos O valor padrão é 1 que corresponde a cor corrente ticscolorinteger especifica a cor a ser utilizada para o desenho dos tiques O valor padrão é 1 que corresponde à cor corrente Descrição drawaxis é utilizado para desenhar um eixo na direção horizontal ou vertical A direção do eixo é dada por dir dir u ou d fornece a direção com os tiques indo para cima u ou para baixo d dir r ou l fornece um eixo vertical com os tiques indo para a direita r ou esquerda l x e y fornecem as posições dos tiques dos eixos Se o eixo é horizontal então y deve ser um escalar ou pode ser omitido e x é um vetor Scilab O significado de x é controlado por tics Se ticsv então x fornece as posições dos tiques ao longo do eixo x Se ticsr então x deve ter tamanho 3 xxminxmaxn e n fornece o número de intervalos drawaxis 606 Se ticsi então x deve ser de tamanho 4 xk1k2an Então xmink110a xmaxk210a e n fornece o número de intervalos Se y for omitido então o eixo será posicionado ao topo da moldura se diru ou ao fundo se dird Por padrão os números são impressos ao longo do eixo Eles são impressos utilizandose um formato padrão que pode ser alterado através de formatn ITambém é possível exibir strings dados e não números isto é feito se val é fornecido O tamanho de val deve corresponder ao número de tiques Exemplos plot2d1101101020 eixo horizontal drawaxisx27y4diruticsv eixo horizontal na parte superior da moldura drawaxisx27diruticsv eixo horizontal na parte inferior da moldura drawaxisx27dirdticsv eixo horizontal dado por um intervalo drawaxisx273y4dirdticsr eixo vertical drawaxisx4y27dirrticsv drawaxisx2y273dirlticsr drawaxisy27dirrticsv drawaxisy27dirlticsv eixo horizontal com strings exibidos nas posições dos tiques drawaxisx27y8diruticsvvalAstring16 eixo vertical com strings exibidos nas posições dos tiques drawaxisx8y27dirrticsvvalBstring16 eixo horizontal dado com um intervalo i drawaxisx2503y9diruticsi drawaxisx9y2503dirrticsisubint5 eixo horizontal de novo drawaxisx27y4diruticsvfontsize10textcolor9ticscolor7seg0subint20 Autor JPhC 607 Name drawlater Torna galhos dos eixos invisíveis drawlater Descrição Esta função pode ser utilizada para não se exibir imediatamente na figura corrente os próximos objetos gráficos a serem criados por uma chamada a funções de altonível tais como funções de esboço ou ajuste de propriedades de objetos existentes A propriedade immediatedrawing da figura cor rente é ajustada para off para se adiar os próximos desenhos Pode ser utilizada especialmente com a função Para reabilitar immediatedrawing para a figura corrente você pode utilizar a função Aviso note que entre chamadas às funções drawlater e drawnow a figura corrente pode ser modifi cada Logo estas funções devem ser usadas com cuidado Exemplos Exemplo 1 uma entidade Axes uma entidade Figure drawlater xfarc2555115064360 xfarc5555115064360 xfrect3832 xfrect2752 xfrect327811 xfrect4478141 xfrect24158 xstring0339A Scilab Car agetcurrentaxes achildren1fontsize4 achildren1fontstyle4 achildren1background5 achildren3background8 achildren4background8 achildren5background17 achildren6background17 achildren7background25 achildren8background25 xclickdrawnow Exemplo 2 duas entidades Axes uma entidade Figure subplot212 agca drawlater o que estará presente nestes eixos será desenhado depois plot2d desenhará estes eixos e seus galhos depois subplot211 aviso mudamos os eixos plot2d1 modo de desenho padrão drawa os eixos são visíveis apenas se você não resdesenhar a janela drawnow tudo está visível drawlater 608 Ver Também get set drawnow graphicsentities Autor Djalel ABDEMOUCHE FLeray 609 Name drawnow Desenha entidades gráficas escondidas drawnow Descrição Considerando a figura corrente esta função pode ser usada para desenhar as entidades gráficas es condidas e todos os seus galhos que podem ter sido adiados por uma chamada anterior à função drawlater A propriedade immediatedrawing da figura corrente é ajustada para on Pode ser usado especialmente com a função drawlater Exemplos fgetcurrentfigure manipulador da figura corrente drawlater subplot221 t110plot2dtt2 subplot222 x017plot2dxcosx2 subplot234 plot2dtcost3 subplot235 plot2dxsin2x5 subplot236 plot2dttan2t drawgca desenhando os eixos correntes e seus galhos drawfchildren3 4 desenhando os eixos especificados e seus galhos drawnow desenhando a figura corrente Ver Também get set drawlater graphicsentities Autores Djalel ABDEMOUCHE FLeray 610 Name editcurv editor interativo de curvas gráficas xyokgc editcurvy xyokgc editcurvxy xyokgc editcurvxyjob xyokgc editcurvxyjobtit xyokgc editcurvxyjobtitgc Parâmetros x vetor de coordenadas x y vetor de coordenadas y job um string formado por um a três dos caracteres axy a adicionar pontos à curva editada x modificar coordenadas x dos pontos das curvas editadas y modificar coordenadas y dos pontos das curvas editadas tit um vetor de três strings que fornecem a legenda da curva gc uma lista de parâmetros de janela de gráficos gclistrectnax rect bordas dos gráficos ver plot2d para detalhes nax parâmetros de graduação ver plot2d para detalhes ok indicador Se ok t retorna com menu ok senão retorna com menu abort lista objetos gráficos criados sob editcurv Descrição editcurv é um editor de curvas gráficas interativo Para adicionar um ponto novo apenas clique na localização desejada o ponto adicionado será conectado à extremidade mais próxima Para mover um ponto clique nele arraste o mouse para a nova posição e clique para ajustar a nova posição Autor Serge Steer 611 Name errbar adiciona barras de erro veriticais a um esboço 2d errbarxyemep Parâmetros xyemep quatro matrizes de mesmo tamanho Descrição errbar adiciona barras de erro verticais a um esboço 2d x e y têm o mesmo significado que em plot2d emij e epij são os intervalos de erro sobre os valores yij yij emijyijepij Entre com o comando errbar para visualizar uma demonstração Exemplos t0012pi ysint cost xt t plot2dxy errbarxy005onesx003onesx Ver Também plot2d Autor JPhC 612 Name eval3d valores de uma função em um grid zeval3dfunxy Parâmetros fun função que aceita vetores como argumentos xy 2 vetores de tamanhos 1n1 e 1n2 valor padrão para y yx z matriz de tamanho n1n2 Descrição Esta função retorna uma matriz zn1n2 zijfunxiyj Se a função fun não aceitar argumentos do tipo vetor use a primitiva feval Exemplos x55yx deffzfxyz xy zeval3dfxy plot3dxyz deffzfxyz xy zfevalxyf plot3dxyz Ver Também feval Autor Steer S 613 Name eval3dp computa facetas 3d de uma superfície parametrizada XfYfZfeval3dpfunp1p2 Parâmetros XfYfZf matrizes de tamanho 4n1m1 Xfi Yfi e Zfi são respectivamente as coordenadas nos eixos x y e z dos 4 pontos da iésima faceta de quatro lados fun uma função do Scilab p1 um vetor de tamanho n p2 um vetor de tamanho m Descrição eval3dp computa uma representação de uma faceta de quatro lados de uma superfície 3d parametrizada definida pela função fun funp1p2 computa as coordenadas nos eixos x y e z dos pontos correspondentes da superfície como xiyizifunp1ip2i Isto é usado para eficiência Exemplos p1linspace02pi10 p2linspace02pi10 deffxyzscpp1p2xp1sinp1cosp2 yp1cosp1cosp2 zp1sinp2 XfYfZfeval3dpscpp1p2 plot3dXfYfZf Ver Também genfac3d plot3d 614 Name event handler functions Protótipo de funções que podem se utilizadas como gerenciadoras de even tos enventhandlerfunctionwinxyibut Parâmetros win número da janela onde o evento ocorreu x coordenada X em píxeis do ponteiro do mouse no momento onde o evento ocorreu y coordenada Y em píxeis do ponteiro do mouse no momento onde o evento ocorreu ibut número correspondente ao tipo de evento Descrição Quando o modo de gerenciador de eventos está habilitado o Scilab chamaráo gerenciador de eventos especificado a cada vez que um evento ocorre na janela gráfica A função de gerenciamento de evento deve concordar com o protótipo acima A cada vez que um evento ocorre a função é chamada e os quatro eventos são ajustados de acordo com o número da janela a posição do mouse e o tipo do evento O parâmetro ibut toma um dos seguintes valores dependendo do tipo do evento ocorrido ibut0 o botão esquerdo foi pressionado ibut1 o botão do meio foi pressionado ibut2 o botão direito foi pressionado ibut3 o botão esquerdo do mouse foi clicado ibut4 o botão do meio do mouse foi clicado ibut5 o botão direito do mouse foi clicado ibut10 o botão esquerdo do mouse foi clicado duas vezes ibut11 o botão do meio do mouse foi clicado duas vezes ibut12 o botão direito do mouse foi clicado duas vezes event handler functions 615 ibut5 o botão esquerdo do mouse foi liberado ibut4 o botão do meio do mouse foi liberado ibut3 o botão direito do mouse foi liberado ibut1 o ponteiro do mouse foi movido ibut 32 uma tecla com código asciiibut foi pressionada ibut 32 uma tecla com código asciiibut foi liberadav ibut 100032 uma tecla com código asciiibut1000 foi pressionada enquanto a tecla CTRL estava sendo pres sionada ibut1000 a janela de gráficos foi fechada Por exemplo digamos que o nome da função de gerenciamento de eventos seja fooHandler para a janela de número 0 Um clique com o botão esquerdo na janela na posição 100150 em píxeis será equivalente a chamar fooHandler 0 100 150 3 Ver figureproperties ou seteventhandler para mais informações sobre como especificar o nome do gerenciador de eventos Exemplos function myeventhandlerwinxyibut if ibut1000 then returnend xyxchangexyi2f xinfomsprintfEvento de código d na posição do mouse é ffibutxy endfunction plot2d fig gcf figeventhandler myeventhandler figeventhandlerenable on agora mova o mouse sobre a janela gráfica pressione e libere as teclas com shift pressionado ou não e com Ctrl pressionado ou não pressione um botão espere um pouco e libere pressione e libere um botão clique duas vezes em um botão figeventhandlerenable off suprimindo o gerenciador de eventos Ver Também figureproperties seteventhandler xgetmouse xclick event handler functions 616 Autor JeanBaptiste Silvy 617 Name fac3d Esboço de uma superfície 3d obsoleta fac3dxyzthetaalphalegflagebox fac3d1xyzthetaalphalegflagebox Descrição Estas funções estão obsoletas e foram substituídas por plot3d e plot3d1 Ver Também plot3d plot3d1 618 Name fchamp campo direcional de uma EDO 2d de primeira ordem fchampftxryrarfactrectstrf fchampftxryroptargs Parâmetros f uma external função ou string ou uma lista descrevendo a EDO Pode ser um nome de função f onde f se supõe ser uma função do tipo yftxy p1pn f retorna um vetor coluna de tamanho 2 y que fornece o valor do campo direcional f no ponto xyxy e no tempo t Também pode ser um objeto do tipo lista listfP1Pn onde f é uma função do tipo yftxyp1pn e Pi fornece o valor do parâmetro pi t o tempo selecionado xryr dois vetores linhas de tamanhos n1 e n2 que definem o grid sobre o qual o campo direcional é computado optargs representa uma seqüência de decarações key1value1key2value2 onde key1 key2 pode ser um dos seguintes arfact rect strf ver abaixo arfactrectstrf argumentos opcionais ver champ Descrição fchamp é utilizado para desenhar o campo direcional de uma EDO 2d de primeira ordem definida pela função externa f Note que se a EDO é autônoma o argumento t não possui utilidade mas deve ser fornecido Entre com o comando fchamp para visualizar uma demonstração Exemplos deffxdot derpoltx xd1 x2 xd2 x1 1 x12x2 xdot xd1 xd2 xf 1011 yf 1011 fchampderpol0xfyf clf fchampderpol0xfyf12222011 Ver Também champ champ1 Autor JPhC 620 Name fcontour curvas de nível sobre uma superfície 3d definida por uma função fcontourxryrfnzthetaalphalegflageboxzlev fcontourxryrfnzoptargs Descrição Esta função está obsoleta Está agora inclusa na função contour Autor JPhC 621 Name fcontour2d curvas de nível de uma superfície definida por uma função em um esboço 2d fcontour2dxryrfnzstylestrflegrectnax fcontour2dxryrfnzoptargs Descrição Esta função está obsoleta Está agora inclusa na função contour2d Autor JPhC 622 Name fec Esboço pseudocolorido triangular de uma função definida por uma malha triangular fecxytrianglesfuncoptargs fecxytrianglesfuncstrflegrectnaxzminmaxcolminmaxcoloutmesh Parâmetros xy dois vetores de tamanho n xiyi fornece as coordenadas do nó i func vetor de tamanho n funci fornece o valor no nó i da função para a qual queremos o esboço pseudocolorido triangles é uma matriz Ntr5 Cada linha de triangles especifica um triângulo da malha trianglej numbernode1node2node3flag node1node2node3 são os números dos nós que constituem o triângulo number é o número do triângulo e flag é um inteiro que não é usado na função fec optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes strf leg rect nax zminmax colminmax colout mesh ver plot2d para os quatro primeiros strflegrectnax ver plot2d zminmax vetor com dois compontenteszmin zmax útil para animações em particular colminmax vetor de dois inteiros positivos colmin colmax colout vetor de dois inteiros undermincol uppermaxcol mesh escalar booleano valor padrão f deve ser verdadeiro se você também quiser exibir a malha Descrição Esta função é boa para se desenhar soluções de elementos finitos triangulares lineares ou simplesmente para se exibir uma função definida sobre uma triangularização A interpolação de cores é feita através de um software de computação e portanto não é tão rápida A função colorbar pode se utilizada para se visualizar a escala de cores ver a seção de exemplos O argumento zminmax fornece os valores de z asosicados às primeira e últimas cores do mapa de cores corrente Mais exatamente se o mapa de cores possue nc cores e se notarmos dz zmaxzmin nc então a parte da triangularização onde zmin i1dz z zmin i dz é preenchida com a cor i Por padrão zmin minfunc e zmax maxfunc Se você quiser uma animação com valores da função que variam no tempo tome para zmin e zmax os valores máximo e mínimo globais ou algo próximo O argumento colout permite que o usuário escolha as cores para as duas regiões extremas func zmin and func zmax undermincol e uppermaxcol podem ser iguais independen temente a fec 623 1 neste caso a mesma cor que a zona de vizinhança é utilizada CUIDADO você não vê que o limite correspondente é cruzado este é o caso padrão 0 neste caso a região de extremidade não é pintanda k k sendo um índice de cor válido no mapa de cores corrente a região de extremidade é pintada com a cor k Se você não quiser usar o mapa de cores completo você pode utilizar o argumento 1 colmin colmax nc nc sendo o número de cores do mapa de cores corrente para utilizar apenas a sub parte colmincolmax do mapa de cores por padrão todas as cores do mapa de cores são utilizadas Ver arquivos de demonstração demosfec fecex1 é um simples arquivo de exemplo no qual uma malha e uma função sobre esta malha é completamente construída em sintaxe do Scilab fecex2 é um exemplo no qual a malha e os valores da função foram computados por um construtor de malhas externo malha do tipo amdba e um programa externo Um conjunto de macros fornecido pelo arquivo macrossci pode ser utilizado para ler os arquivos de dados no Scilab e esboçar os resultados Exemplos definindo uma minitriangularização 4 vértices 2 triângulos x 0 1 0 1 y 0 0 1 1 T 1 1 2 3 1 2 3 4 1 1 z 0 1 0 1 valores da função em cada vértice xbasc xsetcolormapjetcolormap64 subplot121 colorbar11 fecxyTzstrf040mesht xtitleexemplo de fec com a malha subplot122 colorbar11 fecxyTzstrf040 rmq meshf por padrão xtitleexemplo de fec em a malha xselect este exemplo mostra o efeito de zminmax e usa os dados de exemplos anteriores você tem que executálos primeiro xbasc xsetcolormapjetcolormap64 colorbar0505 cuidado a barra de cores deve ser ajustada na mão fecxyTzstrf040 zminmax05 05 mesht xtitleexemplo de fec utilizando o argumento zminmax xselect este exemplo mostra os efeitos de zminmax e colout Utiliza também os dados de exemplos anteriores você tem que executálos primeiro xbasc xsetcolormapjetcolormap64 fec 624 subplot221 colorbar0505 fecxyTzstrf040 zminmax05 05 colout0 0 mesht xtitleexemplo de fec utilizando zminmax e colout 0 0 subplot222 colorbar0505 fecxyTzstrf040 zminmax05 05 colout32 32 mesht xtitleexemplo de fec utilizando zminmax e colout 32 32 subplot223 colorbar0505 fecxyTzstrf040 zminmax05 05 colout1 0 mesht xtitleexemplo de fec utilizando zminmax e colout 1 0 subplot224 colorbar0505 fecxyTzstrf040 zminmax05 05 colout0 1 mesht xtitleexemplo de fec utilizando zminmax e colout 0 1 xselect este exemplo mostra um recurso de colminmax utilizando dois mapas de cores para dois subesboços Também utiliza dados de exemplos anteriores xbasc xsetcolormaphotcolormap64jetcolormap64 subplot121 colorbar111 64 fecxyTzstrf040 colminmax1 64 mesht xtitlefec utilizando mapa de cores hot subplot122 colorbar1165 128 fecxyTzstrf040 colminmax65 128 mesht xtitlefec utilizando mapa de cores jet xselect Ver Também colorbar Sfgrayplot Sgrayplot 625 Name fecproperties Descrição das propriedades da entidade Fec Descrição A entidade Fec é uma folha na hierarquia de entidade gráficas Representa um esboço 2d de elementos finitos ver fec Sgrayplot parent esta propriedade contém o manipulador para a raiz A raiz da entidade Fec deve ser do tipo Ax es ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores Fec correntemente não possuem galhos visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o esboço é visível a propriedade é on Se off o esboço não é exibido na tela data uma matriz de três colunas xyf onde xi e yi são as coordenadas do iésimo nó fi é o valor associado ao nó i triangles uma matriz de cinco colunas tnn1n2n3flag tnj é o número do triângulo n1j n2j e n3j são índices dos nós que constituem o triângulo flagj não é us ado zbounds este vetor de tamanho 2 zminzmax fornece os valores z associados às primeira e última cores do mapa de cores corrente Mais exatamente se o mapa de cores possui nc cores e se notarmos dz zmaxzminnc então a parte da triângularização onde zmin i1dz z zmin i dz é preenchida com a cor i Por padrão o valor da propriedade zbounds é 00 Neste caso zmin e zmax são automaticamente ajustados para os valores mínimo e máximo do argumento func outsidecolor este vetor de tamanho 2 cmin cmax define a cor utilizada quando os valores dos nós estão fora do intervalo zbounds zminzmax Quando os valores dos nós são menores do que zmin a cor com índice cmin é utilizada Quando os valores dos nós são menores do que zmax a cor com índice cmax é utilizada Por padrão o valor da propriedade outsidecolor é 00 Neste caso cmin e cmax são automaticamente ajustados para os limites do mapa de cores Se cmin ou cmax são negativos então os valores fora do intervalo zbounds não são exibidos eles aparecem transparentes colorrange este vetor de tamanho 2 rmin rmax permite utilizar apenas uma parte do mapa de cores para a exibição rmin e rmax são os índices do mapa de cores Se ambos forem maiores do que 1 então o mapa de cores utilizados para exibir a entidade fec é colormaprminrmax onde colormap é o mapa de cores da figura raiz Por padrão O valor da propriedade colorrange é 00 Neste caso todo o mapa de cores é utilizado linemode Se on o wireframe esqueleto encerrando os triângulos é desenhado Se off apenas os triângulos de dentro são desenhados foreground este índice de cor especifica a cor da malha Se a propriedade linemode for on o wireframe é desenhado utilizandose esta cor fecproperties 626 clipstate este campo contém o valor da propriedade clipstate para o fec o valor de clipstate pode ser off significa que o fec não é recortado clipgrf significa que o fec é recortado fora da caixa dos eixos on significa que o fec é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquer do largura altura define as porções do retângulo a ser exibido contudo o valor da propriedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade Fec e recuperála Exemplos x1010 y1010m rand2121 Sgrayplotxym agetcurrentaxes fachildrenchildren1 fdata31sizefdata1 aparentcolormaphotcolormap64 Ver Também set get delete fec Sgrayplot graphicsentities Autor Djalel ABDEMOUCHE 627 Name fgrayplot esboço 2d de uma superfície definida por uma função utilizando cores fgrayplotxyfstrfrectnax fgrayplotxyfoptargs Parâmetros xy vetor linha de reais f função externa do tipo yfxy optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 pode ser um dos seguintes rect nax strf ou axesflag e frameflag ver plot2d strfrectnax ver plot2d Descrição fgrayplot realiza um esboço 2d de uma superfície dada por zfxy em um grid definido por x e y Cada retângulo no grid é preenchido com um nível de cinza ou de cor dependendo do valor médio de z nas quinas do retângulo Entre com o comando fgrayplot para visualizar uma demonstração Exemplos t1011 deffzmysurfacexyzx2y2 fgrayplotttmysurfacerect2222 Ver Também grayplot plot2d Sgrayplot Sfgrayplot Autor JPhC 628 Name figureproperties Descrição das propriedades da entidade gráfica Figure figura Descrição A figura é o topo da hierarquia de entidades gráficas Esta entidade contém um número de propriedades designadas a controlar muitos aspectos da exibição de objetos gráficos do Scilab Estas propriedades estão dividas em duas categorias Propriedades que contém informação sobre a própria figura e outras relacionadas a valores padrões para criação de galhos Figure properties children estes manipuladores representam o vetor dos galhos da figura Note que todos os galhos de figuras são do tipo Axes Também tenha em mente que ao se criar uma entidade figura utilizando o comando scf uma entidade Axes de eixos é simultaneamente criada figurestyle o valor deste campo determina o estilo da figura Desde o Scilab 50 o modo gráfico antigo foi desabilitado Esta propriedade é mantida por compatibilidade mas não pode ser alterada figureposition este campo contém a posição em pixel da janela de gráficos na tela É um vetor xy definindo a posição do canto superior esquerdo da janela A posição 00 é o canto superior esquerdo da tela A posição inicial de uma janela de gráficos é tomada a partir da entidade figura padrão ver gdf A única excessão é quando o valor figureposition da figura padrão é 11 Neste caso A posição inicial da janela de gráficos é ajustada automaticamente pelo sistema de janelamento figuresize esta propriedade controla o tamanho em pixel da janela de gráficos da tela O tamanho é o vetor widthheight axessize usado para especificar o tamanho da janela de gráficos virtual O tamanho é o vetor widthheight A janela de gráficos virtual deveria ser maior que a parte realmente visível na tela Esta propriedade não poderia ser alterada se a figura está aportada com outros elementos autoresize esta propriedade determina se a janela de gráficos é redimensionada Se o valor é on então a propriedade axessize é igualada a figuresize e os galhos eixos são ampliados de modo correspondente Se o valor é off axessize não pode ser redimensionado quando figuresize é modificado viewport posição da parte visível do gráfico na janela figurename este campo contém o nome da figura O nome é um string exibido no topo da janela de gráficos Pode conter um único substring d que será substituido por figureid Em nen hum outro caso o caractere é permitido dentro do nome figureid este campo contém o identificador da figura É um número inteiro que é ajustado na criação da figura e não pode ser mudado depois figureproperties 629 infomessage este string ajusta o texto que será exibido na barra de informações da janela colormap propriedade que define o mapa de cores utilizado pela figura O mapa de cores é uma matriz m por 3 m é o número de cores O número da cor i é dado pela tripla 3uple R G B corre spondentes respectivamente às intensidades de vermelho verde e azul entre 0 e 1 pixmap esta propriedade controla o status de pixmap de uma janela de gráficos Se o valor é off os gráficos são diretamente exibidos na tela Se é on os gráficos são feitos em um pixmap e são enviados à janela através do comando showpixmap pixeldrawingmode este campo define a operação bit a bit usada para desenhar o pixel na tela O modo padrão é copy que significa dizer que o pixel é desenhado como requerido De modo mais geral a operação bit a bit é realizada entre a cor do pixel fonte e a cor do pixel já presente na tela As operações são clear and andReverse copy andInverted noop xor or nor equiv invert orReverse copy Inverted orInverted nand set immediatedrawing esta propriedade controla a exibição da figura Pode ser on modo padrão ou off É utilizada par atrasar uma grande sucessão de comandos gráficos implicando vários esboços ou reesboços Note que ao se utilizar os comandos drawlater ou drawnow É utilizada par atrasar uma grande sucessão de comandos gráficos implicando vários esboços ou re esboços Note que ao se utilizar os comandos off ou on background esta propriedade controla a cor de plano de fundo da figura O valor é um índice de cor correspondente ao mapa de cores corrente eventhandler um string O nome da função do Scilab que deverá manipular os eventos Note que definir um string vazio desabilitará o manipulador de eventos Para mais informações sobre o ma nipulador de eventos veja a ajuda event handler functions eventhandlerenable habilita ou desabilita o manipulador de eventos Seu valor deve ser on ou off userdata este campo pode ser utilizado para se armazenar qualquer variável Scilab na estrutura de dados da entidade figura e recuperála tag este campo pode ser utilizado para armazenar um string geralmente utilizado para identificar o controle Ele permite fornecer um nome Principalmente utilizado em conjunção a find obj Valores padrões para galhos visible este campo determina se o conteúdo da figura deve ser redesenhado O valor pode ser on ou off rotationstyle este campo está relacionado ao botão 3D Rot Toma unary como valor padrão para rotacionar apenas o esboço 3d selecionado Em outros casos o valor pode ser multiple todos os esboços 3d são rotacionados figureproperties 630 Nota sobre valores padrões todas estas propriedades e campos listados herdam valores de valores padrões armazenados num modelo de figura Estes valores padrões podem ser vistos e salvos Para fazêlo use o comando getdefaultfigure ele retorna o manipulador gráfico de uma figura Note que nen huma janela de gráficos é criada por este comando As próximas figuras criadas herdarão valores deste modelo ver o exemplo 2 abaixo Exemplos lines0 desabilitando paginamento vertical Exemplo 1 fgetcurrentfigure obtendo o manipulador da figura corrente se nenhum existir cria uma figura e retorna o manipulador correspondente ffigureposition ffiguresize200200 fbackground2 fchildren podese ver que uma entidade Axes já existe deletef fgcf atalho de macro ltgt fgetcurrentfigure fpixmap on ajusta o status de pixmap para on plot2d nada acontece na tela showpixmap exibe o pixmap na tela Exemplo 2 configurações de defaultfigure dfgetdefaultfigure obtendo os valores padrões o atalho é gdf vamos mudar os padrões dfcolormaphotcolormap128 dfbackground 110 ajustando o plano de fundo para um tipo de amarelo note que estamos utilizando um índice de cor dentro do mapa de cores colormap redefinido previamente scf122 criando uma nova figura de número122 com o novo padrão plot2d scf214 tpi03pi plot3dttsintcost3545XYZ1524 Ver Também lines set get scf gcf gdf gca gda axesproperties showpixmap clearpixmap hotcolormap event handler functions Autor Djalel ABDEMOUCHE 631 Name fplot2d esboço 2d de uma curva definida por uma função fplot2dxrfstylestrflegrectnax fplot2dxrfoptargs Parâmetros xr vetor f função externa do tipo yfx ie uma função scilab ou rotina dinamicamente linkada ligada referida como um string stylestrflegrectnax ver plot2d optargs ver plot2d Descrição fplot2d esboça uma curva definida pela função externa f A curva é aproximada por uma interpolação linear seccional utilizando os pontos xrifxri Os valores de fx são obti dos por fevalxrf Entre com o comando fplot2d para visualizar uma demonstração Exemplos deffyfxysinxcosx x00110pi10 fplot2dxf clf fplot2d110parab Ver Também plot2d feval paramfplot2d Autor JPhC 632 Name fplot3d esboço 3d de uma superfície definida por uma função fplot3dxryrfthetaalphalegflagebox fplot3dxryrfoptargs Parâmetros xr vetor linha de tamanho n1 yr vetor linha de tamanho n2 f external do tipo zfxy thetaalphalegflagebox ver plot3d optargs ver plot3d Descrição fplot3d esboça uma superfície definida pela função externa f no grid definido por xr e yr Entre com o comando fplot3d para ver uma demonstração Exemplos deffzfxyzx4y4 x3023 yx clf fplot3dxyfalpha5theta31 Ver Também plot3d Autor JPhC 633 Name fplot3d1 Esboço 3d em escala de cinza ou colorido de nível de uma superfície definida por uma função fplot3d1xryrfthetaalphalegflagebox fplot3d1xryrfoptargs Parâmetros xr vetor linha de tamanho n1 yr vetor linha de tamanho n2 f função externa external do tipo zfxy thetaalphalegflagebox ver plot3d1 optargs ver plot3d Descrição fplot3d1 esboça em 3d em escala de cinza ou colorido níveis de uma superfície definida pela função externa f no grid definido por xr e yr Entre com o comando fplot3d1 para visualizar uma demonstração Exemplos deffzfxyzx4y4 x3023 yx clf fplot3d1xyfalpha5theta31 Ver Também plot3d1 Autor JPhC 634 Name gca Retorna o manipulador da entidade Axes corrente a gca Parâmetros a manipulador o manipulador da entidade Axes corrente Descrição Esta rotina retorna o manipulador da entidade Axes da figura corrente Exmplos subplot211 agca obtendo os eixos correntes aboxoff tpi03piplot3dttsintcost8050XYZ524 subplot212 plot2d esboço simples agca obtendo os eixos correntes aboxoff axlocationmiddle aparentbackground4 deletegca deletando os eixos correntes xdel0 deletando uma janela de gráficos Ver Também gda gcf gce get graphicsentities Autor Djalel ABDEMOUCHE 635 Name gce Retorna o manipulador da entidade corrente e gce Parâmetros e manipulador da entidade corrente Descrição Esta rotina retorna o manipulador da última e ainda existente entidade criada Exemplos agca obtendo o manipulador dos novos eixos criados adatabounds111010 aaxesvisible on for i15 xfrect7i9i33 egce ebackgroundi end delete deletando a entidade corrente deletegce deletando a entidade corrente deletegcf deletando a figura corrente Ver Também gcf gca get graphicsentities Autor Djalel ABDEMOUCHE 636 Name gcf Retorna o manipulador da janela GUI ou de gráficos corrente h gcf Parâmetros h manipulador Descrição Esta função retorna o manipulador da janela gráfica corrente Exemplos fgcf criando uma figura ffiguresize 6104692 ffigurename Foo ffigure criando uma figura huicontrolfstylelistboxposition 10 10 150 160 criando um listbox seth string item 1item 2item3 preenchendo a lista seth value 1 3 selecionando os itens 1 e 3 na lista gcf scf0 tornando a janela de gráficos 0 a figura corrente gcf obtendo o manipulador gráfico da figura corrente figuref tornando a janela GUI f a figura corrente gcf retorna o manipulador gráfico da figura corrente Ver Também gdf gca gce get scf set graphicsentities uicontrol Autor Serge Steer INRIA 637 Name gda Retorna o manipulador dos eixos padrões a gda a getdefaultaxes Parâmetros a o manipulador dos eixos padrões Descrição Os eixos padrões são uma entidade gráfica entidade Axes que nunca é desenhada Ela usada como referência para os valores de propriedades padrões dos eixos Estes valores de propriedades padrões são usados para inicializar novos eixos dentro de figuras A função gda retorna o manipulador dos eixos padrões O usuário pode utilizar este manipulador para ajustar ou obter os valores padrões de propriedades dos eixos Note que uma entidade gráfica padrão equivalente também existe para entidades Figure ver gdf Exemplos agda obtendo o manipulador dos eixos modelos ajustando suas propriedades aboxoff aforeground2 alabelsfontsize3 alabelsfontcolor5 asubtics5 5 3 axlocationtop os eixos modelos são agora usados subplot211 criando uma nova entidade Axes plot2d veja outros modelos de propriedades abackgroundcolorgray agrid5 5 5 subplot212 t0015pi plot2dsintcost setadefaultvalues1 retornando para os valores padrões do modelo ver a função sda clf plot2dsintcost Ver Também gdf sda sdf clf gca get graphicsentities Autor 639 Name gdf Retorna o manipulador da figura corrente f gdf f getdefaultfigure Parâmetros f manipulador da figura corrente Descrição A figura padrão é uma entidade gráfica entidade Figure que nunca é desenhada É usada como referência para os valores padrões das propriedades da figura Estes valores padrões são utilizados para iniciar novas figuras A função gdf retorna o manipulador da figura corrente O usuário pode utilizar este manipulador para ajustar ou obter os valores padrões das propriedades da figura Note que uma entidade gráfica padrão equivalente também existe para entidades Axes de eixos ver gda Exemplos fgdf obtendo o manipulador da figura modelo ajustando suas propriedades fbackground7 ffigurenameFunction gdf ffigureposition1 100 fautoresizeoff ffiguresize300 461 faxessize600 400 plot2d criando uma figura scf1 plot3d criando uma segunda figura setfdefaultvalues1 retornando para os valores padrões do modelo da figura ver a função sdf scf2 plot2d Ver Também gda sdf sda gcf get scf set graphicsentities Autor Djalel ABDEMOUCHE 640 Name ged Editor Gráfico do Scilab gedaction fignum Parâmetros action Real ação a ser executada na janela gráfica dada por fignum 1 Ajusta a janela fignum como sendo a corrente 2 Redesenha a janela fignum 3 Limpa a janela fignum 4 Pede que o usuário selecione uma entidade gráfica para efetuar cópia 5 Cola a última entidade gráfica copiada pela ação 4 6 Pede ao usuário para que selecione uma entidade gráfica e então a mova 7 Pede ao usuário que selecione uma entidade gráfica para efetuar deleção 8 Inicia uma GUI para se editar propriedades da janela 9 Inicia uma GUI para se editar propriedade dos eixos correntes 10 Inicia um selecionador para selecionar um objeto e editálo através da GUI do Editor Gráfico 11 Para o selecionador de entidades fignum Real número da janela de gráficos a figura a ser editada Descrição ged inicia um Editor Gráfico do Scilab sobre a figura de número fignum e executa a ação fornecida por action Autor VC 641 Name genfac3d computa facetas de uma superfície 3d xxyyzzgenfac3dxyzmask Parâmetros xxyyzz matrizes de tamanho 4n1xm1 xxi yyi e zzi são respectivamente as coordenadas nos eixos x y e z dos 4 pontos da iésima faceta de quatro lados x vetor de coordenadas no eixo y de tamanho n y vetor de coordenadas no eixo y de tamanho n z matriz de tamanho mn zij é o valor da superfície no ponto xiyj mask matriz de valores booleanos opcional de mesmo tamanho que z utilizada para selecionar entradas de z a serem representadas por facetas Descrição genfac3d computa uma faceta de quatro lados de uma superfície 3d zfxy definida por x y e z Exemplos t0032pi zsintcost xxyyzzgenfac3dttz plot3dxxyyzz Ver Também eval3dp plot3d 642 Name geom3d projeção 3d para 2d após um esboço 3d xygeom3dx1y1z1 Parâmetros x1y1z1 vetores reais de mesmo tamanho pontos em 3d xy vetores reais de mesmos tamanhos que x1 y1 e z1 Descrição Após o uso de uma função de esboço 3d como plot3d plot3d1 ou param3d geom3d gives the mapping between a point in 3D space x1iy1iz1i e o ponto correspondente xiyi no plano 2d projetado Então todas as primitivas de gráficos 2d que funcionam em xy podem ser usadas para superposição no esboço 3d Exemplos deffzsurfacexyzsinxcosy tpi101010 esboço 3d da superfície fplot3dttsurface3545XYZ agora ttsintcost é uma curva na superfície que pode ser desenhada utilizandose geom3d e xpoly xygeom3dpi20surfacepi20 Autor JPhC 643 Name get Recupera um valor de propriedade de uma entidade de gráficos ou um objeto Interface do Usuário hgetprop valgethprop valhprop Parâmetros h manipulador da entidade da qual se deseja recuperar uma propriedade h pode ser um vetor de manipuladores e neste caso get retorna os valores da propriedade definidos para todos os objetos identificados por h h também pode ser 0 para se retornar as propriedades do objeto raiz prop string com o nome da propriedade val objeto Scilab o valor da propriedade Descrição Esta rotina pode ser utilizada para se recuperar o valor de uma propriedade especificada de uma en tidade de gráficos ou objeto GUI Neste caso é equivalente a se usar o operador ponto em um manipulador Por exemplo gethbackground é equivalente a hbackground Nomes de propriedades são strings Para obter a lista de todas as propriedade existentes ver graphicsentities ou uicontrol para objetos de Interface do Usuário get também pode ser chamado com apenas uma propriedade como argumento Neste caso a pro priedade deve ser uma das seguintes currententity or hdl retorna o manipulador da última e ainda existente entidade criada getcurrententity e gethdl equivalem a gce currentfigure retorna o manipulador da figura Figure corrente getcurrentfigure equivale a gcf currentaxes retorna o manipulador da entidade de eixos Axes corrente getcurrentaxes equivale a gca defaultfigure retorna o manipulador da figura padrão getdefaultfigure equivale a gdf defaultaxes retorna o manipulador dos eixos padrões getdefaultaxesequivale a gda figuresid retorna um vetor contendo os ids de todas as figuras gráficas abertas getfiguresid equivale a winsid Exemplos get 644 para entidades gráficas clf objetos gráficos simples subplot121 x2012pi plot2dx2x2 subplot122 xrect2752 xrect3832 xfarc2555115064360 xfarc5555115064360 xstring029Exemplo ltltUM CARROgtgt hgetcurrententity obtendo o novo objeto criado hfontsize3 fgetcurrentfigure obtendo a figura corrente ffiguresize ffiguresize700 500 fchildren fchildren2type fchildren2children fchildren2childrenchildrenthickness4 agetcurrentaxes obtendo os eixos correntes achildrentype achildrenforeground obtendo a cor de primeiro plano de um conjunto de objetos gráficos achildrenforeground9 para objetos de Interface do Usuário huicontrolstring Button Abrindo uma janela com um botão pgethposition obtendo o aspecto geométrico do botão dispLargura do botão stringp3 imprimindo a largura do botão close fechando a figura Ver Também uicontrol rootproperties graphicsentities set Autor Djalel ABDEMOUCHE 645 Name getfigurehandle Retorna o manipulador de uma figura a partir de seu id f getfigurehandlefigureid Parâmetros figureid inteiro o id da figura a ser recuperada f o manipulador da figura correspondente Descrição getfigurehandle permite recuperar o manipulador de uma figura gráfica desde que se conheça o seu identificador Se uma figura com o id especificado existir ela é retornada Em caso contrário uma matriz vazia é retornada Exemplos criando algumas figuras scf0 scf5 scf12 obtendo o manipulador da figura com id 5 f5 getfigurehandle5 a figura corrente ainda é aquela com id 12 gcf obtendo uma figura inexistente f42 getfigurehandle42 Ver Também set get gcf scf graphicsentities Autor JeanBaptiste Silvy INRIA 646 Name getcolor abre um diálogo que exibe as cores no mapa de cores corrente cgetcolortitlecini cgetcolor Parâmetros title string o título do diálogo cini identificador da cor selecionada inicial O valor padrão é 1 c identificador da cor selecionada ou se o usuário tiver clicado no botão Cancel cancelar Descrição getcolor abre uma janela que exibe o palete do mapa de cores corrente O usuário pode clicar numa cor para exibir seu identificador e valores RGB getcolor retorna o identificador da cor selecionada ou se o usuário clicar no botão Cancel Ver Também color colormap getmark getfont 647 Name getfont Diálogo para selecionar fonte da letra Função obsoleta fIdfSizegetfont fIdfSizegetfontstr fntgetfont fntgetfontstr fntgetfontSstrfontfIdfSize Parâmetros str caractere por exemplo a fId inteiro o número da fonte selecionada fSize inteiro o tamanho da fonte selecionada fnt vetor fIdfSize Descrição Esta função que foi projetada para trabalhar com a função xset também está obsoleta Utilize o editor de propriedade ged ao invés getfont abre uma janela gráfica para seleção de uma fonte O usuário deve escolher uma fonte e um tamanho clicando no caractere exibido correspondente Apertar uma tecla faz com que o caractere exibido mude Exemplos fIdfSizegetfont xsetfontfIdfSize plot2d00rect0 0 10 10axesflag0 xstring55string Ver Também ged textproperties 648 Name getlinestyle Diálogo para seleção de estilo de linha Função obsoleta kgetlinestyle Parâmetros k inteiro o estilo de linha selecionado ou se o botão Cancel cancelar for clicado Descrição Esta função que foi projetada para trabalhar com a função xset também está obsoleta Utilize o editor de propriedades ged getlinestyle abre uma janela de gráfico para selecionar um estilo de linha Exemplos x00110 plot2dxsinx egce armazenando o Compound contendo o esboço echildren1linestyle getlinestyle Ver Também ged set segsproperties segsproperties 649 Name getmark Diálogo para selecionar marcas símbolos Função obsoleta markmrkSizegetmark Parâmetros mark inteiro o número da marca selecionada mrkSize inteiro o tamanho da marca selecionada Descrição Esta função que foi projetada para funcionar com a função xset também está obsoleta Utilize o editor de propriedades ged ao invés getmark abre uma janela de gráficos para selecionar uma marca símbolo Exemplos x00110 markmrkSizegetmark plot2dxsinxstylemark clf plot2dxsinx egce armazenando o Compound contendo o esboço markmrkSizegetmark echildren1markstyle mark Ver Também ged set segsproperties segsproperties 650 Name getsymbol diálogo para a seleção de um símbolo e seu tamanho Função obsoleta cgetsymboltitle Parâmetros title string título do diálogo c vetor de tamanho 2 nsz Descrição Esta função que foi projetada para trabalhar com a função xset também está obsoleta Utilize o editor de propriedades ged ao invés getsymbol abre uma caixa de diálogo de escolha com título title se fornecido onde o usuário pode selecionar um símbolo e seu tamanho getsymbol retorna o identificador do símbolo n e o identificador de seu tamanho sz Ver Também ged set segsproperties segsproperties 651 Name glue Cola um conjunto de entidades gráficas em um Compound composto glueH hagregglueH Parâmetros H um vetor de manipuladores hagreg manipulador da entidade Compound Descrição Dado um vetor de manipuladores esta função cola as entidades correspondentes em um único Com pound e retorna o manipulador desta nova entidade Exemplos Ver Também get set move unglue graphicsentities Autor Djalel ABDEMOUCHE 652 Name graduate graduação de eixos xixanpgraduate xmi xman1n2 xixanpgraduate xmi xma Parâmetros xmixma escalares reais n1 n2 inteiros com valores padrões 310 xi xa escalares reais np inteiro Descrição graduate procura pelo intervalo mínimo xixa e um número de tiques np tais que xi xmi xma xa xa xi np k10nk em 1 3 5 para um inteiro n n1 np n2 Exemplos y003314578 xbascplot2d1enn0y ymnymxnpgraduateminiymaxiy rect1ymnprodsizeyymx xbascplot2d1enn0y1011 rect10310np Ver Também xsetech plot2d Autor S Steer 1992 653 Name graphicsentities Descrição das estruturas de dados de entidades gráficas Descrição No Scilab uma janela de gráficos e os desenhos contidos nela são representados por entidades hierárquicas O topo do nível hierárquico é a Figure figura cada Figure define pelo menos um galho do tipo Axes eixos Cada entidade Axes contém um conjunto de folhas que são objetos gráficos básicos como Polylines Rectangles Arcs Segs poligonais retângulos arcos e segmen tos Também pode ser do tipo Compound composto que são conjuntos recursivos de entidades O interesse principal no novo modo de gráficos é facilitar a mudança de propriedades O novo modo de gráficos fornece um conjunto de rotinas gráficas de altonível ver set get utilizadas para controlar propriedades dos objetos como dados cores coordenadas e escalas cores e aparências sem que seja necessário entrar novamente os comandos de gráficos iniciais Entidades gráficas do Scilab estão associadas a variáveis do tipo handle manipuladores O ma nipulador é um identificador único que é associado a cada instância de uma entidade gráfica criada Utilizandose manipuladores é possível tanger propriedades de entidades através das rotinas set e get Os manipuladores também são utilizados para manipular objetos gráficos para movêlos para fazer cópias ou deletálos Figure a entidade figura é o topo da hierarquia de entidades gráficas Esta entidade define os parâmetros para a figura em si tanto quanto os valores padrões dos parâmetros para criação de galhos Os galhos das figuras são as entidades de eixos O manipulador da figura corrente a figura para onde os desenhos foram enviados pode ser obtido utilizandose getcurrentfigure e pode ser ajustado utilizandose setcurrentfigureh onde h pode ser tanto um manipulador da figura ou um iden ficador da figura figureid neste último caso se não existir um é automaticamente criado Veja figureproperties para detalhes Axes a entidade de eixos está no segundo nível da hierarquia de entidades gráficas Esta entidade define parâmetros para a mudança de coordenadas dos eixos e o desenho dos eixos tanto quanto os parâmetros padrões para criação de seus galhos Ver axesproperties for details para detalhes O manipulador dos eixos correntes pode ser obtido utilizandose getcurrentaxes Compound a entidade composta é simplesmente um vetor de galhos com uma única propriedade propriedade de visibilidade É usada para colar um conjunto de entidades Ver as documentações glue unglue e Compoundproperties Axis a entidade eixo é uma folha da hierarquia de entidades gráficas Esta entidade define os parâmetros de escala de um eixo e aparência Ver axisproperties para detalhes Polyline a entidade poligonal é uma folha na hierarquia de entidades gráficas define propriedades de de senho de poligonais e extensões poligonais 2d e 3d Ver polylineproperties para detalhes Arc a entidade arco é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para elipses e partes de elipses graphicsentities 654 Ver arcproperties para detalhes Rectangle a entidade retângulo é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para retângulos e retângulos preenchidos Ver rectangleproperties para detalhes Surface a entidade superfície é uma folha na hierarquia de entidades gráficas possui subtipos Fac3d ou Plot3d Esta entidade define parâmetros para esboço de superfícies 3d Ver surfaceproperties para detalhes Fec a entidade Fec é uma folha na hierarquia de entidades gráficas Representa esboços de elementos 2d finitos Ver fecproperties para detalhes Grayplot a entidade Grayplot é uma folha na hierarquia de entidades gráficas Representa esboços 2d de superfícies utilizando cores e imagens Ver grayplotproperties para detalhes Matplot a entidade Matplot é uma folha na hierarquia de entidades gráficas Representa esboços 2d uti lizando matrizes de inteiros Ver Matplotproperties para detalhes Segs a entidade de segmentos é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros um conjunto de flechas ou segmentos coloridos Ver segsproperties para detalhes Champ a entidade Champ é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para esboços 2d de campos vetoriais Ver champproperties para detalhes Text a entidade texto é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para impressão de strings Ver textproperties para detalhes Label a entidade rótulo é um galho da entidade gráfica Axes de eixos Esta entidade define parâmetros para os rótulos dos 3 eixos x y e z desenhados em uma janela de gráficos Ver labelproperties para detalhes Legend a legenda é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para legendas desenhadas impressas sob gráficos plot2dx Esta entidade requer futuros desenvolvi mentos Ver legendproperties para detalhes graphicsentities 655 Exemplos execute este exemplo linha por linha scf criando figura no modo de entidade obtendo o manipulador da entidade Figure e exibindo suas propriedades fgetcurrentfigure afchildren o manipulador da galho Axes x110 plot2dxx2 x15 eachildren Compound de duas poligonais p1echildren1 as propriedades das últimas poligonais desenhadas p1foreground5 mudando a cor da poligonal echildrenthickness5 mudando a espessura das poligonais deleteechildren2 moveechildren030 transladando a poligonal aaxesbounds0 0 05 05 subplot222 criando uma nova entidade Axes plot110 a1fchildren1 obtendo seu manipulador copyechildrena1 copiando a poligonal do primeiro esboço nos novos eixos a1databounds1 010 100 mudando os limites dos eixos setcurrentfigure10 criando uma nova figura com figureid10 plot3d os desenhos são enviados à nova figura com figureid10 setcurrentfiguref torna a figura anterior a corrente plot2dxx3 os desenhos são enviados à figura inicial Ver Também set get move draw delete objecteditor plot surf 656 Name graphicsfonts Descrição de fontes utilizadas em figuras gráficas Descrição Algumas entidades gráficas como Text Axes Label ou Legend exibem um ou mais strings em suas figuras gráficas A aparência dos strings exibidos pode ser modificada especificando diferentes fontes e tamanhos de caracteres Mudando a fonte Fontes utilizadas em figuras gráficas são selecionadas de um conjunto de fontes chamado fontes carregadas Em outras palavras as fontes carregadas são aquelas correntemente disponíveis em figuras gráficas Uma lista destas fontes pode ser obtida utilizandose a função xlfont sem ar gumento Por padrão o Scilab possui um conjunto de 11 fontes carregadas Este conjunto pode ser modificado e estendido utilizandose a função xlfont com um nome de fonte como argumento A fonte carregada pode ser de um arquivo ou mesmo uma uma do sistema Para conhecer a lista de fontes disponíveis no sistema utilize o comando xlfontAVAILABLEFONTS Para mais informações sobre como manipular fontes veja xlfont Aqui está a lista das 11 fontes padrões Número da fonte Família de Fontes Negrito Itálico 0 Monospaced Não Não 1 ScilabSymbols Não Não 2 Serif Não Não 3 Serif Não Sim 4 Serif Sim Não 5 Serif Sim Sim 6 SansSerif Não Não 7 SansSerif Não Sim 8 SansSerif Sim Não 9 SansSerif Sim Sim 10 SansSerif Sim Sim A fonte utilizada por uma entidade gráfica pode ser alterada através da propriedade fontstyle Esta é um inteiro positivo fazendo referência a uma das fontes Seu valor deve estar entre 0 fazendo referência à primeira fonte e o número de fontes carregadas menos um fazendo referência à última fonte A propriedade fractionalfont controla o antiserrilhamento da fonte Seu valor pode ser on ou off Se for ona fonte é suavizada em caso contrário ela não é Mudando o tamanho dos caracteres O tamanho do texto de uma entidade gráfica é modificado através da propriedade fontsize É um escalar especificando o tamanho dos caracteres exibidos O tamanho do caractere do Scilab é diferente do tamanho do caractere Java Aqui está uma equivalência entre as duas escalas Tamanho Scilab Tamanho Java 0 8 graphicsfonts 657 1 10 2 12 3 14 4 18 5 24 6 30 7 36 8 42 9 48 10 54 O tamanho do caractere pode não ser um inteiro Neste caso o resultado depende da propriedade fractionalfont da entidade Se a propriedade fractionalfont for on então o tamanho da fonte é interpolado entre os dois inteiros mais próximos Por exemplo um tamanho de fonte 25 exibe caracteres com tamanho Java 13 Se a propriedade fractionalfont for off então a fonte exibida é truncada para a sua parte inteira Por exemplo um tamanho de fonte 25 exibe caracteres Java de tamanho 12 Ver Também xlfont graphicsentities 658 Name graycolormap mapa de cores linear cinza cmapgraycolormapn Parâmetros n inteiro 1 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição graycolormap computa um mapa de cores com n cores cinzas variando linearmente do preto para o branco Exemplos f scf plot3d1 fcolormap graycolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap xset 659 Name grayplot esboço 2d de uma superfície utilizandose cores grayplotxyzstrfrectnax grayplotxyzoptargs Parâmetros xy vetores de reais de tamanhos n1 e n2 z matriz de reais de tamanho n1n2 zij é o valor da superfície no pontoxiyj optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes rect nax strf ou axesflag e frameflag ver plot2d e plot2doldversion strfrectnax ver plot2d Descrição grayplot faz um esboço 2d de uma superfície dada por z em um grid definido por x e y Cada retângulo no grid é preenchido com um nível de cinza ou de cor dependendo do valor médio de z nas quinas do retângulo Entre com o comando grayplot para visualizar uma demonstração Exemplos x1010 y1010m rand2121 grayplotxymrect20202020 tpi01pi msintcost clf grayplotttm Ver Também fgrayplot plot2d Sgrayplot Sfgrayplot Autor JPhC 660 Name grayplotproperties description of the grayplot entities properties Descrição A entidade Grayplot é uma folha na hierarquia de entidades gráficas Representa esboços 2d de superfícies utilizando cores e imagens ver grayplot Sgrayplot fgrayplot e Sfgray plot parent esta propriedade contém o manipulador para a raiz A raiz de uma entidade grayplot deve ser do tipo Axes children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores gray plot não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o grayplot é visível a propriedade é on Se off o grayplot não é exibido na tela data este campo define uma estrutura de dados do tipo tlist de tipo grayplotdata composto de uma linha e índices de colunas de cada elemento as coordenadas do grid x e y estão contidas respectivamente em datax e datay O campo complementar chamado dataz é o valor da superfície no ponto xiyj modo escalado ou o valor centrado da superfície definido entre dois pontos consecutivos xi e yj modo direto Se datamapping ver abaixo for ajustado para scaled todo o dado z é utilizado para realizar uma interpolação de cores enquanto que se o valor de datamapping for direct a última linha e coluna dos índices de dados z são ignoradas e a cor é determinada diretamente no mapa de cores através dos índices da submatriz dataz1111 datamapping por padrão o valor desta propriedade é scaled os índices das cores utilizadas para colorir são proporcionais ao valor das coordenadas z Em outro caso a propriedade possui valor di rect onde o esboço é um grayplot e os índices das cores de pintura são fornecidos pelos dados ver acima clipstate este campo contém o valor da propriedade clipstate para o grayplot o valor de clipstate pode ser off significa que o grayplot não é recortado clipgrf significa que o grayplot é recortado fora da caixa dos eixos on significa que o grayplot é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquer do largura altura define as porções do retângulo a ser exibido contudo o valor da propriedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade grayplot e recuperála grayplotproperties 661 Exemplos m5n5 Mround32randmn grayplot1m1nM agetcurrentaxes adatabounds 1177 hachildren hdatamappingdirect um esboço 2D de uma matriz utilizando cores xbasc agetcurrentaxes adatabounds 0044 b5ones1111 b2102104 b57572 Matplot1b1133 hachildren for i17 xclick um click ajusta os dados do Matplot hdatahdata4 end Ver Também set get delete grayplot Matplot Matplot1 graphicsentities Matplotproperties Autores Djalel ABDEMOUCHE FLeray 662 Name graypolarplot Esboço polar 2d de uma superfície utilizandose cores graypolarplotthetarhozstrfrect Parâmetros theta vetor de tamanho n1 a discretização do ângulo em radianos rho vetor de tamanho n2 a discretização do raio z matriz de reais de tamanho n1n2 zij é o valor da superfície no ponto thetairhoj strf string de comprimento 3 xy0 default o padrão é 030 x controla a exibição de legendas x0 sem legendas x1 com legendas Elas são fornecidas pelo argumento opcional leg y controla a computação da moldura y0 as molduras correntes definidas por uma chamada anterior a uma função de esboço de altonível são utilizadas Útil ao se superpor esboços múltiplos y1 o argumento opcional rect é utilizado para se especificar as fronteiras do esboço y2 as fronteiras do esboço são computadas utilizandose os valores mínimo e máximo de x e y y3 como y1 mas produz escala de isovisualização y4 como y2 mas produz escala de isovisualização y5 como y1 mas plot2d pode mudar as fronteiras do esboço e os tiques dos eixos para se obter boas graduações Quando o botão de zoom é ativado este modo é usado y6 como y2 mas plot2d pode mudar as fronteiras do esboço e os tiques dos eixos para se obter boas graduações Quando o botão de zoom é ativado este modo é usado graypolarplot 663 y7 como y5 mas a escala do novo esboço é misturada à escala corrente y8 como y6 mas a escala do novo esboço é misturada à escala corrente leg string É usado quando o primeiro caractere x do argumento strf é 1 leg possui a forma leg1leg2 onde leg1 leg2 etc são respectivamente as legendas das primeira segunda etc curvas O padrão é rect É usado quando o segundo caractere y do argumento strf é 1 3 ou 5 É um vetor linha de tamanho 4 e fornece as dimensões da moldura rectxminyminxmaxymax Descrição Toma um esboço 2d de uma superfície dada por z em um grid de coordenadas polares definido por rho e theta Cada região é preenchida com um nível de cinza ou de cor dependendo do valor médio de z nas quinas do grid Exemplos rho1014theta000212pi z30roundtheta1rho2 fgcf fcolormap hotcolormap128 clfgraypolarplotthetarhoz 664 Name havewindow Retorna o modo de janela do Scilab havewindow Descrição Retorna t se o Scilab possui a sua própria janela e f se não ie se o Scilab foi chamado com scilab nw nw significa sem janela 665 Name hist3d representação 3d de um histograma hist3dfthetaalphalegflagebox hist3dlistfxythetaalphalegflagebox Parâmetros mtx matriz de tamanho mn definindo o histograma mtxijFxiyj onde x e y asão tomados como 0m e 0n listmtxxy onde f é uma matriz de tamanho mn definindo o histograma mtxijFxiyj com vetores x e y de tamanho 1n1 e 1m1 thetaalphalegflagebox ver plot3d Descrição hist3d representa um histograma 2d como um esboço 3d Os valores são associados aos intervalos xi xi1 X yi yi1 Entre com o comando hist3d para visualizar uma demonstração Exemplos hist3d10rand1010 Z zeros1005 A absrand405 Z140 A scf hist3dZ Index findZ0 ZIndex nan scf hist3dZ A absrand105 Z91100 A scf hist3dZ Ver Também histplot plot3d Autores Steer S JPhilippe C 666 Name histplot esboça um histograma histplotn data optargs histplotx data optargs Parâmetros n inteiro positivo número de classes x vetor crescente definindo as classes x pode ter pelo menos dois componentes data vetor dados a serem analisados optargs representa uma seqüência de declarações key1value1key2value2 onde key1 key2 pode ser qualquer normalização ou parâmetro de plot2d opcional stylestrfleg rectnax logflagframeflag axesflag No caso de normalização o valor correspondente deve ser um escalar booleano valor padrão t Descrição Esta função esboça um histograma do vetor data utilizando classes x Quando o número n de classes é fornecido ao invés de x as classes são escolhidas de modo igualmente espaçado e x1 mindata x2 x1 dx xn1 maxdata com dx xn1x1n As classes são definidas por C1 x1 x2 e Ci xi xi1 para i 2 Notando Nmax o número total de data Nmax comprimento de data e Ni o número de componentes de data em Ci o valor do histograma para x em Ci é igual a NiNmax xi1xi quando normalization normalização for verdadeiro caso padrão senão é simplesmente igual a Ni Quando a normalização ocorre o histograma verifica xn1 hx dx 1 when x1mindata e maxdata xn1 x1 Qualquer plot2d parâmetro opcional pode ser fornecido por exemplo para esboçar um his tograma com a cor número 2 azul se o mapa de cores padrão for utilizado e para restringir o esboço ao retângulo 33x005 você pode utilizar histplotndata style2 rect30305 Entre com o comando histplot para visualizar uma demonstração Exemplos exemplo 1 variações ao redor de um histograma de uma amostra gaussiana aleatória drand110000normal a amostra gaussiana aleatória clfhistplot20d clfhistplot20dnormalizationf histplot 667 clfhistplot20dlegrand110000normalstyle5 clfhistplot20dlegrand110000normalstyle16 rect30305 exemplo 2 histograma de uma amsostra binomial B605 aleatória d grand10001bin 6 05 c linspace05658 xbasc subplot211 histplotc d style2 xtitlehistograma normalizado subplot212 histplotc d normalizationf style5 xtitlehistograma não normalizado exemplo 3 histograma de uma amostra exponencial aleatória lambda 2 X grand1000001exp 1lambda Xmax maxX xbasc histplot40 X style2 x linspace0maxXmax100 plot2dxlambdaexplambdaxstrf000style5 legendhistograma de amostra exponencial aleatória curva de densidade exata Ver Também hist3d plot2d dsearch 668 Name hotcolormap mapa de cores de vermelho para amarelo cmaphotcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição hotcolormap computa um mapa de cores com n cores quentes que variam do vermelho para o amarelo Exemplos f scf plot3d1 fcolormap hotcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 669 Name hsv2rgb Converte cores HSV para RGB rgb hsv2rgbhsv rgb hsv2rgbhsv rgb hsv2rgbhsv rgb hsv2rgbhsv Parâmetros h um vetor de tamanho n Os valores hue de matiz s um vetor de tamanho n Os valores saturation de saturação v um vetor de tamanho n Os valores value de valor hsv uma matriz n x 3 Cada linha contém uma tripla hue saturation value r um vetor coluna de tamanho n Os valores red de vermelho g um vetor coluna de tamanho n Os valores green de verde b um vetor coluna de tamanho n Os valores blue de azul rgb uma matriz n x 3 Cada linha contém uma tripla red green blue Descrição A função hsv2rgb converte mapas de cores entre os espaços de cores RGB e HSV Como a matiz varia de 0 a 10 as cores correspondentes podem variar partindo do vermelho entre amarelo verde ciano azul magenta e preto até vermelho novamente de modo que há na verdade valores de vermelho tanto em 0 quanto em 10 À medida em que a saturação varia de 0 a 10 as cores correspondentes matizes variam de insaturadas gradações de cinza a completamente saturadas nenhum componente branco à medida em que o valor ou brilho varia de 0 a 10 as cores correspondentes vão se tornando mais brilhantes Exemplos t0032pi zsintcost plot3d1ttz fgcffpixmapon for h0011 hsvhones321 linspace0132 07ones321 fcolormaphsv2rgbhsv showpixmap xpause10000 end for v0011 hsv2rgb 670 hsvones321 linspace0132 vones321 fcolormaphsv2rgbhsv showpixmap xpause10000 end Autor Serge Steer INRIA 671 Name hsvcolormap Mapa de cores de matizsaturaçãovalor huesaturationvalue cmap hsvcolormapn Parâmetros n inteiro 1 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição hsvcolormap computa um mapa de cores com n cores Este mapa de cores varia o componente de matiz do modelo de cor hsv huesaturationvalue matizsaturaçãovalor As cores começam do vermelho passando por amarelo verde azul celeste azul magenta e retornam para o vermelho O mapa é particularmente útil para exibir funções periódicas Exemplos t0012pi zsintcost fgcffcolormaphsvcolormap64 plot3d1ttz3545XYZ222 Autor Serge Steer INRIA Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 672 Name ishandlevalid Verifica se um conjunto de manipuladores gráficos ainda é válido isValid ishandlevalidh Parâmetros h matriz de manipuladores gráficos isValid matriz de booleanos com o mesmo tamanho que h Descriçãp ishandlevalid testa se um conjunto de manipuladores ainda é válido Um manipulador válido é um que ainda não foi deletado O resultado isValid é uma matriz de booleanos tal que isValidij é verdadeiro se hij é válido e falso em caso contrário Exemplos verificando se os objetos correntes são válidos ishandlevalidgcf gca gce criando 11 poligonais plot010 010 010 010 0055 0220 verificando a validade das poligonais axes gca polylines axeschildren1children ishandlevalidpolylines deletando algumas poligonais deletepolylines37 imprimindo a validade ishandlevalidpolylines Ver Também delete graphicsentities Autor JeanBaptiste Silvy INRIA 673 Name isoview ajusta escalas para esboço isométrico não muda o tamanho da janela isoviewxminxmaxyminymax Parâmetros xminxmaxyminymax quatro valores reais Descrição Esta função está obsoleta use a opção de plot2d frameflag4 que permite redimensionamento da janela ao invés isoview é usado para obter escalas isométricas nos eixos x e y O tamanho da janela de gráficos não é alterado O retângulo xmin xmax ymin ymax será contido no quadro computado da janela de gráficos isoview ajusta as escalas gráficas correntes e pode ser usado em conjunção com rotinas que requerem escalas gráficas correntes por exemplo strfx0z em plot2d Exemplos t0012pi plot2dsintcost xbasc isoview1111 plot2dsintcost1001 xsetdefault plot2dsintcostframeflag4 Ver Também square xsetech Autor Steer S 674 Name jetcolormap Mapa de cores de gradação do azul para o vermelho cmapjetcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com três colunas RGB Descrição jetcolormap computa o mapa de cores com n cores variando do azul passando por azul claro verde amarelo laranja e então vermelho Exemplos f scf plot3d1 fcolormap jetcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap wintercolormap 675 Name labelproperties Descrição de propriedades da entidade Label rótulo Descrição A entidade Label é um galho da entidade Axes de eixos Quando uma entidade Axes é construída os manipuladores das entidades Title e Label são criados juntos e são parte das propriedade da entidade Axes Logo as propriedades destes subobjetos são editáveis via o manipulador da entidade Axes ver gca e gda Esta entidade define os parâmetros para impressão de rótulos parent esta propriedade contém o manipulador para a raiz A raiz de uma entidade Label deve ser do tipo Axes Note que por ora a entidade Label é exclusivamente utilizada na construção de title xlabel ylabel e zlabel visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o rótulo é visível o valor da propriedade é on Se off o rótulo não é impresso na tela text a matriz contendo os strings do objeto As linhas da matriz são exibidas horizontalmente e as colunas verticalmente fontforeground este campo contém o índice de cor utilizado para exibir o rótulo text Seu valor deve ser um índice de cor relativo ao mapa de cores corrente foreground este campo contém a cor utilizada para exibir o rótulo e a linha ao redor da caixa se houver Deve ser um índice de cor relativo ao mapa de cores corrente background este campo contém a cor a ser usada para preencher a caixa se houver Deve ser um índice de cor relativo ao mapa de cores corrente fillmode este campo toma valores on ou off Se on uma caixa é desenhada ao redor do texto com uma linha em sua borda e um plano de fundo fontstyle especifica a fonte a ser utilizada para exibir o rótulo É um inteiro positivo fazendo referência uma das fontes carregadas Seu valor deve estar entre 0 fazendo referência à primeira fonte e o número de fontes carregadas menos um fazendo referência à última fonte Para mais informações veja graphicsfonts fontsize é um escalar especificando o tamanho dos caracteres exibidos Se a propriedade fractionalfont for off apenas a parte inteira é utilizada Para mais informações veja graphicsfonts fractionalfont esta propriedade especifica se o texto será utilizado utilizandose tamanhos de fonte fracionários Seu valor deve ser on ou off Se on o valor em ponto flutuante de fontsize é utilizado para a exibição e evitase o serrilhamento da fonte Se off apenas a parte inteira é utilizada e a fonte não é suavizada labelproperties 676 fontangle um escalar que permite girar o rótulo A fonte é girada em sentido horário em um ângulo dado em graus Note que mudar fontangle desabilitará automaticamente a propriedade autorotation autorotation se on o Scilab computa automaticamente o melhor ângulo de rotação para a exibição do rótulo Se off o rótulo pode ser girado manualmente através da propriedade fontangle position este vetor 2d permite posicionar o rótulo na tela A posição é armazenada em unidades de dados dos eixos Note que mudar fontangle desabilitará automaticamente a propriedade autoposition autoposition se on o Scilab computa automticamente a melhor posição para a exibição do rótulo na janela de gráficos Se off o rótulo pode ser posicionado manualmente através da propriedade po sition Exemplos agetcurrentaxes atitle typeatitle plot3d axlabel aylabel azlabel xtitleMeu títulomeu rótulo de eixo x VolumeMês tatitle tforeground9 tfontsize5 tfontstyle5 ttextSCILAB xlabelaxlabel xlabeltext Peso xlabelfontstyle 5 aylabelforeground 12 Ver Também set get delete xtitle graphicsentities axesproperties textproperties Autor Djalel ABDEMOUCHE 677 Name legend Imprime uma legenda para o gráfico hllegendh string1string2 pos boxed hllegendh strings pos boxed Parâmetros h manipulador gráfico de uma entidade de eixos ou vetor de manipuladores de entidades poligonais O valor padrão é o manipulador dos eixos correntes string1string2 strings stringsi é a legenda da iésima curva strings vetor de strings de dimensão n stringsi é a legenda da iésima curva pos opcional especifica onde imprimir as legendas este parâmetro pode ser um flag inteiro ou de modo equivalente um string ou um vetor xy que fornece as coordenadas da quina superior esquerda da caixa de legenda No primeiro caso os valores possíveis são 1 as legendas são impressas no canto superior direito 2 as legendas são impressas no canto superior esquerdo 3 as legendas são impressas no canto inferior esquerdo 4 as legendas são impressas no canto inferior direito 5 localização interativa com o mouse 1 as legendas são impressas à direita do canto superior direito 2 as legendas são impressas à esquerda do canto superior esquerdo 3 as legendas são impressas à esquerda do canto inferior esquerdo 4 as legendas são impressas à direita do canto inferior direito 5 as legendas são impressas acima do canto superior esquerdo 6 as legendas são impressas abaixo do canto inferior esquerdo boxed um booleano valor padrão t que ajusta se a caixa será desenhada ou não legend 678 hl um manipulador pontos no Compound contendo todas as legendas Descrição Põe uma legenda no esboço corrente utilizando os strings especificados como rótulos legend pre anexa rótulos por uma rechamada à linha correspondente ou remendo A rechamada é de tipo e propriedades são recobradas dos dados manipuladores Quando chamada sem o argumento manipulador ou com manipulador de uma entidade Axes a função procura vetores de manipuladores de entidades poligonais construídos primeiro que são galhos dos eixos dados Na localização interativa opt 5 movese a caixa de legenda com o mouse e apertase o botão es querdo para liberála Exemplos tlinspace0pi20 agcaadataboundst1 18t 18 plot2dtcostcos2tcos3t52 3 egce e1echildren1e1thickness2e1polylinestyle4e1arrowsizefactor 12 echildren2linestyle4 e3echildren3e3linemodeone3markbackground5 hllegendcostcos2tcos3t Ver Também plot2d xstring captions polylineproperties 679 Name legendproperties Descrição das propriedades da entidade Legend legenda Descrição A entidade Legend é uma folha na hierarquia de entidade gráficas Esta entidade define parâmetros para legendas impressas abaixo de gráficos plot2dx ou criadas pela função captions Para cada linha esboçada a legenda exibe uma amostra do tipo da linha de sua marca e de sua cor parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Legends deve ser do tipo Compound Este Compound contém também o restante das entidade gráficas children esta propriedade contém um vetor com os galhos do manipulador contudo manipuladores leg end não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Se on a legenda é impressa se off a legenda não é exibida na tela text este campo é um vetor de strings que contém as legendas para cada objeto anotado fontsize um escalar especificando o tamanho da fonte Se a propriedade fractionalfont for off apenas a parte inteira é utilizada Para mais informações veja graphicsfonts fontstyle especifica a fonte utilizada para exibir os rótulos da legenda É um inteiro positivo fazendo referência a uma das fontes carregadas Seu valor deve estar entre 0 fazendo referência à primeira fonte e o número de fontes caregadas menos um fazendo referência à última fonte Para mais informações veja graphicsfonts fontcolor um índice de cor esta propriedade determina a cor do texto fractionalfont esta propriedade especifica se os textos são exibidos utilizandose tamanhos de fonte fracionários Seu valor deve ser on ou off Se on o valor em ponto flutuante de fontsize é utilizado para a exibição e evitase o serrilhamento da fonte Se off apenas a parte inteira é utilizada e a fonte não é suavizada links um array linha de manipuladores Eles se referem às poligonais associadas legendlocation um string especifica a localização da legenda inupperright as legendas são exibidas no canto superior direito da caixa de eixos inupperleft as legendas são exibidas no canto superior esquerdo da caixa de eixos inlowerright as legendas são exibidas no canto inferior direito da caixa de eixos inlowerleft as legendas são exibidas no canto inferior esquerdo da caixa de eixos outupperright as legendas são exibidas à direita do canto superior direito da caixa de eixos legendproperties 680 outupperleft as legendas são exibidas à esquerda do canto superior esquerdo da caixa de eixos outlowerright as legendas são exibidas à direita do canto inferior direito da caixa de eixos outlowerleft as legendas são exibidas à esquerda do canto inferior esquerdo da caixa de eixos uppercaption as legendas são exibidas acima do canto superior esquerdo da caixa de eixos lowercaption as legendas são exibidas abaixo do canto inferior esquerdo da caixa de eixos Esta opção corresponde ao argumento leg de plot2d bycoordinates o canto superior esquerdo da caixa de legendas é fornecido pelo cam po position da estrutura de dados associada As posições x e y são fornecidas como frações dos axesbounds position as coordenadas do canto superior esquerdo da legenda As posições x e y são dadas como frações dos tamanhos axesbounds Este campo pode ser ajustado se legendlocationbycoordinates ou obtido de outros ajustes de legendlocation linemode este campo especifica se um retângulo é desenhado ao redor da legenda ou não Deve ser on ou off Se on o retângulo é desenhado utilizandose as seguintes propriedades thickness este campo fornece a espessura da linha utilizada para desenhar o retângulo foreground este campo contém o índice de cor da linha utilizada para desenhar o contorno do retângulo fillmode este campo especifica se o plano de fundo da legenda será pintado ou não Deve ser on ou off Se on o plano de fundo é pintado utilizandose a cor definida no campo back ground background este campo contém o índice de cor da linha utilizada para pintar a área do retângulo clipstate este campo contém o valor da propriedade clipstate para todos os objetos O valor de clipstate pode ser off significa que todos os objetos criados posteriormente não são recortados valor padrão clipgrf significa que todos os objetos criados posteriormente são recortados fora da caixa dos eixos on significa que todos os objetos criados posteriormente são recortados fora do retângulo dado pela propriedade clipbox clipbox este campo contém o valor padrão da propriedade clipbox para todos os objetos O seu valor é uma matriz vazia se clipstate é off Em outros casos o recorte é dado por xywh ponto superior esquerdo largura altura legendproperties 681 userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados do texto e recuperála Exemplos inicialização de x x0012pi plot2dxsinx sin2x sin3x123legL1L2L3 agetcurrentaxes lachildren2 llinks ltextsinxsin2xsin3x lvisibleoff invisível lfontsize 2 lfontstyle 5 lvisibleon Ver Também plot2d graphicsentities Autor Djalel ABDEMOUCHE 682 Name legends Imprime uma legenda para o gráfico legendsstringsstyleoptargs Parâmetros strings vetor de strings de dimensão n stringsi é a legenda da iésima curva style vetor linha de inteiros de dimensão n os estilos de esboço terceiro parâmetro de plot2d ou uma matriz 2 x n style1k contém o estilo de esboço para a késima curva e style2k contém o estilo de linha se style1k0 ou cor da marca se style1k0 optargs representa uma seqüência de declarações key1value1key2value2 onde key1 key2 podem ser um dos seguintes opt opcional especifica onde imprimir as legendas este parâmetro pode ser um flag inteiro ou de modo equivalente um string ou um vetor xy que fornece as coordenadas da quina superior esquerda da caixa de legenda No primeiro caso os valores possíveis são 1 ou ur as legendas são impressas no canto superior direito 2 ou ul as legendas são impressas no canto superior esquerdo 3 ou ll as legendas são impressas no canto inferior esquerdo 4 ou lr as legendas são impressas no canto inferior direito 5 ou localização interativa com o mouse padrão 6 ou below as legendas são impressas abaixo do gráfico que é redimensionado de acordo withbox um booleano valor padrão t que ajusta se a caixa será desenhada ou não fontsize um inteiro valor padrão 1 que ajusta o tamanho da fonte para os nomes na legenda Descrição Põe uma legenda no esboço corrente utilizando strings especificados como rótulos Na localização interativa opt5 ou opt movese a caixa de legenda com o mouse e apertase o botão esquerdo para liberála Esta função permite uma localização mais flexível de legendas que o argumento de plot2d leg Exemplos legends 683 Exemplo 1 t0012pi plot2dtcostcos2tcos3t12 3 legendscostcos2tcos3t12 3optlr scf xsetline style2plot2dtcoststyle5 xsetline style4plot2dtsintstyle3 legendssintcost5234 withboxf opt Exemplo 2 scf subplot221 t0012pi plot2dtcostcos2tcos3t12 3 legendscostcos2tcos3t12 3 opt3 subplot222 xsetline style2plot2dtcoststyle5 xsetline style4plot2dtsintstyle3 legendssintcost5234 withboxf opt6 subplot223 xsetline style2plot2dtcoststyle5 xsetline style4plot2dtsintstyle3 legendssintcost5234 withboxf opt1 fontsize2 subplot224 t0012pi plot2dtcostcos2tcos3t12 3 legendscostcos2tcos3t12 3 opt2 fontsize1 Ver Também plot2d xstring xtitle legend 684 Name locate seleção pelo mouse de um conjunto de pontos xlocatenflag Parâmetros x matriz de tamanho 2n1 n1n se o parâmetro n for dado nflag valores inteiros Descrição locate é usado para obter as coordenadas de um ou mais pontos selecionados com o mouse em uma janela de gráficos As coordenadas são fornecidas usandose a escala de gráficos corrente Se n0 n pontos são selecionados e suas coordenadas são retornadas na matriz x Se n0 os pontos são selecionados até que o usuário clique com o botão esquerdo do mouse que significa parar O último ponto clicado com o botão esquerdo não é retornado xlocate é o mesmo que xlocate1 Se flag1 uma cruz é desenhada nos pontos onde o mouse foi clicado Ver Também xclick xgetmouse Autores SS JPhC 685 Name mesh Esboço 3d de uma malha meshZ meshXYZ meshGlobalProperty meshcolorGlobalProperty meshaxeshandle Parâmetros Z matriz de reais definindo a altura da superfície Não pode ser omitida O dado Z é uma matriz mxn XY duas matrizes de reais sempre ajustadas juntas esses dados definem um novo grid padrão Estes novos componentes X e Y do grid devem coincidir com as dimensões de Z ver descrição abaixo color uma matriz de reais opcional definindo a cor para cada ponto XjYi do grid ver descrição abaixo GlobalProperty este argumento opcional representa uma seqüência de pares de declarações PropertyNamePropertyValue que definem propriedades globais dos objetos apli cadas a todas as curvas criadas neste esboço Para uma completa visualização das propriedades disponíveis veja GlobalProperty axeshandle este argumento opcional força o esboço a aparecer dentro dos eixos selecionados por axeshandle ao invés dos eixos correntes ver gca Descrição mesh desenha uma superfície parametrizada utilizando um grid retangular definido pelas coordenadas X e Y se XY não são especificados este grid é determinado utilizandose as dimensões da matriz Z em cada ponto deste grid uma coordenada Z é dada utilizandose a matriz Z mesh é baseado no comando surf com a opção padrão colormode índice de branco dentro do mapa de cores corrente e colorflag 0 Especificação de dados de entrada Neste parágrafo para sermos mais claros não mencionaremos os argumentos opcionais Global Property já que eles não interferem na entrada de dados exceto pelas propriedades Xdata Ydata e Zdata ver GlobalProperty Assumese que todos estes argumentos opcionais pode riam estar presentes também Se Z é a única matriz especificada Z esboça a matriz Z versus o grid definido por 1sizeZ2 ao longo do eixo x e 1sizeZ1 ao longo do eixo y Observação Para habilitarse o modo de transparência você deve ajustar a opção colormode para 0 Exemplo mesh 686 XYmeshgrid111111 ZX2Y2 xtitlezx2y 2 meshXYZ Ver Também surf meshgrid plot2d LineSpec GlobalProperty Autor FBelahcene 687 Name milkdrop Função 3d gota de leite zmilkdropxy Parâmetros xy dois vetores linhas de tamanhos n1 e n2 z matriz de tamanho n1n2 Descrição milkdrop é uma função que representa uma gota de leite caindo no leite Pode ser usada para testar funções eval3d e plot3d Exemplos x2012 yx zeval3dmilkdropxy plot3dxyz Ver Também eval3d plot3d Autor Steer S 688 Name move Move uma entidade gráfica e seus galhos movehxy movehxyalone Parâmetros h manipulador da entidade a ser movida xy um array dxdy que fornece o vetor translação a ser aplicado alone palavrachave string opcional Descrição Esta rotina pode ser usada para aplicar uma translação em uma entidade de gráficos Se a entidade tiver galhos unidades de dependência hierárquica elas também serão transladadas Dada a palavra chave alone apenas a unidade especificada precisa ser redesenhada Deve ser especialmente usada com a propriedade pixeldrawingmode da entidade de figura ver como desenhar objetos no modo de desenho xor Exemplos Ver Também get set draw figureproperties graphicsentities Autor Djalel ABDEMOUCHE 689 Name name2rgb Retorna valores RGB correspondentes ao nome da cor rgbname2rgbname Parâmetros name nome da cor rgb vetor de valores RGB inteiros de uma cor Descrição name2rgb retorna os valores RGB vermelho verde azul inteiros de uma cor dado o seu nome O resultado é um vetor rgb onde r g e b são inteiros entre 0 e 255 correspondentes aos compo nentes de cor vermelho verde e azul Como de uso 0 significa nenhuma intensidade e 255 significa intensidade total da cor Se uma cor não for encontrada é retornado A lista de todas as cores conhecidas é dada por colorlist Exemplos rgbname2rgbgold rgb2namergb Ver Também color colorlist rgb2name 690 Name newaxes Cria uma nova entidade Axes de eixos anewaxes Parâmetros a o manipulador para a nova entidade Axes criada Descrição newaxes é usado para criar uma nova entidade Axes ver graphicsentities na figura corrente As propriedades dessa entidade são herdadas da entidade defaultaxes ver gda Exemplos clf a1newaxes a1axesbounds001005 t00120 plottacoshtr a2newaxes a2axesbounds0051005 x0014 plotxsinhx legendsinh scaa1 tornando os primeiros eixos os eixos correntes plottasinhtg legendacoshasinh Ver Também subplot gda sca Autor S Steer INRIA 691 Name nf3d Facetas retangulares para parâmetros da função plot3d xxyyzznf3dxyz Parâmetros xyxxxyyzz 6 matrizes de reais Descrição Função utilitária Usada para transformar facetas retangulares codificadas em três matrizes xy e z para o código Scilab para facetas aceito por plot3d Exemplos Uma esfera u linspacepi2pi240 v linspace02pi20 x cosucosv y cosusinv z sinuonesv plot3d2xyz é equivalente a xxyyzznf3dxyz plot3dxxyyzz Ver Também plot3d plot3d2 692 Name objecteditor Descrição das capacidades do editor de objetos gráficos graphic Descrição das capacidades do editor de objetos gráficos menus Descrição das capacidades do editor de objetos gráficos Descrição Os gráficos do Scilab permitem que o usuário interaja com os gráficos antes e depois de têlos desen hado Cada janela gráfica e seus conteúdos são representados por entidades hierárquicas O topo da hierarquia é a figura entidade Figure Cada figura define pelo menos uma entidade galho do tipo Axes eixos Cada entidade Axes contém entidades folhas que são objetos gráficos básicos como Rectangles Arcs Segs retângulos arcos segmentos Também contém o tipo Compound que são conjuntos recursivos de entidades O principal interesse do novo modo gráfico é tornar mudanças de propriedades mais fáceis Este novo modo de gráficos fornece um conjunto de rotinas gráficas de altonível ver set get utilizadas para controlar propriedades dos objetos tais como dados coordenadas e escalas cores e aparências sem que seja necessário entrar com os comandos gráficos iniciais novamente Entidades gráficas são associadas a variáveis Scilab do tipo handle a qual chamaremos manipulador Um manipulador é um identificador único que é associado a cada instância de uma entidade gráfica criada Utilizando manipuladores é possível alcançar propriedades de entidade através das rotinas set e get Os manipuladores também são utilizados para manipular objetos gráficos para movê los para fazer copiálos ou deletálos Para completar e utilizar a capacidade de um manipulador gráfico ao seu máximo um editor de objetos gráficos também foi criado É um conjunto de interfaces TclTk disponíveis para cada tipo de objeto gráfico ver graphicsentities para mais detalhes que pode ser habilitado para cada janela de gráficos Para fazêlo funcionar selecione o menu Edit na janela de gráficos Sete operações de edição gráfica estão disponíveis Select figure as current permite que uma figura seja a corrente Redraw figure redesenha o conteúdo da janela de gráficos Erase figure apaga o conteúdo da janela de gráficos Sua ação corresponde a um comando clf Os últimos oito itens são especialmente dedicados ao editor gráfico Copy object utilizando o mouse permite que o usuário selecione um objeto 2d como uma curva um retângulo e coloque na área de transferência Logo por uma nova chamada a Paste object colar objeto o objeto é copiado nos eixos correntes selecionados Paste object permite que o usuário cole um objeto anterior posto na àrea de transferência nos eixos correntes selecionados objecteditor 693 Move object utilizando o mouse permite que o usuário mova um objeto 2d como uma curva um retângulo dentro dos eixos correntes selecionados Delete object utilizando o mouse permite que o usuário selecione um objeto 2dcomo uma curva um retângulo dentro dos eixos correntes selecionados e deleteo instantaneamente Figure Properties lança a interface TclTk para o objeto Figure aplicado ao manipulador da figura da janela de gráficos Current Axes Properties lança a interface TclTk para o objeto Axes aplicado ao manipulador dos eixos correntes da janela de gráficos Start Entity Picker inicia um manipulador de eventos na janela de gráficos para pegar os cliques do mouse sobre objetos gráficos e lança a interface TclTk correspondente O clique com botão esquerdo do mouse permite edição de objetos e com botão direito realiza um movimento do objeto selecionado Note que por ora este recurso só se aplica a objetos 2d Stop Entity Picker para a ação de Entity Picker terminando o manipulador de eventos na janela de gráficos Uma vez que a interface gráfica é habilitada utilizando as opções Figure Properties ou Cur rent Axes Properties duas áreas principais aparecem Um tree selector seletor de árvore posicionado à direita do editor gráfico um seletor de árvores hierárquicas especifica que objeto é correntemente editado Pode ser usado para alternar de um objeto gráfico para outro fornecido estando eles na mesma janela de gráficos objecteditor 694 Um notebook caderno a segunda área representa um caderno composto de diferentes páginas de propriedades como Style Data Clipping dependendo do objeto gráfico selecionado Utilizandose este edi tor podese editar mais facilmente todo o conjunto de propriedade gráficas de cada objeto gráfico como através dos comandos set e get Aqui está um exemplo de um caderno para a entidade Axes exibindo as suas propriedades objecteditor 695 Furthermore você poderá colocar legendasanotações em sua figura utilizando primitivas de amostra fornecidas no menu Insert na janela gráfica Utilizando o mouse e seguindo as instruções na sub janela de mensagem você poderá acrescentar Line Desenhe uma linha entre dois cliques do mouse A linha vive nos eixos onde o primeiro ponto foi selecionado objecteditor 696 Polyline Desenhe uma poligonal clicando no botão esquerdo para definir o caminho da linha e clique no botão direito para completar o desenho A poligonal vive nos eixos onde o primeiro ponto foi selecionado Arrow Desenhe uma seta entre dois cliques do mouse A seta vive nos eixos onde o primeiro ponto foi selecionado Double arrow Desenhe uma seta dupla entre dois cliques do mouse A seta dupla vive nos eixos onde o primeiro ponto foi selecionado Text Abra uma caixa de diálogo para inserir o texto então clique na janela da figura para posicionálo O texto vive nos eixos onde o primeiro ponto foi selecionado Rectangle Desenhe um retângulo dois cliques com o botão direito definem os cantos superior esquerdo e inferior direito do retângulo O retângulo vive nos eixos onde o primeiro ponto foi selecionado Circle Desenhe um círculo 2dois cliques com o botão direito definem os cantos superior esquerdo e inferior direito da caixa em que o círculo vive O retângulo vive nos eixos onde o primeiro ponto foi selecionado Ver Também graphicsentities set get clf plot Autor FLeray INRIA 697 Name oceancolormap Mapa de cores linear azul cmapoceancolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição oceancolormap computa um mapa de cores com n cores azuis que variam linearmente do preto para o azul Exemplos f scf plot3d1 fcolormap oceancolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap pinkcolormap rainbowcolormap springcolormap summercol ormap whitecolormap wintercolormap 698 Name oldplot Esboço simples versão antiga oldplotxyxcapycapcaption oldploty Parâmetros xy dois vetores de tamanhos iguais xcapycapcaption strings ou matrizes de strings Descrição Esboça y em função x xcap e ycap são legendas para os eixos x e y respectivamente e caption é a legenda do esboço IChamado com apenas um argumento oldploty esboça o vetor y ou se y for uma matriz esboça todos os vetores linhas em um mesmo esboço Isto é feito em relação ao vetor 1 número de colunas de y oldplot está obsoleto Use plot2d ou plot ao invés Exemplos x0012pi esboço simples oldplotsinx usando legendas xbasc oldplotxsinxsintempoesboço de seno esboço de duas funções xbasc oldplotsinxcosx Ver Também plot2d plot Autor JPhC 699 Name param3d esboço 3d de uma curva parametrizada param3dxyzthetaalphalegflagebox Parâmetros xyz três vetores de mesmo tamanho pontos da curva parametrizada theta alpha valores reais fornecendo em graus as coordenadas esféricas do ponto de observação os valores padrões são 35 e 45 graus leg string definindo rótulos para cada eixo com como separador de campo por exemploXYZ flagtypebox type e box possuem o mesmo significado que em plot3d type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos Este é o valor padrão type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2Note que as fronteiras dos eixos podem ser customizadas através das pro priedades da entidade de eixos ver axesproperties box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 param3d 700 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos também pode ser customizado através das propriedades da en tidade Axes ver axesproperties Este é o padrão ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag se este for ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds field que também pode ser ajustado através das propriedades da entidade de eixos ver axesproperties O valor padrão de ebox é 010101 Descrição param3d é usado para esboçar uma curva 3d definida por suas coordenadas x y e z Note que os dados também podem ser ajustados ou recebidos através das propriedades da entidade superfície ver surfaceproperties Note que propriedades como rotation angles colors e thickness da superfície esboçada também podem ser ajustadas através das propriedades de param3d ver param3dproperties Use param3d1 para realizar esboços múltiplos Entre com o comando param3d para visualizar uma demonstração Exemplos t0015pi param3dsintcostt103545XYZ23 egce o manipulador para a poligonal 3d eforegroundcolorred agca o manipulador para os eixos arotationangles10 70 Ver Também param3d1 plot3d Autor JPhC 701 Name param3d1 esboço 3d de curvas parametrizadas param3d1xyzthetaalphalegflagebox param3d1xylistzcolorsthetaalphalegflagebox Parâmetros xyz matrizes de mesmo tamanho nlnc Cada coluna i das matrizes corresponde às coordenadas da iésima curva Você pode fornecer uma cor específica para cada curva utilizando listzcolors ao invés de z onde colors é um vetor de tamanho nc Se colori for negativo a curva é esboçada utilizandose a marca com identificador absstylei se stylei for estritamente positivo uma linha simples com idenficador de cor stylei ou uma linha tracejada com identificador de tipo de tracejado stylei é utilizada thetaalpha valores reais fornecendo em graus as coordenadas esféricas do ponto de observação Os valores padrões são 35 e 45 graus leg string definindo rótulos para cada eixo com como separador de campo por exemplo XYZ flagtypebox type e box possuem o mesmo significado que em plot3d type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos Este é o valor padrão type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das pro priedades da entidade de eixos ver axesproperties param3d1 702 box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos também pode ser customizado através das propriedades da en tidade Axes ver axesproperties Este é o valor padrão ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag se este estiver ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds fque também pode ser ajustado através das propriedades da entidade de eixos ver axesproperties O valor padrão de ebox é 010101 Descrição param3d1 usado para esboçar curvas 3d definidas por suas coordenadas x y e z Note que os dados também podem ser ajustados ou recebidos através das propriedades da entidade Surface ver surfaceproperties Note que propriedades como rotation angles colors e thickness das curvas esboçadas também podem ser ajustadas através das propriedades de param3d ver param3dproperties Entre com o comando param3d1 para visualizar uma demonstração Exemplos xsetwindow20 criando janela de número 20 t0015pi param3d1sintsin2tcostcos2t listt10sint323545XYZ23 xdel20 agetcurrentaxesobtendo manipulador dos novos eixos criados t0015pi param3d1sintsin2tcostcos2tt10sint arotationangles6575 adatabounds111112 limites fornecidos por databounds athickness 2 hachildren obtendo o manipulador para a entidade Param3d um Compound composto de duas curvas hchildren1foreground 3 primeira curva curve2 hchildren2 curve2foreground 6 curve2markstyle 2 param3d1 703 Ver Também param3d plot3d plot2d gca xdel delete Autor JPhC 704 Name param3dproperties description of the 3D curves entities properties Descrição A entidade Param3d é uma folha na hierarquia de entidades gráficas visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão as curvas são visíveis a propriedade é on Se off as curvas não são desen hadas na tela data este campo contém as coordenadas de curvas 3d É a matriz XYZ tal que Xi Yi Zi contém as coordenadas 3d da iésima curva Este campo contém o valor padrão da propriedade linestyle para objetos segmentos arcos retângulos e poligonais linemode este campo contém o valor padrão da propriedade linemode para a poligonal O valor pode ser on linha desenhada ou off nenhuma linha desenhada linestyle este campo seleciona o tipo de linha a ser utilizada para desenhar linhas O valor deve ser um inteiro em 0 6 0 significa linha sólida o restante seleciona tracejados ver getlinestyle polylinestyle este campo seleciona o modo como as curvas são desenhadas modos interpolado padrão escada esboço de barras em setas e preenchido estão disponíveis por índices inteiros em 15 markmode este campo contém o valor padrão da propriedade markmode Deve ser on ou off valor padrão markstyle este campo contém o valor padrão da propriedade markstyle A propriedade markstyle seleciona o tipo de marca a ser exibida o valor deve ser um inteiro em 0 9 que significa ponto sinal de mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo trevo e círculo marksizeunit este campo contém o valor padrão da propriedade marksizeunit Se marksizeunit for ajustado para point então o valor de marksize é diretamente dado em pontos Quan do marksizeunit é ajustado para tabulated marksize é computado em relação ao array de tamanho de fonte logo seu valor deve ser um inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que param3d e funções puras do Scilab utilizam o modo tabulat ed como padrão quando se utiliza a função plot o modo point é automaticamente habilitado marksize este campo contém o valor padrão da propriedade marksize A propriedade marksize seleciona o tamanho de fonte da marca a ser exibida Deve ser um valor inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt ver getmark markforeground este campo contém o valor da propriedade markforeground que é a cor da borda das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor da propriedade markbackground que é a cor da face das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente param3dproperties 705 thickness este campo contém o valor padrão da propriedade thickness espessura das linhas utilizadas para desenhar os eixos e curvas Deve ser um inteiro positivo foreground este campo contém o índice de cor utilizado para desenhar as curvas O valor deve ser um índice de cor relativo ao mapa de cores corrente clipstate este campo contém o valor padrão da propriedade clipstate O valor pode ser off significa que todas as curvas criadas posteriormente não serão recortadasvalor padrão clipgrf significa que todas as cruvas criadas posteriormente serão recortadas fora do fora das fronteiras da entidade Axes on significa que todas as curvas criadas posteriormente serão recortadas fora do retângulo dado pela propriedade clipbox clipbox este campo contém o valor padrão da propriedade clipbox É uma matriz vazia se clipstate é off Em outros casos o recorte é dado pelo vetor xywh ponto superior esquerdo largura altura userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade Param3d e recuperála parent esta propriedade contém o manipulador para a raiz A raiz de uma entidade curvas 3d deve ser do tipo Axes ou Compound Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados t0015pi param3d1sintsin2tcostcos2tt10sint arotationangles6575 adatabounds111112 limites dados por databounds athickness 2 hachildren obtendo o manipulador da entidade param3d um Compound composto de duas curvas hchildren1foreground 3 primeira curva curve2 hchildren2 curve2foreground 6 curve2markstyle 2 Ver Também set get delete param3d param3d1 graphicsentities Autor Djalel ABDEMOUCHE 706 Name paramfplot2d Esboço animado 2d curva definida por uma função paramfplot2dfxtheta paramfplot2dfxthetaflag paramfplot2dfxthetaflagrect Parâmetros x vetor de reais f função yfxt f é uma função Scilab ou rotina dinamicamente ligada referida através de um string theta vetor de reais conjunto de parâmetros flag string no ou yes Se yes a janela é limpa entre dois esboços consecutivos rect retângulo xmin xmax ymin ymax 1 x 4 vetor de reais Descrição Esboço animado da função xfxt para t theta1 theta2 etc f pode ser uma função do Scilab ou uma rotina dinamicamente ligada desde que yfxt seja avaliado como yfevalxtf Ver feval A função f tal que xt fxt RN é avaliada em x vetor de RN e tnúmero real x é um Nvetor de valores x e para cada t em theta fxtNvetor de valores y Exemplos deffyfxtytsinx xlinspace02pi50theta00051 paramfplot2dfxtheta Ver Também plot2d feval fplot2d 707 Name pie Desenha um gráfico de torta piex piexsptxt Parâmetros x um escalar real ou vetor de reais positivos sp um escalar real ou vetor de reais txt uma célula ou vetor de strings Descrição piex se o tamanho de x é N então a função desenha um gráfico de torta de N partes a área da i ésima parte é igual a xisumx superfície do círculo unitário piexsp o vetor sp permite cortar um ou vários pedaços da torta o tamanho de sp deve ser igual a N Se o valor do iésimo índice de sp é diferente de 0 então a iésima parte é separada das outras por um espaço senão se for igual a zero então é anexada às outras piextxt o vetor txt permite escrever um texto para cada parte da torta o iésimo componente de txt corresponde à iésima parte da torta padrão são escritas as porcentagens que correspondem às partes da superfície O tamanho de txt deve ser igual a N Exemplos primeiro exemplo um argumento de entrada x1 2 5 scf0 pie1 2 5 segundo exemplo dois argumentos de entrada x5 9 4 6 3 sp0 1 0 1 0 o segundo e o quarto são separados dos demais scf1 pie5 9 4 6 30 1 0 1 0 terceiro exemplo três argumentos de entrada x3 4 6 2 sp0 1 0 0 txtparte 1parte 2parte 3parte 4 scf2 pie3 4 6 20 1 0 0parte 1parte 2parte 3parte 4 Ver Também xfpolys Autor Farid Belahcene 708 Name pinkcolormap Coloração de tons em sépia de imagens em preto e branco cmappinkcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição pinkcolormap computa um mapa de cores que fornece uma coloração de tons em sépia de imagens em preto e branco Exemplos f scf plot3d1 fcolormap pinkcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap rainbowcolormap springcolormap summercol ormap whitecolormap wintercolormap 709 Name plot Esboço 2d plotyLineSpecGlobalProperty plotxyLineSpecGlobalProperty plotx1y1LineSpec1x2y2LineSpec2xNyNLineSpecNGlobalProperty1GlobalProperty2GlobalPropertyM plotaxeshandle Parâmetros x uma matriz ou vetor de reais Se omitido é assumido como sendo o vetor 1n onde n é o número de pontos de curva dado pelo parâmetro y y uma matriz de reais ou um vetor y também pode ser uma função definida como um macro ou uma primitiva LineSpec este argumento opcional deve ser usado como um atalho para especificar um modo de desen har uma linha Podemos ter um LineSpec por y ou xy previamente entrados As opções LineSpec lidam com os especificadores LineStyle Marker e Color ver LineSpec Estes es pecificadores determinam o estilo de linha de marcas e a cor das linhas esboçadas GlobalProperty este argumento opcional representa uma seqüência de pares de declarações PropertyNamePropertyValue tque define propriedades globais de objetos a serem aplicadas a todas as curvas criadas pelo esboço Para uma visualização completa de das pro priedades disponíveis veja GlobalProperty axeshandle este argumento opcional força o esboço a aparecer dentro dos eixos selecionados fornecidos por axeshandle ao invés dos eixos correntes ver gca Descrição plot esboça um conjunto de curvas 2d plot foi reconstruído para lidar melhor com a sintaxe do Matlab Para melhorar a compatibilidade gráfica com o Matlab utilize plot ao invés de plot2d Especificação de entrada de dados Neste parágrafo para sermos mais claros não mencionaremos os argumentos opcionais LineSpec ou GlobalProperty já que eles não interferem na entrada de dados exceto pelas propriedades Xdata Ydata e Zdata ver GlobalProperty É assumido que todos estes argumentos po dem estar presentes também Se y é um vetor ploty esboça um vetor y versus o vetor 1sizey Se y é uma matriz ploty esboça cada coluna de y versus o vetor 1sizey1 Se x e y são vetores plotxy esboça o vetor y versus o vetor x Os vetores x e y devem ter o mesmo número de entradas Se x é um vetor e y uma matriz plotxy esboça cada coluna de y versus o vetor x Neste caso o número de colunas de y deve ser igual ao número de entradas de x Se x e y são matrizes plotxy esboça cada coluna de y versus a coluna correspondente de x Neste caso os tamanhos x e y devem ser os mesmos plot 710 Finalmente se apenas x ou y é uma matriz o vetor é esboçado versus cada linha ou cada coluna da matriz A escolha é feita dependendo se a dimensão de linha ou coluna do vetor coincide com a dimensão de linha ou coluna da matriz No caso de uma matriz quadrada apenas x ou penas y a prioridade é dada a colunas ao invés de linhas ver exemplos abaixo y também pode ser uma função definida como um macro ou uma primitiva Neste caso os dados x devem ser fornecidos como um vetor ou uma matriz e a computação correspondente de yx é feita implicitamente Os argumentos LineSpec e GlobalProperty devem ser utilizados para customizar o esboço Aqui está uma lista completa das opções disponíveis LineSpec esta opção pode ser utilizada para se especificar de um modo curto e fácil como as curvas são de senhadas Deve sempre ser um string contendo referências aos especificadores LineStyle Marker e Color Essas referências devem ser ajustadas denro do string a ordem não é importante de modo a não ter ambigüidades Por exemplo para especificar uma linha vermelha de traço longo com marcas de rombos podese escrever rd ou dire ou reddiam ou outra sentença sem ambigüidade ou de modo completo diamondred ver LineSpec Note que os estilos de linha e marcas e tamanhos e as cores podem ser reajustados através das propriedades da entidade poligonal ver polylineproperties GlobalProperty esta opção pode ser utilizada para especificar como as linhas serão desenhadas com mais opções que via LineSpec Deve sempre ser um par de declarações constituidos de um string definindo PropertyName nome da propriedade e seu valor associado PropertyValue que pode ser um string um inteiro ou qualquer outra coisa dependendo do tipo de PropertyName Utilizandose GlobalProperty podese ajustar várias propriedades todas as propriedades disponíveis via LineSpec e mais a cor da marca plano de fundo e primeiro plano a visibilidade o recorte e a espessura das curvas ver GlobalProperty Note que todas as propriedades podem ser reajustadas através das propriedades de entidades poligonais ver polylineproperties Observações Por padrão esboços sucessivos são superpostos Para limpar o esboço anterior use clf Para ha bilitar o modo autoclear limpeza automática como modo padrão edite seus eixos fazendo o seguinte dagda daautoclear on Para uma melhor exibição a função plot pode modificar a propriedade box de seu Axes eixos raíze Isto acontece quando uma entidade Axes é criada por uma chamada a plot ou é vazia antes da chamada Se um dos eixos é centrado na origem box é desabilitado Em caso contrário box é habilitado Para mais informações sobre a propriedade box e sobre o posicionamento dos eixos veja axesproperties Uma tabela de cores padrão é utilizada para colorir as curvas esboçadas quando você não especifica as cores Ao desenhar linhas múltiplas o comando plot automaticamente atribui as cores abaixo de modo cíclico Aqui estão as cores utilizadas R G B 0 0 1 plot 711 0 05 0 1 0 0 0 075 075 075 0 075 075 075 0 025 025 025 Entre com o comando plot para visualizar uma demonstração Exemplos inicialização de x x0012pi esboço simples plotsinx clf plotxsinx esboços múltiplos clf plotxsinx sin2x sin3x clf eixo à direita plotxsinx agca manipulador da entidade Axes aylocation right clf eixo centrado em 00 plotx4sinxx2cosx agca manipulador da entidade Axes axlocation middle aylocation middle algumas operações em entidades criadas por plot agca aisoviewon achildren listando os galhos da entidade Axes aqui é um galho Compound composto por duas entidades poly1 achildrenchildren2 armazenando um manipulador Polyline em poly1 poly1foreground 4 outro modo de se mudar o estilo poly1thickness 3 e a espessura de uma curva poly1clipstateoff controle de recorte aisoviewoff exemplos com LineSpec e GlobalProperty clf t0pi202pi plottsintrotcostcyatabssintmo scf2 plott tsint costxdat12 scf3 axfig3 gca scf4 deveria permanecer em branco plotaxfig3t tsint costzdat12markerdmarkerfacgreenmarkeredgyel plot 712 xdelwinsid especificação de dados tpi01pi sizet plott esboços simples de y versus tamanho do vetor t clf limpando figura plottsint esboça sint versus t clf t1 1 1 1 2 3 4 5 3 4 5 6 4 5 6 7 plott esboça cada coluna t column versus tamanho de linha clf subplot221 plottsint esboça sint versus t coluna por coluna desta vez xtitlesint versus t subplot222 plottsint xtitlesint versus t subplot223 plottsint agca adatabounds0 17 1 para ver a linha vertical escondida pelo eixo y xtitlesint versus t subplot224 plottsint xtitlesint versus t clf caso especial 1 x vector 5 6 7 8 and y matrix t x5 6 7 8 plotxt plotxt idem x é automaiticamente transposto para corresponder a t aqui as colunas clf apenas um caso de possibilidade de correspondência como realizar quatro esboços idênticos 4 de quatro maneiras 4 x é um vetor 1x4 vector y is uma matriz nãoquadrada 4x5 subplot221 plotxt 891012 subplot222 plotxt 891012 subplot223 plotxt 891012 subplot224 plotxt 891012 clf caso especial 2 caso onde apenas x ou y é uma matriz quadrada x matrix t e y vetor 1 2 3 4 plot 713 plott1 2 3 4 equivalente a plott1 1 1 12 2 2 23 3 3 34 4 4 4 plott1234 o mesmo esboço clf t é transposto note a prioridade dada ao tratamento das colunas plott1 2 3 4 equivalente a plott1 1 1 12 2 2 23 3 3 34 4 4 4 plott1 2 3 4 o mesmo esboço clf y é uma função definida por uma primitiva plot10110sin equivalente a plot10110sin10110 clf uma macro deffytotoxyxx plot110toto Ver Também plot2d surf scf clf xdel delete LineSpec GlobalProperty Autor FLeray 714 Name plot2d esboço 2d plot2dxy plot2dxyoptargs Parâmetros x uma matriz ou vetor de reais Se omitido é assumido como sendo o vetor 1n onde n é o número de pontos da curva dados pelo parâmetro y y uma matriz ou vetor de reais optargs representa uma seqüência de sentenças key1value1key2value2 onde key1 key2 podem ser um dos seguintes style ajusta o estilo da curva O valor associado deve ser um vetor de reais com valores inteiros positivos ou negativos rect as fronteiras mínimas requeridas para o esboço O valor associado deve ser um vetor de reais com quatro entradas xminyminxmaxymax logflag ajusta a escala linear ou logaritmica ao longo dos eixos O valor associado deve ser um string com um dos possíveis valores nn nl ln e ll frameflag controla a computação dos intervalos de coordenadas reais a partir dos valores mínimos re queridos O valor associado deve ser um inteiro entre 0 e 8 axesflag especifica como os eixos são desenhados O valor associado deve ser um inteiro entre 0 e 5 nax ajusta os rótulos dos eixos e a definição de tiques O valor associado deve ser um vetor de quatro entradas inteiras nxNxnyNy leg ajusta a legenda das curvas O valor associado deve ser um string Descrição plot2d esboça um conjunto de curvas 2d Se você está familiarizado com a sintaxe do Matlab da função plot você deve usar plot Se x e y são vetores plot2dxyoptargs esboça o vetor y versus o vetor x Os vetores x e y vectors devem ter o mesmo número de entradas Se x é um vetor e y uma matriz plot2dxyoptargs esboça cada coluna de y versus o vetor x Neste caso o número de colunas de y deve ser igual ao número de entradas de x Se x e y são matrizes plot2dxyoptargs esboça cada coluna de y versus a coluna correspondente de x Neste caso x e y devem ter o mesmo tamanho plot2d 715 Se y é um vetor plot2dyoptargs esboça o vetor y versus o vetor 1sizey Se y é uma matriz plot2dyoptargs esboça cada coluna de y versus o vetor 1sizey1 Os argumentos optargs devem ser usados para customizar o esboço style esta opção deve ser usada para especificar como as curvas são desenhadas Se esta opção for especificada o valor associado deve ser um vetor com tantas entradas quanto as curvas Se stylei é estritamente crescente a curva é desenhada como uma linha simples e stylei define o índice da cor para utilizada para desenhar a curva ver getcolor Note que o estilo de linha e a espessura podem ser ajustados através das propriedades da entidade poligonal ver polylineproperties Interpolação linear é feita entre os dados pontos da curva Se stylei é negativo ou zero os pontos dados são desenhados utilizandose marcas absstylei define a marca com identificador utilizada Note que as cores das mar cas e seus tamanhos podem ser ajustados através das propriedades da entidade poligonal ver polylineproperties logflag esta opção é usada para ajustar a escala linear ou logarítmica ao longo dos eixos O valor asso ciado é um string com um dos seguintes valores nn nl ln e ll l significa escala e graduação logarítimica e n escala normal rect esta opção pode ser usada para ajustar as fronteiras mínimas requeridas para o esboço Se esta opção for especificada o valor associado deve ser um vetor real de quatro entradas xminyminxmaxymax xmin e xmax definem os limites para as abscissas enquanto ymin e ymax definem os limites para as ordenadas Este argumento pode ser utilizado junto com a opção frameflag para especificar como os limites dos eixos derivam do argumento dado rect Se a opção frameflag não for fornecida é suposta como sendo frameflag7 As fronteiras dos eixos também podem ser customizadas através das propriedades da entidade de eixos Axes ver axesproperties frameflag esta opção pode ser usada para controlar a computação dos intervalos de coordenadas reais a partir de valores mínimos requeridos Mudanças reais podem ser maiores que os requerimentos mínimos frameflag0 não há computação o esboço usa a escala anterior ou padrão frameflag1 os intervalos reais são dados pela opção rect frameflag2 os intervalos reais são computados a partir dos valores máximos e mínimos dos dados x e y frameflag3 os intevalo reais são os intervalos fornecidos pela opção rect e aumentados para se obter uma escala isométrica frameflag4 os intervalos reais são computados a partir dos valores máximos e mínimos de x e y e au mentados para se obter uma escala isométrica plot2d 716 frameflag5 os intervalos reais são os intervalos fornecidos pela opção rect e aumentados para se obter rótulos de eixos embelezados frameflag6 os intervalos reais são computados a partir dos valores mínimos dos dados x e y e então aumentados para se obter rótulos de eixos embelezados frameflag7 é como frameflag1 mas os esboços anteriores são redesenhados em uma nova escala É utilizado para adicionar o gráfico corrente a um anterior frameflag8 é como frameflag2 mas os esboços anteriores são redesenhados em uma nova escala É utilizado para adicionar o gráfico corrente a um anterior frameflag9 é como frameflag8 mas a imagem é aumentada enlarged to para se obter rótulos de eixos embelezados Este é o alor padrão Os limites dos eixos também podem ser customizados através das propriedades da entidade de eixos ver axesproperties axesflag esta opção pode ser utilizada para especificar como os eixos são desenhados O valor associado deve ser um inteiro entre 0 e 5 axesflag0 nada é desenhado ao redor do esboço axesvisibleoff offboxoff axesflag1 os eixos são desenhados o eixo y é exibido à esquerda axesvisibleon onboxonylocationleft axesflag2 o esboço é cercado por uma caixa sem tiques axesvisibleoff offboxon axesflag3 os eixos são desenhados o eixo y é exibido à direita axesvisibleon onboxoffylocationright axesflag4 os eixos são desenhados centrados no meio da caixa de moldura axesflag5 os eixos são desenhados para se cruzarem no ponto 00 Se o ponto 00 não estiver dentro da moldura os eixos não aparecerão no gráfico axesvisibleon onboxonylocationmiddle axesflag9 os eixos são desenhados o eixo y é exibido à esquerda axesvisibleon onboxoffylocationleft Este é o valor padrão O aspecto dos eixos também pode ser customizado através das propriedades da entidade de eixos ver axesproperties nax esta opção pode ser utilizada para se especificar os rótulos dos eixos e a definição de tiques quando a opção axesflag1 é utilizada O valor associado deve ser um vetor de inteiros com quatro entradas nxNxnyNy plot2d 717 Nx fornece o número de tiques principais utilizados no eixo x não mais levado em conta nx fornece o número de subtiques entre dois tiques principais no eixo x Ny e ny fornecem as informações similares para o eixo y Se a opção axesflag não for ajustada a opção nax supõe que a opção axesflag foi ajustada para 1 leg esta opção pode ser usada para se ajustar as legendas das curvas deve ser um string com a forma leg1leg2 onde leg1 leg2 etc São respectivamente as legendas para a primeira curva segunda curva etc o padrão é As legendas de curvas são desenhadas abaixo do eixo x Esta opção não é tão flexível use as funções captions ou legend preferivelmente Mais Informações Para obter mais informações sobre a sintaxe antiga de plot 2d veja a documentação plot2doldversion Por padrão esboços sucessivos são superpostos para limpar o esboço anterior use clf Entre com o comando plot2d para uma demonstração Outras funções plot2d de alto nível existem plot2d2 é o mesmo que plot2d mas as curvas são supostas seccionalmente constantes plot2d3 é o mesmo que plot2d mas a curva é esboçada com barras verticais plot2d4 é o mesmo que plot2d mas a curva é esboçada com flechas Exemplos inicialização de x x0012pi esboço simples plot2dsinx clf plot2dxsinx múltiplos esboços clf plot2dxsinx sin2x sin3x múltiplos esboços sem fornecer as dimensões da moldura clf plot2dxsinx sin2x sin3xrect00605 múltiplos esboços com legendas dados tiques estilo clf plot2dxsinx sin2x sin3x 123legL1L2L3nax210210rect022pi2 isovisualização clf plot2dxsinx1frameflag 4 escala clf plot2dxsinx1frameflag 6 autoescala com esboços anteriores estilo plot2d 718 clf plot2dxsinx1 plot2dx2sinx12 plot2d2xcosx3 eixo à direita clf plot2dxsinxlegsinx agca manipulador da entidade Axes aylocation right eixo centrado em 00 clf plot2dx4sinx1legsinx agca manipulador da entidade Axes axlocation middle aylocation middle algumas operações sobre entidades criadas por plot2d agca aisoviewon achildren lista dos galhos dos eixos há um Compound formado por duas poligonais e uma legenda poly1 achildren1children1 armazena um manipulador de poligonal em poly1 poly1foreground 4 outra maneira de se mudar o estilo poly1thickness 3 e a espessura de uma curva poly1clipstateoff controle de recorte leg achildren2 armazena manipulador de legenda em leg legfontstyle 9 leglinemode on aisoviewoff Ver Também plot plot2d1 plot2d2 plot2d3 plot2d4 clf xdel delete 719 Name plot2d1 Esboço 2d em escala logarítmica obsoleto plot2d1strxystylestrflegrectnax Parâmetros str string de comprimento 3 abc a pode ter um dos seguintes valores e o ou g e significa vazio Especifica que o valor de x não é utilizado os valores de x são supostos regularmente espaçados ie 1número de linhas de y De qualquer forma o usuário deve fornecer o valor de x 1 por exemplo plot2d1enn1y o significa um Se há várias curvas todas possuem o mesmo valor x x é um vetor col una de tamanho n1 e y é uma matriz de tamanhonlnc Por exemplo x0012 piplot2d1onnxsinx cosx g significageral x e y devem ter o mesmo tamanho nlnc Cada coluna de y é esboçada em relação à coluna correspondente de x nc curvas são esboçadas utilizandose nl pontos b c pode possuir valores n normal ou l logarítmico bl um eixo logarítmico é utilizado em x cl um eixo logarítmico é utilizado em y xystylestrflegrectnax estes argumentos possuem o mesmo significado que na função plot2d optargs estes argumentos possuem o mesmo significado que na função plot2d Descrição Esta função está obsoleta Utilize plot2d ao invés plot2d1 esboça um conjunto de curvas 2d É o mesmo que plot2d mas com mais um argumento str que habilita escala logarítmica Ainda permite especificar apenas um vetor coluna para x quando é o mesmo para todas as curvas Por padrão esboços sucessivos são superpostos Para limpar o esboço anterior use clf Entre com o comando plot2d1 para visualizar uma demonstração Exemplos plot2d1 720 esboços múltiplos sem fornecer x x0012pi plot2d1enn1sinx sin2x sin3x esboços múltiplos fornecendo apenas x clf plot2d1onnxsinx sin2x sin3x esboço logarítmico x01013 clf plot2d1ollxexpx expx2 expx3 Ver Também plot2d plot2d2 plot2d3 plot2d4 clf Autor JPhC 721 Name plot2d2 esboço 2d funções de degraus plot2d2xy plot2d2xyoptargs plot2d2logflagxystylestrflegrectnax Parâmetros args ver plot2d para uma descrição dos parâmetros Descrição plot2d2 é o mesmo que plot2d mas as funções dadas por xy são supostas seccionalmente constantes Por padrão esboços sucessivos são superpostos Para limpar os esboços anteriores use clf Entre com o comando plot2d2 para visualizar uma demonstração Note que todos os modos propostos por plot2dxx xx 1 a 4 podem ser habilitados utilizandose plot2d e ajustando a opção polylinestyle para o número correspondente Exemplos esboçando uma função de degrau de valor i no segmento ii1 o último segmento não é desenhado plot2d214141111função de degrau0055 compare o seguinte com plot2d x0012pi clf plot2d2xsinx sin2x sin3x apenas no novo modo gráfico clf plot2dxsinx sin2x sin3x egce echildren1polylinestyle2 echildren2polylinestyle2 echildren3polylinestyle2 Ver Também plot2d plot2d3 plot2d4 subplot clf polylineproperties Autor JPhC 722 Name plot2d3 esboço 2d barras veticais plot2d3logflags xystylestrflegrectnax plot232y plot2d3xy optargs Parâmetros args ver plot2d para uma descrição dos parâmetros Descrição plot2d3 é o mesmo que plot2d mas as curvas são esboçadas utilizandose barras verticais Por padrão esboços sucessivos são superpostos Para limpar esboços anteriores use clf Entre com o comando plot2d3 para visualizar uma demonstração Note que todos os modos pro postos por plot2dxx xx 1 a 4 podem ser habilitados utilizandose plot2d podem ser habilita dos utilizandose polylinestyle para o número correspondente Exemplos compare o seguinte com plot2d1 x0012pi plot2d3xsinx sin2x sin3x no novo modo de gráficos apenas clf plot2dxsinx sin2x sin3x egce echildren1polylinestyle3 echildren2polylinestyle3 echildren3polylinestyle3 Ver Também plot2d plot2d2 plot2d4 clf polylineproperties Autor JPhC 723 Name plot2d4 esboço 2d setas plot2d4logflag xystylestrflegrectnax plot2d4y plot2d4xy optargs Parâmetros args ver plot2d para uma descrição dos parâmetrosfor a description of parameters Descrição plot2d4 é o mesmo que plot2d mas as curvas são esboçadas utilizandose setas Isto pode ser útil para se esboçar solulções de uma EDO equação diferencial ordinária em um espaço fásico Por padrão esboços sucessivos são superpostos Para limpar o esboço anterior use clf Entre com o comando plot2d4 para visualizar uma demonstração Note que todos os modos propostos por plot2dxx xx 1 a 4 podem ser habilitados utilizandose plot2d e ajustandose a opção polylinestyle para o número correspondente Exemplos compare o seguinte com plot2d1 x0012pi plot2d4xsinx sin2x sin3x apenas no novo modo gráfico clf plot2dxsinx sin2x sin3x egce echildren1polylinestyle4 echildren2polylinestyle4 echildren3polylinestyle4 Ver Também fchamp plot2d plot2d2 plot2d3 subplot clf polylineproperties Autor JPhC 724 Name plot2doldversion As sintaxes descritas abaixo estão obsoletas plot2dlogflagxystylestrflegrectnax Parâmetros xy duas matrizes ou vetores colunas De maneira usual x é uma matriz de mesmo tamanho que y a coluna j de y é esboçada em relação à coluna j de x Se todas as colunas de x são iguais ie as abscissas de todas as curvas são as mesmas x pode ser simplesmente o vetor coluna destas abscissas x é então um vetor coluna de comprimento igual a dimensão de linha de y Quando x não é fornecido é suposto como sendo o vetor 1 2 dimensão de linha de y style é um vetor real de tamanho nc O estilo a ser utilizado na curva i é definido por stylei O estilo padrão é 1nc 1 para a primeira curva 2 para a segunda etc Se stylei é negativo ou zero a curva é esboçada com marca de identificador absstylei use xset para ajustar o identificador de marca e xgetmark para obter o identificador de marca corrente Se stylei for estritamente positivo uma linha simples de identificador de cor stylei ou uma linha tracejada com identificador de tracejado stylei é utilizada use xset para vizualizar os identificadores de cor Quando apenas uma curva é desenhada style pode ser um vetor linha de tamanho stypos onde sty é utilizado para especificar o estilo e pos é um inteiro entre 1 e 6 que especifica uma posição a ser utilizada para a legenda Pode ser útil quando o usuário dese ja desenhar múltiplas curvas em um esboço chamando a função plot2d várias vezes e quer fornecer uma legenda para cada curva Esta opção não possui mais efeito no modo gráfico novo Utilize a função captions para ajustar as legendas quando todas as curvas forem desenhadas strf string de comprimento 3 xyz por padrão strf 081 x controla a exibição de legendas x0 sem legendas x1 legendas são exibidas Elas são dadas pelo argumento opcional leg y controla a computação dos intervalos de coordenadas reais a partir dos valores mínimos re queridos Intervalos reais podem ser maiores que os requerimentos mínimos y0 sem computação o esboço utiliza a escala anterior ou padrão plot2doldversion 725 y1 a partir do argumento rect y2 a partir dos valores mínimomáximo dos dados x e y y3 constrói uma escala isométrica a partir do argumento rect y4 constrói um esboço isométrico a partir dos valores mínimomáximo dos dados x e y y5 aumentados para obtenção de bons eixos a partir do argumento rect y6 aumentados para obtenção de bons eixos a partir dos valores mínimomáximo dos dados x e y y7 como y 1 mas os anteriores são redesenhados para se utilizar a nova escala y8 como y 2 mas os anteriores são redesenhados para se utilizar a nova escala z controla a exibição de informação na moldura ao redor do esboço Se eixos são requeridos o número de tiques pode ser especificado pelo argumento opcional nax z0 nada é desenhado ao redor do esboço z1 eixos são desenhados o eixo y é exibido à esquerda z2 o esboço é cercado por uma caixa sem tiques z3 eixos são desenhados o eixo y é exibido à direita z4 eixos são desenhados centrados no meio da caixa de moldura z5 eixos são desenhados cruzandose no ponto 00 Se o ponto 00 não estiver den tro da moldura os eixos não aparecerão no gráfico leg um string É utilizado quando o primeiro caractere x do argumento strf é 1 leg tem a forma leg1leg2 onde leg1 leg2 etc são respectivamente as legendas para a primeira segunda etc curvas O padrão é rect este argumento é utilizado quando o segundo caractere y do argumento strf is 1 3 ou 5 é 1 3 ou 5 É um vetor linha de tamanho quatro e fornece a dimensão da moldura rectxminyminxmaxymax nax este argumento opcional é utilizado quando o terceiro caractere z do argumento strf é 1 É um vetor linha de quatro entradas nxNxnyNy onde nx ny é o número de subgraduações no eixo x y axis e Nx Ny é o número de graduações no eixo x y plot2doldversion 726 logflag um string formado por dois caracteres h para eixo horizontal e v for para eixo vertical cada um desses caracteres pode assumir valores n ou l l corresponde à graduação logarítmica e n à graduação normal Por exemplo ll corresponde a um esboço com ambos os eixos x e y em graduação logarítmica O valor padrão é nn Descrição plot2d esboça um conjunto de curvas 2d Esboço linear seccional é utilizado Por padrão esboços sucessivos são superpostos Para limpar o esboço anterior use xbasc Veja o significado dos parâmetros acima para uma completa descrição Entre com o comando plot2d para uma demonstração Outras funções plot2d de altonível existem plot2d2 é o mesmo que plot2d mas as curvas são supostas seccionalmente constantes plot2d3 é o mesmo que plot2d mas a curva é esboçada com barras verticais plot2d4 é o mesmo que plot2d mas a curva é esboçada com flechas Exemplos esboço simples x0012pi plot2dsinx xbasc plot2dxsinx esboços múltiplos xbasc plot2dxsinx sin2x sin3x esboços múltiplos fornecendo as dimensões da moldura sintaxe antiga e sintaxe nova xbasc plot2dxsinx sin2x sin3x1301100605 xbasc plot2dxsinx sin2x sin3xrect00605 esboços múltiplos com legendas e tiques dados velha sintaxe e nova sintaxe xbasc plot2dxsinx sin2x sin3x 123111L1L2L3022pi2210210 xbasc plot2dxsinx sin2x sin3x 123legL1L2L3nax210210rect022pi2 isovisualização xbasc plot2dxsinx1041 escala xbasc plot2dxsinx1061 autoescala com esboços anteriores xbasc plot2dxsinx1 plot2dx2sinx2 plot2d2xcosx3 plot2doldversion 727 eixo à direita xbasc plot2dxsinx1183sinx eixo centrado xbasc plot2dxsinx1184sinx eixo centrado em00 xbasc plot2dx4sinx1185sinx Ver Também plot2d1 plot2d2 plot2d3 plot2d4 xbasc xset Autor JPhC 728 Name plot3d esboço 3d de uma superfície plot3dxyzthetaalphalegflagebox plot3dxyzoptargs plot3dxfyfzfthetaalphalegflagebox plot3dxfyfzfoptargs plot3dxfyflistzfcolorsthetaalphalegflagebox plot3dxfyflistzfcolorsoptargs Parâmetros xy vetores linhas de tamanhos n1 e n2 coordenadas dos eixos x e y Estas coordenadas devem ser monótonas z matriz de tamanho n1n2 zij é o valor da superfície no ponto xiyj xfyfzf matrizes de tamanho nfn Elas definem as facetas usadas para desenhar a superfície Há n fac etas Cada faceta i é definida por um polígono com nf pontos As coordenadas dos eixos x y e z dos pontos da iésima faceta são dados respectivamente por xfi yfi e zfi colors um vetor de tamanho n fornecendo as cores de cada faceta ou uma matriz de tamanho nfn fornecendo a cor próxima a cada borda da faceta a cor da faceta é interpolada optargs representa uma seqüência de sentenças key1value1 key2value2 onde key1 key2 pode ser um dos seguintes theta alpha leg flag ebox ver definições abaixo theta alpha valores reais de dados em graus as coordenadas esféricas de observação do ponto leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho três flagmodetypebox mode um inteiro cor da superfície mode0 a superfície é pintada com a cor mode a borda da faceta é desenhada com o estilo e linha e cor correntes mode0 uma malha da superfície é desenhada mode0 a superfície é pintada com a cor mode a borda da faceta não é desenhada Note que o tratamento de cor da superfície pode ser feito utilizandose as opções colormode e colorflag através das propriedades da entidade superfície ver surfaceproperties plot3d 729 type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relção de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relção de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das propriedades da entidade de eixos ver axesproperties box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos pode ser customizado através das propriedades da entidade de eixos ver axesproperties ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag se este for ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds que também pode ser ajustado através das propriedades da entidade de eixos ver axesproperties plot3d 730 Descrição plot3dxyzthetaalphalegflagebox desenha a superfície parametrizada zfxy plot3dxfyfzfthetaalphaleg flagebox desenha uma superfície defini da por um conjunto de facetas Você pode desenhar esboços multiplos substituindo xf yf e zf por múltiplas matrizes montadas por linhas como xf1 xf2 yf1 yf2 e zf1 zf2 Note que os dados também podem ser ajustados ou recebidos através das propriedades da entidade superfície ver surfaceproperties Você pode fornecer uma cor específica para cada faceta utilizando listzfcolors ao invés de zf onde colors é um vetor de tamanho n Se colorsi for positivo fornece a cor da faceta i e a borda da faceta é desenhada utilizandose o estilo de linha e cor correntes Se colorsi for negativo o identificador de cor colorsi é utilizado e a borda da faceta não é desenhada Também é possível obter cores interpoladas para as facetas Para este tipo de cor o argumento deve ser uma matriz nf x n fornecendo as cores próximas a cada borda da faceta de cada faceta Neste caso valores positivos para cores significam que as bordas não seram desenhadas Note que as cores também podem ser ajustadas através das propriedades da entidade Surface superfície via tlist affectations e editadas utilizandose a opção colorflag ver surfaceproperties Os arugumentos opcionais theta alpha leg flag ebox podem ser passados por uma seqüência de argumentos key1value1 key2value2 Neste caso a ordem não tem sig nificado especial Note que todos estes argumentos exceto flag podem ser customizados através de propriedades da entidade de eixos ver axesproperties Como descrito anteriormente a opção flag lida com as propriedades da entidade superfície para mode ver surfaceproperties e as propriedades de eixos Axes para type e box ver axesproperties Você pode utilizar a função genfac3d para computar facetas de quatro lados da superfície zfxy eval3dp também pode ser utilizado Entre com o comando plot3d para visualizar uma demonstração Exemplos esboço simples utilizando zfxy t0032pi zsintcost plot3dttz o mesmo esboço utilizando facetas computadas por genfac3d xxyyzzgenfac3dttz clf plot3dxxyyzz esboços múltiplos clf plot3dxx xxyy yyzz 4zz esboços múltiplos utilizandose cores clf plot3dxx xxyy yylistzz zz44ones1400 5ones1400 esboço simples utilizando ponto de observação e legendas clf plot3d11012010rand1020alpha35theta45flag223 plot3d 731 esboço de uma esfera utilizando utilizando facetas computadas por eval3dp deffxyzsphalptetxrcosalpcostetorig1onestet yrcosalpsintetorig2onestet zrsinalporig3onestet r1 orig0 0 0 xxyyzzeval3dpsphlinspacepi2pi240linspace0pi220 clfplot3dxxyyzz clf fgcf fcolormap hotcolormap128 r03orig15 0 0 xx1yy1zz1eval3dpsphlinspacepi2pi240linspace0pi220 ccxxzz232cc1xx1orig1zz1r232 clfplot3d1xx xx1yy yy1listzzzz1cc cc1theta70alpha80flag563 operações disponíveis apenas no novo modo de gráficos deletegcf t0032pi zsintcost xxyyzzgenfac3dttz plot3dxx xxyy yylistzz zz44ones1400 5ones1400 egce fedata TL tlist3d x y z colorfxfyfz6randfz matriz de cores aleatória edata TL TL2 tlist3d x y z colorfxfyfz4rand1800 vetor de cores aleatório edata TL2 TL3 tlist3d x y z colorfxfyfz20ones1400 6ones1400 edata TL3 TL4 tlist3d x y zfxfyfz nenhuma cor edata TL4 ecolorflag1 índice de cor proporcional à altitude coordenada z ecolorflag2 de volta ao modo padrão ecolorflag 3 modo de gradação interpolada baseada na cor azul padrão clf plot3dxx xxyy yylistzz zz44ones1400 5ones1400 hgce obtendo manipulador da entidade corrente aqui é a superfície agca obtendo eixos correntes arotationangles4070 agrid1 1 1 criando grides adatabounds601665 aaxesvisibleoff os eixo estão escondidos aaxesbounds2 0 1 1 hcolorflag1 colorindo de acordo com z hcolormode2 removendo as bordas das facetas ajustando colormode para a cor branca hcolorflag2 colorindo de acordo com as cores fornecidas hcolormode 1 colocando de volta as bordas das facetas ajustando colormode de volta para preto fgcfobtendo o manipulador da figura raiz fcolormaphotcolormap512 c14001400 TLcolor cc1c2c3 hdata TL hcolorflag3 modo de gradação interpolada We can use the plot3d function to plot a set of patches triangular quadrangular etc The plot3d function to draw patches plot3d 732 patchxyz patchxylistzc The size of x number of points in the patches x number of patches y and z have the same sizes as x c a vector of size number of patches the color of the patches a matrix of size number of points in the patches x number of patches the color of each points of each patches Example 1 a set of triangular patches x 0 0 0 1 1 1 y 1 1 2 2 2 1 z 1 1 1 1 1 1 tcolor 2 3 subplot221 plot3dxylistztcolor xtitleA triangle set of patches Example 2 a mixture of triangular and quadrangular patches xquad 5 0 100 155 105 yquad 150 2010 1515 105 zquad ones42 xtri 01010 5 0 102020 5 0 2020151010 ytri 01020 510 1020201520 0 0151020 ztri zeros35 subplot223 plot3dxquadyquadzquad plot3dxtriytriztri xtitleMixing triangle and quadrangle set of patches plot3d 733 Example 3 some rabbits rabxtri 5 5 25 75 10 5 15 5 10 10 15 15 5 10 15 rabytri 10 10 95 25 0 20 10 12 5 5 10 0 7 0 0 rabztri 00000 00000 00000 rabtricolorbyface 2 2 2 2 2 rabtricolor 22222 33333 44444 rabxquad 0 1 0 6 511 5 6 rabyquad 1823 2328 2328 1823 rabzquad 11 11 11 11 rabquadcolorbyface 2 2 rabquadcolor 22 33 44 55 subplot222 plot3drabxtri rabytri listrabztrirabtricolor plot3drabxquadrabyquadlistrabzquadrabquadcolor h gcf hchildren1background 1 xtitleA psychedelic rabbit set of patches subplot224 plot3drabxtri rabytri listrabztrirabtricolorbyface plot3drabxquadrabyquadlistrabzquadrabquadcolorbyface h gcf hchildren1background 1 xtitleA standard rabbit set of patches The result of the preceding example plot3d 734 We can also use the plot3d function to plot a set of patches using vertex and faces Vertex Faces example 3D example The vertex list contains the list of unique points composing each patch The points common to 2 patches are not repeated in the vertex list vertex 0 1 1 0 2 2 1 2 3 1 1 4 The face list indicates which points are composing the patch face 1 2 3 1 3 4 tcolor 2 3 plot3d 735 The formula used to translate the vertex face representation into x y z lists xvf matrixvertexface1sizeface1lengthvertexface1sizeface1 yvf matrixvertexface2sizeface1lengthvertexface1sizeface1 zvf matrixvertexface3sizeface1lengthvertexface1sizeface1 scf subplot211 plot3dxvfyvflistzvftcolor xtitleA triangle set of patches vertex face mode 3d 2D test We use the 3D representation with a 0 Z values and then switch to 2D representation Vertex Faces example 3D example The vertex list contains the list of unique points composing each patch The points common to 2 patches are not repeated in the vertex list vertex 0 1 0 2 1 2 1 1 The face list indicates which points are composing the patch face 1 2 3 1 3 4 The formula used to translate the vertex face representation into x y z lists xvf matrixvertexface1sizeface1lengthvertexface1sizeface1 yvf matrixvertexface2sizeface1lengthvertexface1sizeface1 zvf matrixzerosvertexface2sizeface1lengthvertexface1sizeface1 subplot212 plot3dxvfyvflistzvftcolor xtitleA triangle set of patches vertex face mode 2D a gca aview 2d The result of the preceding example plot3d 736 How to set manually some ticks plot3d h gca hxticks tlisttickslocationslabels2101221012 hyticks tlisttickslocationslabels432101234432101234 hzticks tlisttickslocationslabels101Point 1Point 2Point 3 Ver Também eval3dp genfac3d geom3d param3d plot3d1 clf gca gcf xdel delete axesproperties Autor JPhC 737 Name plot3d1 Esboço 3d em níveis de cinza ou de cores de uma superfície plot3d1xyzthetaalphalegflagebox plot3d1xfyfzfthetaalphalegflagebox plot3d1xyzoptsargs plot3d1xfyfzfoptsargs Parâmetros xy vetores linhas de tamanhos n1 e n2 coordenadas dos eixos x e y Estas coordenadas devem ser monótonas z matriz de tamanho n1n2 zij é o valor da superfície no ponto xiyj xfyfzf matrizes de tamanho nfn Elas definem as facetas usadas para desenhar a superfície Há n fac etas Cada faceta i é definida por um polígono com nf pontos As coordenadas dos eixos x y e z dos pontos da iésima faceta são dados respectivamente por xfi yfi e zfi optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 pode ser um dos seguintes theta alpha leg flag ebox ver definições abaixo theta alpha valores reais de dados em graus as coordenadas esféricas do ponto de observação leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho três flagmodetypebox mode um inteiro cor da superfície mode0 a superfície é pintada com a cor mode a borda da faceta é desenhada com o estilo e linha e cor correntes mode0 uma malha da superfície é desenhada mode0 a superfície é pintada com a cor mode a borda da faceta não é desenhada Note que o tratamento de cor da superfície pode ser feito utilizandose as opções colormode e colorflag através das propriedades da entidade Surface ver surfaceproperties type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 plot3d1 738 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das propriedades da entidade Axes ver axesproperties box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos pode ser customizado através das propriedades da entidade Axes ver axesproperties ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag é ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds que também pode ser ajustado através das propriedades da entidade de eixos ver axesproperties Descrição plot3d1 esboça uma superfície com cores dependendo do nível z da superfície Esta função de esboço especial também pode ser habilitada ajustando colorflag1 após um plot3d ver surfaceproperties plot3d1 739 Entre com o comando plot3d1 para visualizar uma demonstração Exemplos esboço simples utilizando zfxy t0032pi zsintcost plot3d1ttz mesmo esboço utilizando facetas computadas por genfac3d xxyyzzgenfac3dttz clf plot3d1xxyyzz esboços múltiplos clf plot3d1xx xxyy yyzz 4zz esboço simples com ponto de vista e legendas clf plot3d111012010rand10203545XYZ223 mesmo esboço sem grid clf plot3d111012010rand10203545XYZ223 esboço de uma esfera utilizando facetas computadas por eval3dp deffxyzsphalptetxrcosalpcostetorig1onestet yrcosalpsintetorig2onestet zrsinalporig3onestet r1 orig0 0 0 xxyyzzeval3dpsphlinspacepi2pi240linspace0pi220 clf plot3dxxyyzz egce ecolorflag1 scf2 plot3d1xxyyzz os dois gráficos são similares Ver Também plot3d gca gce scf clf Autor JPhC 740 Name plot3d2 Esboço de superfície definida por facetas retangulares plot3d2XYZ vectthetaalphalegflagebox plot3d2XYZ optargs Parâmetros X Y Z três matrizes de reais definindo uma estrutura de dados vect vetor de reais optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes theta alpha legflagebox ver definições abaixo theta alpha valores reais de dados em graus as coordenadas esféricas do ponto de observação leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho três flagmodetypebox mode um inteiro cor da superfície mode0 a superfície é pintada com a cor mode a borda da faceta é desenhada com os estilos correntes de linha e cor mode0 uma malha da superfície é desenhada mode0 a superfície é pintada com a cor mode a borda da faceta não é desenhada Note que o tratamento de cor da superfície pode ser feito utilizandose as opções colormode e colorflag através das propriedades da entidade superfície ver surfaceproperties type um inteiro tipo de escala type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos plot3d2 741 type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das propriedades da entidade Axes ver axesproperties box um inteiro moldura ao redor do esboço box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos pode ser customizado através das propriedades da entidade Axes ver axesproperties ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax Este argumento é utilizado junto com type em flag se for ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds que também pode ser ajustado através das propriedades da entidade Axes ver axesproperties Descrição plot3d2 esboça uma superfície definida por facetas retangulares XYZ são três matrizes que descrevem uma superfície A superfície é composta de polígonos de quatro lados As coordenadas x de uma faceta são dadas por XijXi1jXij1Xi1j1 De modo semel hante Y e Z são coordenadas Y e Z O vetor vect é usado quando múltiplas superfícies são codificadas nas mesmas matrizes XYZ vectj fornece a linha na qual a codificação da jésima superfície começa Como em plot3d as mesmas propriedades são editáveis ver surfaceproperties e axesproperties plot3d2 742 Exemplos u linspacepi2pi240 v linspace02pi20 X cosucosv Y cosusinv Z sinuonesv plot3d2XYZ apenas no novo modo de gráficos egce ecolormode4 mudando a cor fedata TL tlist3d x y z colorfxfyfz10fz1 edataTL ecolorflag2 Ver Também plot3d genfac3d 743 Name plot3d3 Esboço de malha de uma superfície definida por facetas retangulares plot3d3XYZ vectthetaalphalegflagebox plot3d3XYZ optargs Parâmetros X Y Z 3 três matrizes de reais definindo uma estrutura de dados vect vetor de reais optargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 podem ser um dos seguintes theta alpha legflagebox ver definições abaixo theta alpha valores reais de dados em graus as coordenadas esféricas do ponto de observação leg string definindo os rótulos para cada eixo com como um separador de campos por exemplo XYZ flag um vetor real de tamanho quatro flagverticalcolor horizontalcolortypebox verticalcolor um inteiro cor da superfície o padrão é 3 Índice do mapa de cores definindo a cor a ser utilizada para se desenhar as bordas verticais horizontalcolor um inteiro cor da superfície o padrão é 4 Índice do mapa de cores definindo a cor a ser utilizada para se desenhar as bordas horizontais type um inteiro escala o padrão é 2 type0 o esboço é feito utilizandose a escala 3d corrente definida por uma chamada anterior a param3d plot3d contour ou plot3d1 type1 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são especificadas pelo valor do argumento opcional ebox type2 reescala automaticamente caixas 3d com relação de aspecto extrema as fronteiras são computadas utilizandose dados fornecidos type3 fronteiras 3d isométricas com fronteiras da caixa dadas por ebox de modo semelhante a type1 type4 fronteiras 3d isométricas derivadas dos dados de modo semelhante a type2 plot3d3 744 type5 fronteiras 3d isométricas expandidas com fronteiras fornecidas por ebox de modo semelhante a type1 type6 fronteiras 3d isométricas expandidas derivadas dos dados de modo semelhante a type2 Note que as fronteiras dos eixos podem ser customizadas através das propriedades da entidade de eixos ver axesproperties box um inteiro moldura ao redor do esboço o padrão é 4 box0 nada é desenhado ao redor do esboço box1 não implementado é como box0 box2 apenas os eixos atrás da superfície são desenhados box3 uma caixa cercando a superfície é desenhada e legendas são adicionadas box4 uma caixa cercando a superfície é desenhada e legendas e eixos são adicionados Note que o aspecto dos eixos pode ser customizado através das propriedades da entidade Axes ver axesproperties ebox especifica as fronteiras do esboço através do vetor xminxmaxyminymaxzminzmax TEste argumento é utilizado junto com type em flag se for ajustado para 1 3 ou 5 volte acima para ver o comportamento correspondente Se flag estiver faltando ebox não é levado em conta Note que quando especificado o argumento ebox age no campo databounds que também pode ser ajustado através das propriedades da entidade Axes ver axesproperties Descrição plot3d3 realiza um esboço de malha de uma superfície definida por facetas retangulares XYZ são três matrizes que descrevem uma superfície A superfície é composta por polígonos de quatro lados As coordenadas X de uma faceta são dadas por XijXi1jXij1Xi1j1 De modo semel hante Y e Z são coordenadas Y e Z O vetor vect é usado quando múltiplas superfícies são codificadas nas mesmas matrizes XYZ vectj fornece a linha na qual a codificação da jésima superfície começa Ver plot3d2 para uma descrição completa Como um esboço de malha a única propriedade disponível que você pode editar é a opção visible ver axesproperties Exemplos u linspacepi2pi240 v linspace02pi20 X cosucosv plot3d3 745 Y cosusinv Z sinuonesv plot3d3XYZ apenas no novo modo de gráficos egce obtendo a entidade corrente evisibleoff evisibleon de volta à visão da malha Ver Também plot3d2 plot3d param3d 746 Name plotframe esboça uma moldura com escalas e grides Esta função está obsoleta plotframerectticsargopt1argopt2argopt3 plotframerectoptsargs Parameters rect vetor xminyminxmaxymax tics vetor nxmxnymy onde mx nx resp my ny são o número de intervalos e subinter valos do eixo x resp eixo y argoptX até três argumentos opcionais escolhidos entre flags vetor wantgridsfindbounds onde wantgrids é uma variável booleana t ou f que indica o gridding findbounds é uma variável booleana Se findbounds for t os limites dados em rect podem ser ligeiramente modificados na verdade sempre au mentados a fim de se obter graduações mais simples então tics2 e tics4 são ig norados Captions vetor de três strings titlexlegyleg correspondentes respectivamente ao título do esboço e às legendas dos eixos x e y Aviso o C maiúsculo é importante subwin um vetor de tamanho 4 definindo a subjanela A subjanela é especificada através do parâmetro subwinxywh ponto superior esquerdo largura altura Os valores em subwin são especificados utilizandose a proporção de largura ou altura da janela de gráficos corrente ver xsetech optsargs representa uma seqüência de declarações key1value1 key2value2 onde key1 key2 po dem ser um dos seguintes tics flags captions ou subwin Estes argumentos têm o mesmo sig nificado que aqueles utilizados na primeira forma da rotina Descrição plotframe é utilizado com funções de esboço 2d plot2d plot2d1 para ajustar uma moldura gráfica Deve ser usado antes de plot2d que deve ser chamado com o modo de superposição 000 Esta função está obsoleta Exemplos x0308273 yrandx rectminxminymaxxmaxy tics41025 4 xintervalos e 2 yintervalos plotframerectticsffMeu esboçoxy000505 plot2dxy2000 plotframerectticsticsflagstfCaptionsMeu esboço com gridesxysubwin0500505 plotframe 747 plot2dxy3000 plotframerectticstt Meu esboço com grides e fronteiras automáticasxy0050505 plot2dxy4000 plotframerectflagsftticstics CaptionsMeu esboço sem grides mas com fronteiras automáticas xy subwin05050505 plot2dxy5000 Ver Também plot2d graduate xsetech 748 Name plzr Esboço de pólozero plzrsl Parâmetros sl lista syslin Descrição Produz um esboço de pólozero do sistema linear sl lista syslin Exemplos spoly0s n1s 23s4s2 5 0 1s s d13s 5s3 s11s 1ss2 3s1 hsyslincnd plzrh Ver Também trzeros roots syslin 749 Name polarplot Esboço de coordenadas polares polarplotthetarhostylestrflegrect polarplotthetarhooptargs Parâmetros rho vetor valores dos raio theta vetor de mesmo tamanho que rho valores dos ângulos optargs uma seqüência de declarações key1value1 key2value2 onde keys podem ser stylelegrectstrf ou frameflag style vetor de reais de tamanho nc O estilo a ser usado pela curva i é definido por stylei O valor padrão é 1nc 1 para a primeira curva 2 para a segunda etc Se stylei for negativo a curva é esboçada utilizandose a marca com idenfiticador absstylei1 use xset para ver os identificadores das marcas Se stylei for estritamente positivo uma linha simples com identificador de cor stylei ou linha tracejada com identificador de estilo de tracejado stylei é usada use xset para ver os identificadores de cor Quando apenas uma curva é desenhada style pode ser um vetor linha de tamanho 2 stypos onde sty é utilizado para se especificar o estilo e pos é um inteiro entre 1 e 6 que especifica a posição para a legenda Isto pode ser útil quando o usuário deseja desenhar curvas múltiplas em um esboço chamando a função plot2d várias vezes e quer fornecer uma legenda para cada curva strf istring de comprimento 3 xy0 default o padrão é 030 x controla a exibição de legendas x0 sem legendas x1 com legendas Elas são fornecidas pelo argumento opcional leg y controla a computação da moldura É o mesmo que frameflag y0 as fronteiras correntes definidas por uma chamada anterior a uma função de esboço de altonível são utilizadas Útil ao se superpor esboços múltiplos polarplot 750 y1 o argumento opcional rect é utilizado para se especificar as fronteiras do esboço y2 as fronteiras do esboço são computadas utilizandose os valores mínimo e máximo de x e y y3 como y1 mas produz escala de isovisualização y4 como y2 mas produz escala de isovisualização y5 como y1 mas plot2d pode mudar as fronteiras do esboço e os tiques dos eixos para se obter boas graduações Quando o botão de zoom é ativado este modo é usado y6 como y2 mas plot2d pode mudar as fronteiras do esboço e os tiques dos eixos para se obter boas graduações Quando o botão de zoom é ativado este modo é usado y7 como y5 mas a escala do novo esboço é misturada à escala corrente y8 como y6 mas a escala do novo esboço é misturada à escala corrente leg string É usado quando o primeiro caractere x do argumento strf é 1 leg possui a forma leg1leg2 onde leg1 leg2 etc são respectivamente as legendas das primeira segunda etc curvas O padrão é rect é usado quando o segundo caractere y do argumento strf é 1 3 ou 5 É um vetor linha de tamanho 4 e fornece as dimensões da moldura rectxminyminxmaxymax Descrição polarplot cria um esboço de coordenadas polares do ângulo theta versus o raio rho theta é o ângulo do eixo x ao vetor raio especificado em radianos rho é o comprimento do vetor raio especificado em unidades de espaçodedados Exemplos t 0012pi clfpolarplotsin7tcos8t clfpolarplotsin7t sin6tcos8t cos8t12 751 Name polylineproperties Descrição das propriedades da entidade Polyline poligonal Descrição A entidade Polyline uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para poligonais parent esta propriedade contém o manipulador para a raiz A raiz de uma entidade Polyline deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores polig onais não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão a poligonal é visível o valor da propriedade é on Se off a poligonal não é impressa na tela data esta propriedade contém o valor os valores para as coordenadas x e y O componente z deve ser adicionado no caso de eixos 3d é uma matriz de duas três colunas xyz determinando os pontos closed este valor determina se a poligonal é fechada ou não o valor pode ser on ou off o valor padrão depende da primitiva utilizada para criar a poligonal linemode este campo contém o valor padrão da propriedade linemode para a poligonal O valor pode ser on linha desenhada ou off nenhuma linha desenhada fillmode se o campo polylinestyle é diferente de 5 preenche o plano de fundo da curva com a cor definida pela propriedade background linestyle o valor da propriedade linestyle deve ser um inteiro em 1 6 1 significa linha sólida e os demais valores tipos diferentes de tracejados ver getlinestyle thickness este campo contém a propriedade de linha thickness espessura Deve ser um inteiro positivo arrowsizefactor este inteiro permite ajustar o tamanho das flechas desenhadas na poligonal O tamanho real das flechas é o produto entre a propriedade thickness e o fator de tamanho size factor polylinestyle esta propriedade ajusta vários modos de desenho de poligonais Se o valor é 0 ou 1 linhas são desenhadas utilizandose dois pontos consecutivos Se o valor é 2 a poligonal produz um esboço escada Dois pontos consecutivos são ligados por uma linha horizontal seguida de uma vertical Se o valor é 3 a poligonal produz um esboço de barras Para cada ponto xy dado uma linha vertical é desenhada de xy a x0 polylineproperties 752 Se o valor é 4 flechas são desenhadas entre dois pontos consecutivos Se o valor é 5 a poligonal é preenchida remendos Se o valor é 6 a poligonal é um objeto barra como no Matlab As propriedades barshift e barwidth comandam sua aparência foreground este campo contém o valor padrão da propriedade foreground primeiro plano utilizada para desenhar a poligonal O valor deve ser um índice de cor realtivo ao mapa de cores corrente background este campo contém a cor usada para preencher o plano de fundo da poligonal Deve ser um índice de cor relativo ao mapa de cores corrente interpcolorvector este campo contém os índices das cores utilizadas para preencher a poligonal quando a pro priedade interpcolormode é ajustada para on Define os intervalos dos índices do ma pa de cores a serem utilizados para preencher cada segmento Por exemplo o primeiro segmento será preenchido por todas as cores cujo índice está entre os dois primeiros elementos do vetor Só é aplicável se a poligonal é definida por 3 ou 4 pontos Logo o tamanho do vetor deve coincidir com esta dimensão interpcolormode este modo determina se é utilizada gradação interpolada par preencher a poligonal o valor pode ser on ou off Note que interpcolorvector deve ser definido antes e ajustar esta propriedade para on ver acima markmode este campo contém o valor padrão da propriedade markmode Deve ser on marcas desen hadas ou off nenhuma marca desenhada markstyle A propriedade markstyle é utilizada para selecionar o tipo de marca utilizada quando a pro priedade markmode é on O valor é um inteiro em 0 14 que significa ponto sinal de mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo rombo mais círculo asterísco quadrado triângulo para direita triângulo para esquerda e pentagrama marksizeunit este campo contém o valor padrão da propriedade marksizeunit property value Se marksizeunit for ajustado para point então o valor de marksize é diretamente dado em pontos Quando marksizeunit é ajustado para tabulated marksize é computado em relação ao array de tamanho de fonte logo seu valor deve ser um inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que plot2d e funções puras do Scilab utilizam o modo tabulated como padrão quando se utiliza a função plot o modo point é automaticamente habilitado marksize a propriedade marksize é utilizada para selecionar o tipo de tamanho das marcas quando a propriedade markmode é on O valor deve ser um inteiro entre 0 e 5 signficando 8pt 10pt 12pt 14pt 18pt e 24pt markforeground este campo contém o valor da propriedade markforeground que é a cor da borda das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor da propriedade markbackground que é a cor da face das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente polylineproperties 753 xshift este campo contém a compensação computada por uma chamada à função bar ou recomputa da por uma chamada à função barhomogenize e é usada para realizar uma boa representação de barras verticais Note que esta compensação é levada em conta para todos os outros polylinestyle A unidade é expressa nas coordenadas do usuário yshift este campo contém a compensação computada por uma chamada à função bar ou recomputa da por uma chamada à função barhomogenize e é usada para realizar uma boa representação de barras verticais Note que esta compensação é levada em conta para todos os outros polylinestyle TA unidade é expressa nas coordenadas do usuário zshift este campo contém a compensação que o usuário pode especificar Note que esta compensação é levada em conta para todos os polylinestyle A unidade é expressa nas coordenadas do usuário barwidth este campo determina a largura da poligonal selecionada quando sua propriedade polylinestyle é ajustada para modo de barra caso 6 a unidade é expressa nas coorde nadas do usuário clipstate este campo contém o valor da propriedade clipstate para a poligonal O valor de clipstate pode ser off significa que a poligonal não é recortada clipgrf significa que a poligonal é recortada fora da caixa dos eixos on significa que a poligonal é recortada fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções da poligonal a serem exibidas contudo o valor da propriedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade poligonal e recuperála Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds2222 xpolysin2pi055cos2pi055lines0 pgethdl obtendo o manipulador da entidade corrente aqui é a entidade poligonal pforeground2 pthickness3 pmarkstyle9 dpdatad10 0pdatad arotationangles0 45 pdata2012 sin2012pi pmarkmodeoff ppolylinestyle3 polylineproperties 754 plinestyle4 Ver Também set get delete xpoly xfpoly xpolys xfpolys graphicsentities Autor Djalel ABDEMOUCHE 755 Name rainbowcolormap Mapa de cores que varia como um de arcoíris cmaprainbowcolormapn Parâmetros n inteiro 1 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição rainbowcolormap computa um mapa de cores com n cores variando como um arcoíris Exemplos f scf plot3d1 fcolormap rainbowcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap springcolormap summercolormap whitecolormap wintercolormap 756 Name rectangleproperties Descrição de propriedades da entidade Rectangle retângulo Descrição A entidade Rectangle é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para retângulos preenchidos ou não parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Rectangle deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores rect angle não possuem galhos correntemente markmode este campo contém o valor padrão da propriedade markmode para a poligonal Deve ser on marcas desenhadas ou off nenhuma marca desenhada markstyle a propriedade markstyle é utilizada para selecionar o tipo de marca utilizada quando a pro priedade markmode é on O valor é um inteiro em 0 14 que significa ponto sinal de mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo rombo mais círculo asterísco quadrado triângulo para direita triângulo para esquerda e pentagrama marksizeunit este campo contém o valor padrão da propriedade marksizeunit property value Se marksizeunit for ajustado para point então o valor de marksize é diretamente dado em pontos Quando marksizeunit é ajustado para tabulated marksize é computado em relação ao array de tamanho de fonte logo seu valor deve ser um inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que xrect como padrão quando se utiliza a função tabulated como padrão quando se utiliza a função plot o modo point é automati camente habilitado marksize A propriedade marksize é utilizada para escolher o tamanho das marcas quando a propriedade markmode é on Deve ser um valor inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt markforeground este campo contém o valor da propriedade markforeground que é a cor da borda das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor da propriedade markbackground que é a cor da face das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente linemode este campo contém o valor padrão da propriedade linemode para a poligonal O valor pode ser on linha desenhada ou off nenhuma linha desenhada fillmode Se o valor da propriedade fillmode é on o retângulo é preenchido com a cor de primeiro plano markmode também deve ter valor off Senão o valor da propriedade é off apenas a forma o contorno do retângulo é desenhado utilizandose a cor de primeiro plano linestyle a propriedade linestyle deve ser um inteiro em 1 6 1 stands significa linha sólida o restante seleciona tracejados rectangleproperties 757 thickness este campo contém o valor padrão da propriedade thickness espessura da linha Deve ser um inteiro positivo foreground este campo contém a cor utilizada para desenhar a linha de contorno do retângulo Seu valor deve ser um índice de cor relativo ao mapa de cores corrente background este campo contém a cor utilizada para preencher a parte interna do retângulo Seu valor deve ser um índice de cor relativo ao mapa de cores corrente data esta propriedade retorna as coordenadas do ponto superior esquerdo do retângulo sua al tura e largura em unidades de dados dos eixos O resultado é uma matriz xleftyup zupwidthheight visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o retângulo é visível a propriedade é on Se off o retângulo não é exibido na tela clipstate este campo contém o valor da propriedade clipstate para o retângulo o valor de clipstate pode ser off ignifica que o retângulo não é recortado clipgrf significa que o retângulo é recortado fora da caixa dos eixos on significa que o retângulo é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox property Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções do retângulo a ser exibido contudo o valor da pro priedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade retângulo e recuperála Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds2222 xrect1122 rgethdlobtendo o manipulador da entidade corrente aqui a entidade Rectangle rtype rparenttype rforeground13 rlinestyle2 rfillmodeon rbackgroundcolorred rclipbox1 11 1 rdata3 412 12 rectangleproperties 758 rdata1 212 12 rclipstateoff Ver Também set get delete xrect xfrect xrects graphicsentities Autor Djalel ABDEMOUCHE 759 Name relocatehandle Movimentação de manipuladores dentro da hierarquia gráfica relocatehandle movedHandles parent Parâmetros movedHandles vetor de manipuladores realocados parent nova raiz dos manipuladores Descrição A função relocatehandle permite mover manipuladores das suas localizações em uma hierarquia gráfica para outra localização Todas as entidades são realocadas sob o mesmo manipulador raiz es pecificado pelo parâmetro parent Já que não são todos os manipuladores que são compatíveis com todos os outros existem algu mas restrições ao se realocar manipuladores Por exemplo não é permitido mover um manipulador Axes sob um manipulador Polyline Para mais informações sobre compatibilidade veja a página graphicsentities Esta rotina é particularmente útil para se mover um objeto de uma entidade Axes para outra ou para se move objetos Axes de uma entidade Figure para outra Exemplos x 010 esboçando uma primeira poligonal plotxx2 axes1 gca poly1 gce esboçando uma segunda em outra janela scf plot xx axes2 gca poly2 gce poly2bis copy poly2 criando uma cópia da poligonal pondo ambas as poligonais na mesma janela relocatehandle poly2bis axes1 Ver Também graphicsentities copy delete swaphandles Autor JeanBaptiste Silvy 760 Name replot redesenha a janela de gráficos corrente com novas fronteiras replotrecthandle Parâmetros rect vetor linha de tamanho 4 handle argumento opcional Manipuladores do tipo Axes para selecionar uma ou várias entidades Axes válidas Disponível apenas no novo modo de gráficos Descrição replot é utilizado para redesenhar o conteúdo da janela de gráficos atual com novas fronteiras definidas por rectxminyminxmaxymax Sob a sintaxe de gráficos antiga funciona ape nas com o driver Rec Sob o novo modo de gráficos esta transformação pode ser aplicada a eixos específicos fornecidos por manipuladores gráficos Axes via o argumento handle Se handle não for especificado as novas fronteiras são aplicadas aos eixos correntes da figura corrente A transformação muda os valores de databounds para estes eixos Note que a propriedade de eixos tightlimits também deve ser ajustada para on para selecionar estritamente estas fronteiras ver axesproperties Exemplos backupstyle primeiro exemplo x0012pi plot2dxsinx replot11102 segundo exemplo xdelwinsid plot esboçando demonstração fgcf replot11102fchildren1 especificando o valor do manipulador dos eixos replot3284fchildren2 Ver Também xbasr xbasc clf Autor JPhC 761 Name rgb2name Retorna o nome de uma cor namesrgb2namergb namesrgb2namergb Parâmetros rgb RGB vermelho verde azul valores inteiros de uma cor rgb vetor RGB de valores inteiros de uma cor names nomes da cor Descrição rgb2name retorna o nome da cor correspondente aos valores RGB dados pelo seu argumento Um vetor de nomes de cores pode ser retornado se a cor possui mais de um nome r g e b devem ser inteiros entre 0 e 255 correspondentes aos componentes das cores vermelho verde e azul Como de uso 0 significa intensidade nenhuma e 255 significa intensidade total da cor Os valores RGB também podem ser fornecidos pelo vetor rgb Se não for encontrada nenhuma cor é retornado A lista de todas as cores conhecidas é dada por colorlist Exemplos rgb2name255128128 rgb2name255 215 0 retorna a cor de número 10 do mapa de cores corrente acha seu nome cmapgetgcfcolormap rgb2namecmap10255 Ver Também color colorlist name2rgb 762 Name rotate rotação de um conjunto de pontos xy1rotatexythetaorig Parâmetros xy matriz de tamanho 2 xy1 matriz de tamanho 2 theta real ângulo em radianos o valor padrão é 0 orig centro de rotação o valor padrão é 00 Descrição rotate executa a rotação com o ângulo theta xy1i Mtheta xy i orig onde M é a matriz de rotação correspondente Exemplos xsetech00111111 xy00110sin0011010 for i2pi01010 xy1rotatexyi xpolyxy11xy12lines end 763 Name rotateaxes Rotação interativa de um manipulador Axes rotateaxes rotateaxesh Parâmetros h manipulador Axes ou Figure Especifica sobre qual eixo se efetuará a rotação Descrição rotateaxes é utilizado para realizar uma rotação interativa sobre um objeto Axes Quando a função é chamada pedese ao usuário que clique duas vezes na janela gráfica O primeiro clique inicializa uma rotação e o segundo termina Se um manipulador Axes for especificado como argumento de entrada a rotação será aplicada sobre ele Se um manipulador Figure for especificado o primeiro clique determina qual objeto Axes rota cionar Se a função for chamada sem argumento a rotação se aplicará sobre a Figura corrente Exemplos clf criando dois pares de eixos em uma figura subplot2 1 1 plot2d subplot2 1 2 plot3d girando apenas o segundo axes2 gca rotateaxesaxes2 girando o selecionado rotateaxes ou rotateaxesgcf Ver Também zoomrect axesproperties Autor JeanBaptiste Silvy INRIA 764 Name rubberbox Caixa tipo liga de borracha para seleção de um retângulo finalrectbtnrubberbox finalrectbtnrubberboxinitialrect finalrectbtnrubberboxeditionmode finalrectbtnrubberboxinitialrect editionmode Parâmetros initialrect vetor de duas a quatro entradas Com quatro entradas fornece o retângulo inicial definido por xesquerdo ytopo largura altura Com duas entradas largura e altura são supostas 0 editionmode um booleano se editionmodet um aperto de botão seleciona a primeira quina soltar se leciona a quina oposta Se editionmode f aperto de botão ou clique seleciona a primeira quina um clique é requerido para selecionar a quina oposta O valor padrão é editionmodef finalrect um retângulo definido por xesquerdo ytopo largura altura btn um inteiro o número do botão do mouse clicado Descrição rubberboxinitialrect trilha uma caixa liga de borracha na janela de gráficos corrente seguindo o mouse Quando um botão é clicado rubberbox retorna a definição dos retângulos finais finalRect Se o argumento initialrect estiver presente o usuário deve clicar para fixar a posição da quina inicial Exemplos xsetechfrect00100100 xyxclickrrubberboxxy3010 xrectr rrubberbox Ver Também xrect xrects xclick xgetmouse dragrect 765 Name sca Ajusta a entidade de eixos corrente ascaa Parâmetros a o manipulador da entidade Axes de eixos Descrição scaa é usado para ajustar a entidade Axes corrente ver graphicsentities como sendo aquela apontada pelo manipulador a As funções de esboço geralmente utilizam a entidade de eixos corrente Exemplos clf a1newaxes a1axesbounds001005 t00120 plottacoshtr a2newaxes a2axesbounds0051005 x0014 plotxsinhx scaa1 tornando os primeiros eixos correntes plottasinhtg legendacoshasinh scaa2 tornando os segundos eixos correntes legendsinh Ver Também subplot gda newaxes Autor S Steer INRIA 766 Name scaling transformação afim de um conjunto de pontos xy1scalingxyfactororig Parâmetros xy1 matriz de tamanho 2 xy matriz de tamanho 2 factor escalar real coeficiente da transformação linear orig vetor de deslocamento o valor padrão é 00 Descrição scaling executa uma transformação afim de um conjunto de pontos definidos pelas coordenadas xy xy1i factor xyi orig 767 Name scf Ajusta a janela de figura gráfica corrente f scf f scfh f scfnum Parâmetros h o manipulador da figura num identificador da figura f manipulador da figura corrente Descrição A figura corrente é o destino do desenho gráfico A função scf permite modificar esta figura corrente ou criar uma caso ainda não exista scfnum ajusta a figura com figureidnum como figura corrente Se ainda não existir ela é criada scfh ajusta a figura apontada pelo manipulador h ajusta a figura apontada pelo manipulador scf é equivalente a scfmaxwinsid1 Pode ser utilizado para criar uma nova janela de gráficos Exemplos f4scf4 criando figura com id4 e a torna a figura corrente f0scf0 criando figura com id0 e a torna a figura corrente plot2d desenhando na figura corrente id0 scff4 ajustando a primeira figura criada como sendo a corrente plot3d desenhando na figura corrente id4 Ver Também set get gcf clf getfigurehandle graphicsentities Autor S Steer INRIA 768 Name sd2sci estrutura grmenu para conversor de instrução Scilab txtsd2scisd sz orig Parâmetros sd estrutura de dados construída por grmenu sz vetor de números ou strings com dois componentes fornece os fatores de zoom x e y orig vetor de números ou strings fornece o vetor translação da origem Descrição Dada uma estrutura de dados sd gerada por grmenu sd2sci forma um vetor de instruções do Scilab correspondente ao gráfico editado por grmenu Os parâmetros opcionais sz e orig permitem ampliar e deslocar o gráfico inicial Se sz ou orig são fornecidos por strings as instruções geradas são relativas a expressões formais Ver Também execstr Autor Serge Steer INRIA 1988 769 Name sda Ajusta eixos padrões sda a gda setadefaultvalues1 Parâmetros a manipulador dos eixos padrões Descrição Esta rotina reajusta o os eixos modelos para valores padrões Exemplos x0012pi fgetdefaultfigure obtendo o manipulador da figura modelo agetdefaultaxes obtendo o manipulador dos eixos modelo ajustando suas propriedades ffiguresize1200 900 ffigureposition0 0 abackground4 aboxoff a ticscolor5 alabelsfontcolor25 alabelsfontsize4 asubtics7 3 axlocationmiddle aylocationmiddle atightlimitson athickness2 agrid1 24 subplot221 plot2dx2sinx subplot222 plot2dx62cosx7 2cosx9 cos2x 2sin3x123 4 sda obtendo os valores padrões do modelo dos eixos subplot223 plot2dx2sinx subplot224 plot2dx62cosx7 2cosx9 cos2x 2sin3x123 4 xdel0 plot2dx2sinx Ver Também sdf gda gdf set graphicsentities Autor Djalel ABDEMOUCHE 770 Name sdf Ajusta figura padrão sdf f gdf setfdefaultvalues1 Parâmetros f manipulador da figura padrão Descrição Esta rotina reajusta a figura modelo para valores padrões Exemplos x0012pi fgetdefaultfigure obtendo o manipulador da figura modelo agetdefaultaxes obtendo o manipulador dos eixos modelos ajustando suas propriedades fbackground4 fautoresizeoff ffiguresize400 300 faxessize600 400 ffigureposition0 1 axlocationtop aylocationleft for i16 xsetwindowi criando figura com identificador i plot2dxsinx cosxi i xclick if i 4 sdf end obtendo os valores padrões da figura modelo end Ver Também sda gdf gda set graphicsentities Autor Djalel ABDEMOUCHE 771 Name secto3d Conversão de superfícies 3d mxsecto3dseclistnpas msecto3dseclist x Parâmetros seclist uma lista cujos elementos são matrizes 2 npas um inteiro m uma matriz x um vetor Descrição Considerando uma superfície dada através de uma lista seclist de secções no plano xz m xsecto3dseclist npas retorna uma matriz m que contém a discretização regular da superfície A iésima linha da matriz m corresponde à iésima secção A jésima coluna da matriz m corresponde ao xj Cada secção seclisti é descrita por uma matriz 2 que fornece respectivamente as coorde nadas x e z de pontos msecto3dseclist xneste caso o vetor x fornece a discretização do eixo x para todas as secções Ver Também plot3d Autor Steer S 772 Name segsproperties Descrição das propriedades da entidade Segments de segmentos Descrição A entidade Segments é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para um conjunto de segmentos ou setas coloridas parent esta propriedade contém o manipulador da raiz A raiz de uma entidade de Segments deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores Segs não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o os segmentos são visíveis a propriedade é on Se off os segmentos não são exibidos na tela data este campo é uma matriz de duas três xyz que fornece as coordenadas das extremi dades dos segmentos Se xvmatrixx21 e yvmatrixy21 então xvk e yvk são as extremidades dos segmentos de número k linemode este campo contém o valor padrão da propriedade linemode para os segmentos O valor pode ser on linha desenhada ou off nenhuma linha desenhada linestyle O valor da propriedade linestyle deve ser um inteiro em 0 6 0 significa linha sólida o restante seleciona tracejados Esta propriedade se aplica a todos os segmentos thickness este campo contém o valor da propriedade thickness espessura para todos os segmentos Seu valor deve ser um inteiro nãonegativo arrowsize fator que especifica o tamanho das cabeças das setas Com um valor negativo o tamanho também depende do comprimento da seta Para desenhar um segmento o valor deve ser ajustado para 0 segscolor este campo especifica a cor a ser utilizada para desenhar cada segmento Cada elemento é um índice de cor relativo ao mapa de cores corrente markmode este campo contém o valor padrão da propriedade markmode para a poligonal Deve ser on marcas desenhadas ou off nenhuma marca desenhada markstyle a propriedade markstyle é utilizada para selecionar o tipo de marca utilizada quando a pro priedade markmode é on O valor é um inteiro em 0 14 que significa ponto sinal de mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo rombo mais círculo asterísco quadrado triângulo para direita triângulo para esquerda e pentagrama marksizeunit este campo contém o valor padrão da propriedade marksizeunit Se marksizeunit for ajustado para point então o valor de marksize é diretamente dado em pontos Quando segsproperties 773 marksizeunit é ajustado para tabulated marksize é computado em relação ao array de tamanho de fonte logo seu valor deve ser um inteiro em 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que plot2d e funções puras do Scilab utilizam o modo tabulated como padrão quando se utiliza a função plot o modo point é automaticamente habilitado marksize a propriedade marksize é utilizada para selecionar o tipo de tamanho das marcas quando a propriedade markmode é on O valor deve ser um inteiro entre 0 e 5 signficando 8pt 10pt 12pt 14pt 18pt e 24pt markforeground este campo contém o valor da propriedade markforeground que é a cor da borda das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor da propriedade markbackground que é a cor da face das marcas O valor deve ser um índice de cor relativo ao mapa de cores corrente clipstate este campo contém o valor da propriedade clipstate para os segmentos O valor de clipstate pode ser off significa que os segmentos não são recortados clipgrf significa que os segmentos são recortados fora da caixa dos eixos on significa que os sementos são recortada fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções dos segmentos a serem exibidas contudo o valor da propriedade clipstate será alterado userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade de segmentos e recuperála Exemplos agetcurrentaxesobtendo o manipulador dos novos eixos criados adatabounds10101010 x2pi078 xv2sinx9sinx yv2cosx9cosx xsegsxvyv18 sachildren sarrowsize1 ssegscolor1522 for j12 for i18 hsdatai2j sdatai2jsdatai21j sdatai21j h end end segsproperties 774 ssegscolor5 ajustando todas as cores para 5 sclipbox4488 athickness4 xrectsclipbox Ver Também set get delete xsegs graphicsentities Autor Djalel ABDMOUCHE 775 Name set Ajusta um valor de propriedade de uma objeto entidade gráfica ou de um objeto Interface do Usuário User Interface setpropval sethprop sethpropval hpropval Parâmetros h manipulador da entidade da qual a propriedade nomeada se deseja ajustar h pode ser um vetor de manipuladores em tal caso serão ajustados valores de propriedades para todos os objetos identificados por h prop string nome da propriedade a ser ajustada val valor a ser dado à propriedade Descrição Esta rotina pode ser utilizada para se recuperar o valor de uma propriedade especificada de uma en tidade de gráficos ou objeto GUI Neste caso é equivalente a se usar o operador ponto em um manipulador Por exemplo sethbackground5 é equivalente a hbackground 5 Nomes de propriedades são strings O tipo do valor ajustado dependo do tipo do manipulador e da propriedade Para obter a lista de todas as propriedade existentes ver graphicsentities ou uicontrol para objetos de Interface do Usuário set também pode ser chamado com apenas uma propriedade como argumento Neste caso a pro priedade deve ser uma das seguintes currententity or hdl setcurrententityh ou sethdlh ajusta uma nova entidade como a cor rente Neste caso o valor deve ser um manipulador gráfico currentfigure setcurrentfigurefig ajusta uma nova figura como a corrente É equivalente a scf Neste caso o valor deve ser um manipulador FIgure currentaxes setcurrentaxesaxes ajusta novos eixos como os correntes É equivalente a sca Neste caso o valor deve ser um manipulador Axes set também pode ser chamado com manipuladores gráficos e com propriedades como argumen tos O manipulador deve ser de uma figura padrão ou de eixos padrões A propriedade deve ser defaultvalues Neste caso a entidade padrão é reajustada para os valores que possuía na inicialização do Scilab setdefaultvaluesh equivale a sda ou sdf Exemplos set 776 clf setautoclearoff Exemple of a Plot 2D x2012pi plot2dx3sinx1 cos2x1 2 agetcurrentaxes p1achildrenchildren1 p2achildrenchildren2 ajustando as propriedades nomeadas para os valores especificados nos objetos setp2foreground13 setp2polylinestyle2 setatightlimitson setaboxoff setasubtics 7 0 setaylocationmiddle setp2thickness2 setp1markmodeon setp1markstyle3 plot2dx2x220 p3 achildren1children seta p1 p2 p3foreground5 Ver Também get delete copy move graphicsentities uicontrol Autor Djalel ABDEMOUCHE 777 Name seteventhandler Define um gerenciador de eventos para uma janela gráfica seteventhandlersfunname seteventhandler Parâmetros sfunname string O nome da função do Scilab com a qual se pretende gerenciar os eventos Descrição A função permite que o usuário defina um gerenciador de eventos particular para janela gráfica cor rente seteventhandler remove o gerenciador Para mais informações sobre o gerenciador de eventos veja a página event handler functions Exemplos function myeventhandlerwinxyibut if ibut1000 then returnend xyxchangexyi2f xinfomsprintfEvento de código d na posição do mouse é ffibutxy endfunction plot2d seteventhandlermyeventhandler agora mova o mouse sobre a janela gráfica pressione e libere as teclas com shift pressionado ou não e com Ctrl pressionado ou não pressione um botão espere um pouco e libere pressione e libere um botão clique duas vezes em um botão seteventhandler suprimindo o gerenciador de eventos Ver Também addmenu xgetmouse xclick xchange event handler functions figureproperties 778 Name showpixmap Envia o buffer de pixmap à tela showpixmap Descrição Se a propriedade pixmap de uma janela gráfica é on os desenhos são enviados à memória pixmap ao invés da tela de exibição A instrução showpixmap envia o pixmap à tela O modo pixmap pode ser usado para se obter animações suaves Esta propriedade pode ser encontrada entre os campos de entidades da figura ver figureproperties Exemplos fgcffpixmapon ajustando o modo pixmap agcaadatabounds0 0 10 10 construindo dois retângulos xrects010115r1gcer1r1children xrects011113r2gcer2r2children laço de animação for k11000 desenhando os retângulos no buffer pixmap mover1001001mover2001001 exibindo o buffer pixmap showpixmap end Ver Também figureproperties clearpixmap Autor Serge Steer INRIA 779 Name showwindow Restaura uma janela de gráficos showwindowfigure Parâmetros figure número ou manipulador da figura a ser exibida Descrição Sem parâmetros showwindow restaura a janela de gráficos corrente mesmo se estiver iconificada Em caso contrário restaura a janela especificada por seu número ou por seu manipulador Se nenhuma janela existir uma é criada Autor JPhC 780 Name springcolormap Mapa de cores com tons da primavera magenta amarelo cmapspringcolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição springcolormap computa um mapa de cores com n cores variando de magenta a amarelo Exemplos f scf plot3d1 fcolormap springcolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap summercol ormap whitecolormap wintercolormap 781 Name square ajusta escalas para esboço isométrico muda o tamanho da janela squarexminyminxmaxymax Parâmetros xminxmaxyminymax quatro valores reais Descrição square é usado para definir escalas isométricas nos eixos x e y Os valores requeridos xmin xmax ymin ymax são os limites da moldura de gráficos e square muda as dimensões da janela de gráficos para se obter um esboço isométrico square ajusta as escalas gráficas correntes e pode ser usado em conjunção com rotinas de gráfico que requerem a escala de gráficos corrente por exemplo fstrfx0z em plot2d Exemplos t0012pi plot2dsintcost xbasc square1111 plot2dsintcost xsetdefault Ver Também isoview xsetech Autor Steer S 782 Name stringbox Computa o retângulo de fronteira de um texto ou rótulo rect stringbox string x y angle fontStyle fontSize rect stringbox Handle Parâmetros rect uma matriz 2x4 contendo as quatro coordenadas dos vértices do retângulo de fronteira string matriz de strings a ser encerrada xy escalares reais coordenadas do ponto inferior esquerdo dos strings angle ângulo de rotação dos strings em sentido horário e em graus ao redor do ponto xy fonStyle inteiro especificando o tipo da fonte fontSize inteiro especificando o tamanho da fonte Handle um manipulador gráfico do tipo Text ou Label Descrição stringbox retorna os vértices de um retângulo de fronteira de um texto ou rótulo ou um string que será exibido de certo modo As coordenadas são dadas com a escala gráfica corrente O primeiro vértice corresponde às coordenadas do texto xy ponto superior esquerdo sem rotação os vértices seguintes são dados em sentido horário na matriz resultante O resultado pode ser impreciso com um driver Postscript Exemplos exibindo eixos axes gca axesaxesvisible on axesdatabounds 1 1 10 10 exibindo rótulos para eixos xtitle stringbox X Y obtendo a caixa de fronteixa do rótulo X stringbox axesxlabel imprimindo um string str Scilab não é Skylab xstring 4 9 str modificando o texto stringbox 783 e gce efontangle 90 efontsize 6 efontstyle 7 ebox on obtendo sua caixa de fronteira stringbox e ou rect stringbox str 4 9 90 7 6 clicando e descobrindo se o texto foi acertado hit xclick hit hit 2 3 if hit1 rect11 hit1 rect12 hit2 rect22 hit2 rect23 then dispVocê acertou o texto else dispVocê errou end Ver Também xstring xstringl xstringb Autor JeanBaptiste Silvy 784 Name subplot divide uma janela de gráficos em uma matriz de subjanelas subplotmnp subplotmnp Parâmetros mnp inteiros positivos mnp um inteiro com notação decimal mnp Descrição subplotmnp ou subplotmnp parte a janela de gráficos em uma matriz mporn de subjanelas e seleciona a pésima subjanela para esboçar o gráfico corrente O número uma subjanela nas matrizes é contado linha por linha ie a subjanela correspondente ao elemento ij da matriz tem número i1n j Exemplos subplot221 plot2d subplot222 plot3d subplot223 param3d subplot224 hist3d Ver Também plot2d plot3d xstring xtitle 785 Name summercolormap Mapa de cores com tons do verão verde amarelo cmapsummercolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição summercolormap computa um mapa de cores com n cores variando do verde para o amarelo Exemplos f scf plot3d1 fcolormap summercolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap whitecolormap wintercolormap 786 Name surf Esboço de superfície 3d surfZGlobalProperty surfZcolorGlobalProperty surfXYZcolorGlobalProperty surfaxeshandle Parâmetros Z uma matriz real definindo as alturas da superfície Não pode ser omitida O dado Z é uma matriz mxn XY dois vetores ou matrizes reais sempre ajustados juntos estes dados definem um novo grid padrão Estes novos componentes X e Y do grid devem coincidir com as dimensões de Z ver a descrição abaixo color um matriz de reais opcional definindo valores de cores para cada ponto XjYi do grid ver descrição abaixo GlobalProperty esta propriedade rerpresenta uma seqüência de pares de sentenças PropertyNamePropertyValue que definem propriedades globais de objetos apli cadas a todas as curvas criadas neste esboço Para uma completa visualização das propriedades disponíveis veja GlobalProperty axeshandle este argumento opcional força os eixos a aparecerem dentro dos eixos selecionados dados por axeshandle ao invés dos eixos correntes ver gca Descrição surf desenha uma superfície parametrizada colorida utilizando um grid retangular definido pelas coordenadas X e Y se XY não forem especificados este grid é determinado utilizandose as dimensões da matriz Z em cada ponto deste grid uma coordenada Z é dada utilizandose uma ma triz Z apenas dados obrigatórios surf foi criada para lidar melhor com a sintaxe do Matlab Para melhorar a compatibilidade gráfica usuários do Matlab devem utilizar surf ao invés de plot3d Especificação de entrada de dados Neste parágrafo e para sermos mais claros não mencionaremos os argumentos opcionais de Glob alProperty ojá que eles não interferem na entrada de dados exceto pelas propriedades Xdata Ydata e Zdata ver GlobalProperty É assumido que todos estes argumentos opcionais po dem estar presentes também Se Z é a única matriz especificada surfZ esboça a matriz Z versus o grid definido por 1sizeZ2 ao longo do eixo x e 1sizeZ1 ao longo do eixo Se uma tripla XYZ for fornecida Z deve ser uma matriz de sizeZ mxn X or Y can be a um vetor se X for um vetor lengthXn Respectivamente se Y for um vetor lengthYm b uma matriz neste caso sizeX ou sizeY deve ser igual a sizeZ Especificação de entrada de cores surf 787 Como citado acima a superfície é criada sobre um gride retangular de apoio Consideremos duas variáveis independentes i e j tais que Este grid retangular imaginário é utilizado para se contruir o suporte da superfície real sobre o plano XY De fato os dados XY e Z possuem o mesmo tamanho mesmo se X ou Y for um vetor ver abaixo e podem ser considerados como três funções xij yij e zij especificando a superficie desejada Se X ou Y forem vetores eles são internamente tratados para produzir boas matrizes de dimensões correspondentes às dimensões da matriz Z e o grid é forçosamente uma região retangular Considerando as três funções xij yij e zij a porção da superfície definida entre dois i e j consecutivos é chamada remendo Por padrão quando nenhuma matriz de cores é adicionada a uma chamada a surf o parâmetro de cor é ligado o dado Z Quando uma matriz de cores color é dada pode ser aplicada aos remendos de duas formas diferentes nos vértices ou no centro de cada remendo É por isto que se Z é uma matriz mxn a dimensão da matriz color C pode ser mxn uma cor definida por vértice ou m1xn1 uma cor definida por remendo A representação de cores também varia quando se especifica algumas GlobalProperties propriedades globais A propriedade FaceColor ajusta o padrão de gradação pode ser interp ou flat mo do padrão Quando interp é selecionado é realizado uma interpolação bilinear de cores no re mendo Se sizeC é igual a sizeZ1 ie for fornecida apenas uma cor ao remendo então a cor dos vértices definindo o remendo é ajustada para a dada cor do remendo Quando flat modo padrão é habilitado é utilizada uma representação de cores de facetadas uma cor por remendo Se sizeC é igual a sizeZ ie foi fornecida apenas uma cor por os vértices as últimas linha e coluna de C são ignoradas Os argumentos GlobalProperty devem ser usados para customizar a superfície Aqui está uma breve descrição de como funcionam GlobalProperty esta opção pode ser utilizada para especificar como todas as superfícies serão desenhadas Deve sempre ser um par de sentenças constituidos de um string definindo PropertyName nome da propriedade e seu valor associado PropertyValue que pode ser um inteiro ou outra coisa dependendo do tipo de PropertyName Note que você pode ajustar múltiplas propriedades a cor da face e da borda dados de cores mapeamento de dados de cores cor do marcador plano surf 788 de fundo e primeiro plano visibilidade recorte espessura das bordas da superfície ver Glob alProperty Note que todas essas propriedades podem ser reajustadas através das propriedades da entidade superfície ver surfaceproperties Observações Por padrão esboços sucessivos de superfície são superpostos Para limpar o esboço anteirior use clf Para habilitar o modo autoclear limpeza automática como modo padrão edite seus eixos padrões fazendo dagda daautoclear on Entre com o comando surf para visualizar uma demonstração Exemplos inicialização de Z Z 00001 00013 00053 00299 01809 02465 01100 00168 00008 00000 00005 00089 00259 03673 18670 24736 10866 01602 00067 00000 00004 00214 01739 03147 40919 64101 27589 02779 00131 00020 00088 00871 00364 18559 14995 22171 02729 08368 02016 00130 00308 04313 17334 01148 30731 04444 26145 24410 04877 00301 00336 04990 23552 21722 08856 00531 26416 24064 04771 00294 00137 01967 08083 02289 33983 31955 24338 12129 02108 00125 00014 00017 03189 27414 71622 71361 31242 06633 00674 00030 00002 00104 01733 10852 26741 26725 11119 01973 00152 00005 00000 00012 00183 01099 02684 02683 01107 00190 00014 00000 superfície simples surfZ note que X e Y são determinados pelas dimensões de Z a mesma superfície com faces vermelhas e bordas azuis scf2 nova figura de número 2 surfZfacecolrededgecolblu inicialização de X e Y NB aqui X tem as mesmas linhas e Y tem as mesmas colunas X 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 Y 30000 30000 30000 30000 30000 30000 30000 30000 30000 30000 23333 23333 23333 23333 23333 23333 23333 23333 23333 23333 16667 16667 16667 16667 16667 16667 16667 16667 16667 16667 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 surf 789 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 03333 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 16667 16667 16667 16667 16667 16667 16667 16667 16667 16667 23333 23333 23333 23333 23333 23333 23333 23333 23333 23333 30000 30000 30000 30000 30000 30000 30000 30000 30000 30000 exemplo 1 scf3 surfXYZ exemplo 2 como você pode ver o grid não é necessariamente retangular scf4 X14 15 Y14 35 Z14 2 surfXYZ exemplo 3 X e Y são vetores mesmo comportamento que a amostra 1 com vetores o grid é inevitavelmente retangular scf5 nova figura de número 5 X 30000 23333 16667 10000 03333 03333 10000 16667 23333 30000 YX surfXYZ exemplos com LineSpec e GlobalProperty xdelwinsid destruindo todas as figuras existentes surfZZ5 array de cores especificado egce ecdatamappingdirect o padrão é scaled relativo ao mapa de cores colormap ecolorflag3 modo de gradação interpolada O padrão é 4 modo flat para surf scf2 surfXYZcolordaones1010edgecocyamarkerpentamarkersiz20markeredgyelydata5665 scf3 surfZcdatamappingdirect scf4 surfZfacecolinterp interpolated shading mode colorflag 3 scf10 axfig10gca scf11 surfaxfig10Zydat100109markerdmarkerfacgreenmarkeredgyel draw onto the axe of figure 10 xdelwinsid Ver Também plot2d clf xdel delete LineSpec GlobalProperty Autor FLeray 790 Name surfaceproperties Descrição das propriedades da entidade Surface superfície Descrição A entidade Surface é uma folha das hierarquia de entidades gráficas Duas classes aparecem sob este tipo de entidade Plot3d e Fac3d de acordo com a função de esboço ou com o modo como os dados foram inseridos As entidades Fac3d e Plo3d são semelhantes mas Fac3d é mais completa e aceita mais opções que Plot3d Para sempre ter entidades Fac3d simplesmente use genfac3d para préconstruir matrizes antes de usar os comandos plot3d ou use o comando surf Aqui estão as propriedades contidas em uma entidade superfície parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Surface pode ser Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores de superfície não possuem galhos correntemente visible este campo contém o valor padrão da propriedade visible para a entidade Pode ser on ou off Por padrão superfícies são visíveis o valor da propriedade é on Se for off os gráficos 3d não são exibidos na tela surfacemode este campo contém o valor padrão da propriedade surfacemode para a superfície Pode ser on superfície desenhada ou off nenhuma superfície desenhada foreground se colormode 0 contém o índice da cor a ser usada nas bordas Se não foreground não é usado O valor foreground deve ser um índice inteiro de cor relativo ao mapa de cores corrente thickness este campo contém o valor de thickness espessura das linhas usadas para desenhar facetas ou contornos Deve ser um inteiro positivo markmode este campo contém o valor padrão da propriedade markmode para a superfície Seu valor pode ser on marcas desenhadas ou off marcas não desenhadas markstyle o valor da propriedade markstyle é usado para selecionar o tipo de marca usada quando a propriedade markmode é on O valor deve ser um inteiro no intervalo 0 14 que significa ponto mais cruz estrela rombo preenchido rombo triângulo para cima triângulo para baixo rombo mais círculo asterísco quadrado trângulo para direita triângulo para esquerda e penta grama marksizeunit este campo contém o valor padrão da propriedade marksizeunit Se marksizeunit é ajustado para point então o valor de marksize é dado diretamente em pontos Quando marksizeunit é ajustado para tabulated marksize é computado de acordo com o array de tamanho de fonte logo seu valor deve ser um inteiro no intervalo 0 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt Note que plot3d e funções puras do Scilab usam o modo tab ulated como padrão quando se utiliza as funções surf ou plot para linhas 2d o modo point é automaticamente habilitado surfaceproperties 791 marksize a propriedade marksize é utilizada para selecionar o tamanho de fonte das marcas quando a propriedade markmode está on O valor deve ser um inteiro entre 0 e 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt markforeground este campo contém o valor padrão da propriedade markforeground que é a cor da borda das marcas Seu valor deve ser um índice de cor relativo ao mapa de cores corrente markbackground este campo contém o valor padrão da propriedade markbackground que é a cor da face das marcas Seu valor deve ser um índice de cor relativo ao mapa de cores corrente data este campo define uma estrutura de dados tlist do tipo 3d composto de índices de uma linha e uma coluna de cada elemento como as coordenadas x y e z contidas respectivamente em dataxdatay e dataz O campo complementar datacolor está disponível caso um vetor ou matriz reais de cores seja especificado Se nenhum for datacolor não é listado A superfície é pintada de acordo com as propriedades colormode e colorflag colormode um inteiro no intervalo sizecolormap sizecolormap definindo a cor da faceta quando o valor de colorflag é 0 Como dito antes se colormode 0 as bordas são desenhadas usando a cor foreground Se colormode é ajustado para 0 uma malha das superfície é desenhada faces da frente não têm cores Finalmente quando colormode 0 as faces da frente são pintadas com a cor colormode mas nenhuma borda é exibida colorflag este campo é usado para definir o algoritimo usado para ajustar as cores das facetas Note que as regras em colormode foreground e hiddencolor ainda são aplicadas nesse caso colorflag 0 Todas as facetas são pintadas usandose o índice de cores e o método definido por colormode ver acima colorflag 1 Todas as facetas são pintadas utilizandose um índice de cor por faceta proporcional a z O valor mínimo de z é pintado utilizandose o índice 1 enquanto o valor máximo de z é pintado utilizandose o índice mais alto As bordas das facetas pode ser adicionalmente desenhadas dependendo do valor de colormode ver acima Os três casos restantes colorflag 23 or 4 só estão disponíveis para a entidade Fac3d Então o valor de datacolor é usado para ajustar cores para as facetas índices do mapa de cores corrente se existirem Se não o colormode corrente é utilizado para pintar as facetas colorflag 2 flat shading Todas as facetas são pintadas utilizandose o índice de cor dado na propriedade datacolor uma cor por faceta é necessária Dois são os casos possíveis datacolor contém um vetor color vector se colori for positivo fornece a cor da faceta i e a borda da faceta é desenhada com o estilo de linha e cor correntes Se colori for negativo o a cor de identificador colori é usado e a borda da faceta não é desen hada datacolor contém uma matriz de cores de tamanho nfn onde n significa o número de facetas e nf o número de pontos definindo a faceta poligonal Para os vértices nf definindo surfaceproperties 792 cada faceta o algoritmo computa o valor médio do índice de cores da matriz de índices de cores os nf vértices da mesma faceta terão o mesmo valor de índice de cor colorflag 3 interpolated shading Pinta as facetas por interpolação das cores dos vértices Os índices das cores dos vértices são dados pela propriedade datacolor uma cor por vértice é necessária Dois são os casos possíveis datacolor contém um vetor colors então há poucos dados para completar o modo de gradação interpolada De fato uma matriz de cores de tamanho nfn onde n é o número de facetas e nf o número de pontos definindo a faceta poligonal é necessária para realizar esta operação Para cada faceta o algoritmo copia o único valor de índice de cor da faceta nos nf vértices de índices de cores definindo a borda da faceta datacolor contém uma matriz de cores de tamanho nfn ver acima para definições de nf e n o modo de gradação interpolada pode ser completado normalmente utilizandose estes índices de cores colorflag 4 Matlablike flat shading É o mesmo que colorflag2 com uma pequena diferença quando datacolor é uma matriz Todas as facetas são pintadas com o índice de cor fornecido pela propriedade datacolor uma cor por faceta é necessária Dois casos são então possíveis datacolor contém um vetor color vector se colori é positivo fornece a cor da faceta i e a borda da faceta é desenhada com o estilo de linha e cor correntes Se colori é negativo a cor de identificador colori é utilizado e a borda da faceta não é desenhada datacolor contém uma matriz de cores de tamanho nfn onde n é o número de facetas e nf o número de pontos definindo a faceta poligonal Para os nf vértices definindo cada faceta o algoritimo toma a cor do primeiro vértice definindo o retículo faceta cdatamapping específico para manipuladores Fac3d Um string definindo um valor scaled ou direct Se um datacolor é definido cada dado de índice de cor especifica um valor único para vértice cdatamapping determina se estes índices estão em escala para serem mapeados linearmente no mapa de cores corrente modo scaled ou aponta diretamente para o mapa de cores modo direct Esta propriedade é útil quando colorflag é igual a 23 ou 4 hiddencolor esta propriedade contém o índice de cor usado para desenhar as faces atrás de uma superfície Seu valor deve ser um inteiro positivo índice de cores relativo ao mapa de cores corrente Se for um inteiro negativo a mesma cor que a face visível é aplicada para a parte traseira clipstate este campo contém o valor da propriedade clipstate para a superfície O valor de clipstate pode ser off significa que a superfície não é recortada clipgrf significa que a superfície é recortada fora da caixa dos eixos on significa que a superfície é recortada fora do retângulo dado pela propriedade clipbox clipbox este campo determina a propriedade clipbox Por padrão seu valor é uma matriz vazia se a propriedade clipstate é off Em outros casos o vetor xywh ponto superior esquerdo largura altura define as porções da poligonal a serem exibidas contudo o valor da propriedade clipstate será alterado surfaceproperties 793 userdata este campo pode ser usado para armazenar qualquer variável Scilab na estrutura de dados da superfície e recuperála Exemplos criando uma figura t0032pi zsintcost xxyyzzgenfac3dttz plot3dxx xxyy yylistzz zz44ones1400 5ones1400 hgethdl obtendo manipulador da entidade corrente aqui é a superfície agca obtendo eixos correntes arotationangles4070 agrid1 1 1 criando grides adatabounds601665 aaxesvisibleoff os eixos estão escondidos aaxesbounds2 0 1 1 fgetcurrentfigure obtendo o manipulador da figura raiz fcolormaphotcolormap64 mudando o mapa de cores da figura hcolorflag1 colorindo de acordo com z hcolormode2 removendo as bordas das facetas hcolorflag2 colorindo de acordo com as dadas cores hdatacolor1modulo1400641modulo140064 gradação hcolorflag3 scf2 criando segunda janela e utilizando o comando surf subplot211 surfzcdatamappingdirectfacecolinterp subplot212 surfttzedgecobmarkerdmarkersiz9markeredgredmarkerfack egce ecolorflag1 índice de cor proporcional à altitude coordenada z ecolorflag2 de volta ao modo padrão ecolorflag 3 modo de gradação interpolada baseada na cor azul padrão porque o campo datacolor não está preenchido Ver Também set get delete plot3d plot3d1 plot3d2 surf graphicsentities Autores Djalel ABDEMOUCHE FLeray 794 Name swaphandles Permuta dois manipuladores em uma hierarquia gráfica swaphandle handle1 handle2 Parâmetros handle1 primeiro manipulador da permutação handle2 segundo manipulador da permutação Descrição A função swaphandles permite permutar dois manipuladores em uma hierarquia gráfica O primeiro manipulador tomará a posição do segundo e viceversa Desde que nem todos os manipuladores são compatíveis com cada um dos outros existem algumas restrições ao se trocar manipuladores Por exemplo não é permitido trocar um manipulador Polyline com um manipulador Axes já que não seriam compatíveis com suas novas raízes Mais informação sobre compatibilidade pode ser encontrada na página graphicsentities Esta rotina pode ser utilizada em galhos com uma mesma raiz para se trocar os seus índices Exemplos Primeiro Exemplo criando um retângulo xrect 05 050505 rect gce criando um círculo xarc 05 05 05 05 0 64 360 circle gce criando uma seta xpoly0101 arrow gce arrowpolylinestyle 4 arrowarrowsizefactor 4 obtendo a lista de galhos axes gca axeschildren mudando a ordem swaphandles rect arrow swaphandles arrow circle obtendo a nova ordem axeschildren swaphandles 795 Segundo Exemplo criando duas janelas plot2d axes1 gca scf fec axes2 gca trocando os seus eixos note que o mapa de cores não muda swaphandles axes1 axes2 Ver Também graphicsentities copy delete relocatehandle Autor JeanBaptiste Silvy 796 Name textproperties Descrição das propriedades da entidade Text texto Descrição A entidade Text é uma folha na hierarquia de entidades gráficas Esta entidade define parâmetros para escrita de strings parent esta propriedade contém o manipulador da raiz A raiz de uma entidade Text deve ser do tipo Axes ou Compound children esta propriedade contém um vetor com os galhos do manipulador Contudo manipuladores text não possuem galhos correntemente visible este campo contém o valor da propriedade visible para a entidade Pode ser on ou off Por padrão o texto é visível a propriedade é on Se off o texto não é exibido na tela text a matriz contendo os strings do objeto As linhas da matriz são exibidas horizontalmente e as colunas verticalmente alignment especifica como os strings serão alinhados em suas colunas o valor deve ser left center ou right data este campo é o vetor xyz da origem do texto na unidade de dados dos eixos box o valor deste campo pode ser on ou off Se on uma caixa é desenhada ao redor do texto com uma linha em sua borda e um plano de fundo linemode esta propriedade booleana permite desenhar apenas o plano de fundo da caixa quando a pro priedade box é on Se linemode é off a linha da caixa não é desenhada fillmode esta propriedade booleana permite desenhar ou não o plano de fundo da caixa quando a pro priedade box é on Se fillmode for off o plano de fundo da caixa não é transparente textbox um vetor bidimensional especificando o tamanho do retângulo em coordenadas do usuário O retângulo é utilizado quando a propriedade textboxmode está ajustada pára centered ou filled textboxmode Pode ter três valores diferentes off centered ou filled Se off os strings são exibidos utilizandose a dada fonte e o campo data especifica a posição do ponto inferior esquerdo do texto Se centered o texto é exibido no meio do retângulo cujo tamanho é fornecido por textbox Se filled o tamanho de fonte dos strings será expandido para se preencher o retângulo Ao se utilizar os modos off ou centered o tamanho dos textos se mantém constante sob ampliação Eles são os melhores modos para se criar anotações em um gráfico Por outro lado ao se utilizar o modo filled o tamanho do texto segue a escala gráfica É então possível ampliar objetos textos textproperties 797 fontforeground este campo contém a cor utilizada para exibir os caracteres do texto O valor deve ser um índice de cor relativo ao mapa de cores corrente foreground este campo contém a cor utilizada para exibir a linha na borda da caixa O valor deve ser um índice de cores relativo ao mapa de cores corrente background este campo contém a cor utilizada para preencher a caixa ao redor do texto O valor deve ser um índice de cor relativo ao mapa de cores corrente fontsize é um escalar especificando o tamanho dos caracteres exibidos Se a propriedade fractionalfont é off apenas a parte inteira do valor é utilzada Para mais informações veja graphicsfonts fontstyle especifica a fonte a ser utilizada para exibir os strings É um inteiro positivo fazendo referência a uma das fontes carregadas Seu valor deve estar entre 0 referência à primeira fonte e o número de fontes carregadas menos um referência à última fonte Para mais informações veja graphicsfonts fractionalfont Esta propriedade indica se o texto será exibido utilizandose tamanhos de fonte fracionários Pode ser on ou off Se on o valor em ponto flutuante de fontsize é utilizado para exibição e retirase o serrilhamento da fonte Se off apenas a parte inteira é utilizada e a fonte não é suavizada fontangle esta propriedade determina a orientação do string Especifica o valor da rotação em graus clipstate este campo contém o valor da propriedade clipstate para o texto O valor de clipstate pode ser off significa que o texto não é recortado cliprf significa que o texto é recortado fora da caixa dos eixos on significa que o texto é recortado fora do retângulo dado pela propriedade clipbox clipbox este campo contém o valor da propriedade clipbox Seu valor deve ser uma matriz vazia se clipstate é off ou o vetor xywh ponto superior esquerdo largura altura userdata este campo pode ser utilizado para armazenar qualquer variável Scilab na estrutura de dados da entidade texto e recuperála Exemplos agetcurrentaxes adatabounds0011 aaxesvisible on xstring0505Scilab is not esilaB00 tgethdl obtendo o manipulador do novo objeto criado textproperties 798 tfontforeground6 alterando as propriedades da fonte tfontsize5 tfontstyle5 ttextSCILABnãoéesilaB alterando tfontangle90 virando os strings ttextbox 00 ttextboxmode centered o texto está agora centrado em 0505 talignment center tbox on desenhando uma caixa ao redor do texto Ver Também set get delete xtitle graphicsentities Autor Djalel ABDEMOUCHE JeanBaptiste SILVY 799 Name title Exibe um título em uma janela gráfica titlemytitle titlemytitleProperty titleaxeshandlemytitleProperty Parâmetros mytitle string o título a ser exibido Property argumento opcional representa um par de declarações PropertyNamePropertyValueque definem propriedades de objetos globais aplicadas o título criado axeshandle este argumento opcional força o título a parecer dentro dos eixos selecionados dados por axeshandle ao invés dos eixos correntes ver gca Descrição title exibe um título numa janela de gráficos Os argumentos Property propriedade devem ser usados para customizar o título Aqui está uma lista completa das opções disponíveis Property backgroundcolor este campo contém a cor utilizada para preencher a caixa se houver Seu valor deve ser um índice de cor relativo ao mapa de cores corrente color este campo contém a cor a ser utilizada para exibir o texto de título Seu valor deve ser um índice de cor relativo ao mapa de cores corrente edgecolor este campo contém a cor usada para exibir a linha ao redor da caixa se houver alguma Seu valor deve ser um índice de cor relativo ao mapa de cores corrente fontname sete fontes diferentes estão disponíveis Courrier Symbol Times Times Italic Times Bold Definida pelo Usuário A propriedade fontsize é um índice no intervalo 0 6 que é associado a um dos nomes anteriores fontsize a propriedade é utilizada para selecionar o tipo de tamanho do título Seu valor deve ser um inteiro entre 0 e 5 que significa 8pt 10pt 12pt 14pt 18pt e 24pt position este vetor 2d permite que você posicione manualmente o título na tela A posição é armazenada nas unidades de dados dos eixos rotation escalar que permite que você gire o título A fonte é girada em sentido antihorário com o ângulo dado em graus visible este campo contém o valor da propriedade visible para o título Pode ser on ou off Por padrão o título é visível a propriedade é on Se off o título não é exibido na tela Exemplos title 800 exibindo um título com várias propriedades titlemeu título mudando a cor de fonte do título titlemeu títulocolorblue mudando a cor ao redor da caixa titlemeu títuloedgecolorred mudando a posição do título titlemeu títuloposition03 08 mudando o tamanho da fonte titlemeu títulofontsize3 dando uma rotação titlemeu títulorotation90 podemos realizar todas essas modificações apenas pela instrução abaixo titlemeu títulocolorblueedgecolorredfontsize3rotation90position03 08 Ver Também labelproperties titlepage xtitle Autor FBelahcene 801 Name titlepage adiciona título no meio de uma janela de gráficos titlepagestr Parameters str matriz de strings Descrição titlepage exibe a matriz de strings str no meio da janela de gráficos corrente com uma fonte a maior possível Ver Também xtitle Autor S S 802 Name twinkle Faz uma entidade gráfica piscar twinklehn Parâmetros h manipulador de uma entidade gráfica n inteiro Descrição twinkle faz com que a entidade gráfica dada pelo seu manipulador h pisque Pode ser usado para encontrar o objeto gráfico correspondente a um manipulador gráfico em uma janela de gráficos Por padrão a entidade gráfica pisca 5 vezes mas você pode mudar este número através do argumento opcional n Exemplos xlinspace2pi2pi100 plot2dxsinxcosx egce p1echildren1 p2echildren2 fazendo piscar o esboço de cos twinklep1 fazendo piscar o esboço de sin piscar twinklep210 eixos piscando twinklegca Ver Também graphicsentities 803 Name unglue Descola uma objeto Compound e o substitui por um galho individual unglueh Hunglueh Parâmetros h manipulador de um Compound H um vetor de manipuladores das entidades resultantes após um unCompound Descrição Dado um manipulador de uma entidade Compound destrói o Compound e desembrulha as entidades elementares associadas à sua raiz glue retorna um vetor de manipuladores desses galhos individuais Ver Também get set copy glue graphicsentities Autor Djalel ABDEMOUCHE 804 Name unzoom Diminui a ampliação unzoom unzoomH Parâmetros H um vetor de manipuladores Figure ou Axes Descrição unzoom é usado para remover o efeito de ampliação em todos os eixos da figura gráfica corrente unzoomH é usado para remover o efeito de ampliação em todos os Figures e Axes dados pelo vetor de manipuladores H A remoção do efeito de ampliação para uma entidade Figure é o mesmo que remover o efeito de ampliação para todos os seus Axes galhos Exemplos clf x00016pi plot2dxsinx2 zoomrect161181 unzoom aplicação a subesboços clf x00016pi subplot211 plot2dxcosx a1gca subplot212 plot2dxcos2x a2gca rect3 2 7 10 um retângulo especificado nos eixos correntes os últimos zoomrectrect unzooma1 diminuição de ampliação aplicado ao primeiro esboço apenas unzooma2 diminuição de ampliação aplicado ao segundo esboço apenas zoomrectrect aplicando ampliação de novo unzoomgcf diminuição de ampliação aplicada a todos os eixos equivalente a unzoom Ver Também zoomrect axesproperties Autor Serge Steer INRIA JeanBaptiste Silvy INRIA 805 Name whitecolormap Mapa de cores completamente branco cmapwhitecolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição O mapa de cores é completamente branco Exemplos f scf plot3d1 fcolormap whitecolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap wintercolormap 806 Name winsid retorna a lista de janelas de gráficos xwinsid Parâmetros x vetor linha Descrição winsid é usado para retornar a lista de janelas de gráficos como um vetor de números das janelas 807 Name wintercolormap Mapa de cores com tons do inverno azul verde cmapwintercolormapn Parâmetros n inteiro 3 o tamanho do mapa de cores cmap matriz com 3 colunas RGB Descrição wintercolormap computa um mapa de cores com n cores que variam do azul para o verde Exemplos f scf plot3d1 fcolormap wintercolormap32 Ver Também colormap autumncolormap bonecolormap coolcolormap coppercolormap graycolormap hotcol ormap hsvcolormap jetcolormap oceancolormap pinkcolormap rainbowcolormap springcolormap summercolormap whitecolormap 808 Name xarc esboça parte de uma elipse xarcxywha1a2 Parâmetros xywh quatro valores reais definindo um retângulo a1a2 valores reais definindo um setor Descrição xarc desenha parte de uma elipse contida no retângulo xywh ponto superior esquerdo largura altura e no setor definido pelo ângulo alpha1e o ângulo alpha1alpha2 alpha1 e alpha2 são respectivamente dados por a164 graus e a264 graus Esta função usa a cor e a escala gráfica correntes Exemplos escala de isovisualização plot2d001031 2222 xsetcolor3 xarc112209064 xarc151533036064 Ver Também xarcs xfarc xfarcs Autor JPhC 809 Name xarcs desenha partes de um conjunto de elipses xarcsarcsstyle Parâmetros arcs matriz de tamanho 6n descrevendo as elipses style vetor linha de tamanho n fornecendo o estilo a ser usado Descrição xarcs desenha parte de um conjunto de elipses descritas por arcs arcsx y w h a1 a2x y w h a1 a2 onde cada elipse é definida por 6 parâmetros xywha1a2 ver xarc x y w h são especificados nas coordenadas do usuário stylei fornece a cor utilizada para desenhar a elipse número i Exemplos plot2d001031 1111 arcs10 00 05 x superior esquerdo 10 00 05 y superior esquerdo 05 10 05 largura 05 05 10 altura 00 00 00 ângulo 1 18064 36064 9064 ângulo 2 xarcsarcs123 Ver Também xarc xfarc xfarcs Autor JPhC 810 Name xarrows desenha um conjunto de setas xarrowsnxnyarsizestyle Parâmetros nxny vetores ou matrizes de reais de mesmo tamanho arsize escalar real o tamanho da cabeça da seta O tamanho padrão pode ser obtido ajustando arsize para 1 style matriz ou escalar Se style for um escalar positivo fornece a cor a ser usada em todas as setas Se for negativo a cor corrente é utilizada Se for um vetor stylei fornece a cor a ser utilizada no vetor i Descrição xarrows desenha um conjunto de setas dadas por nx e ny Se nx e ny forem vetores a iésima seta é definida por nxinyinxi1nyi1 Se nx e ny são matrizes nxxi1 x12 xf1 xf2 nyyi1 y12 yf1 yf2 a késima seta é definida por xikyikxfkyfk xarrows utiliza a escala de gráficos corrente que pode ser ajustada através de uma chamada a uma função de esboço de altonível como plot2d Exemplos x2pi098 x1sinx9sinx y1cosx9cosx plot2d1010101011022 xsetclipgrf xarrowsx1y11110 xsetclipoff Autor JPhC 811 Name xbasc limpa uma janela de gráficos xbascwindowid Parâmetros windowid escalar inteiro ou vetor de escalares inteiros Descrição Sem argumentos esta função limpa a janela de gráficos corrente e apaga os gráficos gravados Em outro caso ela limpa as janelas de gráficos cujos números estão inclusos no vetor windowid Por exemplo xbasc13 limpa as janelas 1 2 e 3 e apaga seus gráficos gravados correspondentes Se uma dessas janelas não existir ela é automaticamente criada xbasc deleta cada galho das janelas especificadas incluindo menus e uicontrols adicionados pelo usuário Para evitar que menus e uicontrols sejam apagados o comando deletegca pode ser utilizado ao invés A função xbasc está obsoleta Para apagar uma figura por favor use ao invés clf ou delete Ver Também clf xclear 812 Name xbasr desenha novamente uma janela de gráficos xbasrwinnum Descrição xbasr é usado para exibir novamente o conteúdo de uma janela de gráficos com i winnum Fun ciona apenas com o driver Rec Ver Também driver replot Autor JPhC 813 Name xchange conversão de coordenadas reais para coordenadas pixeis x1y1rectxchangexydir Parâmetros xy duas matrizes de tamanho n1n2 coordenadas de um conjunto de pontos dir parâmetro utilizado para especificar o tipo de conversão ver Description para detalhes x1y1 duas matrizes de tamanho n1n2 coordenadas de um conjunto de pontos rect um vetor de tamanho 4 Descrição Após o uso de uma função de gráficos xchange computa coordenadas pixel a partir de coordenadas reais e viceversa de acordo com o valor de parâmetro dirf2i float para int significa real para pixel e i2f int para float significa pixel para real x1 e y1 são as coordenadas de um conjunto de pontos definidos pelas antigas coordenadas x e y rect são as coordenadas em pixel do retângulo no qual o esboço foi feito ponto superior esquerdo largura altura Exemplos t0012pi plot2dtsint xyrectxchange11f2i xyrectxchange00i2f Autor JPhC 814 Name xclear limpa janela de gráficos xclearwindowid Parâmetros windowid vetor de inteiros ou escalar inteiro Descrição Sem argumentos esta função limpa a figura corrente ajustando a sua propriedade visible para off Em caso contrário ela limpa as janelas cujos números estão inclusos no vetor windowid Por exemplo xclear13 limpa as janelas 1 2 e 3 Se uma dessas janelas não existir então ela é automatica mente criada A função xclear está obsoleta Para limpar uma figura por favor utilize a função clf ao invés ou a propriedade visible Ver Também xbasc Autor JPhC 815 Name xclick espera por um clique do mouse ibuttonxcoordyxcoordiwincbmenuxclickflag Parâmetros ibutton escalar real valor inteiro número do botão do mouse código da tecla ver descrição abaixo xcoord escalar real coordenada x do ponteiro do mouse quando ocorreu o clique na escala gráfica cor rente ycoord escalar real coordenada y do ponteiro do mouse quando ocorreu o clique na escala gráfica cor rente iwin escalar real valor inteiro número da janela onde a ação ocorreu cbmenu string callback associado a um menu se xclick retorna devido a um clique em um menu Neste caso ibutton xcoord ycoord e iwin tomam valores arbitrários flag escalar real valor inteiro se presente a fila de eventos de clique não é limpa ao se entrar xclick Descrição xclick espera pelo clique do mouse na janela de gráficos Se for chamado com 3 argumentos do lado esquerdo espera pelo clique do mouse na janela de gráficos corrente Se chamado com 4 ou 5 argumentos do lado esquerdo espera pelo clique do mouse em qualquer janela de gráficos Os valores de ibutton estão descritos abaixo ibutton0 o botão esquerdo foi pressionado ibutton1 o botão do meio foi pressionado ibutton2 o botão direito foi pressionado ibutton3 o botão esquerdo do mouse foi clicado ibutton4 o botão do meio do mouse foi clicado ibutton5 o botão direito do mouse foi clicado xclick 816 ibutton10 o botão esquerdo do mouse foi clicado duas vezes ibutton11 o botão do meio do mouse foi clicado duas vezes ibutton12 o botão direito do mouse foi clicado duas vezes ibutton 32 uma tecla com código ASCII ibutton foi pressionada ibutton 32 uma tecla com código ASCII ibutton foi liberada ibutton 100032 uma tecla com código ASCII ibutton1000 foi pressionada enquanto a tecla CTRL estava sendo pressionada ibutton1000 a janela de gráficos foi fechada Aviso ibutton era igual a 100 para fechamento de janelas gráficas até o Scilab 412 mas este código foi modificado no Scilab 50 pois também era o código retornado pela liberação da tecla d ibutton2 um menu dinâmico foi selecionado e seu callback é retornado em cbmenu Ver Também locate xgetmouse seteventhandler Autores JPhC VC 817 Name xdel deleta uma janela de gráficos xdelwinnums Parâmetros winnums inteiro ou vetor de inteiros Descrição xdel deleta a janela de gráficos winnums ou a janela de gráficos corrente se não for fornecido nenhum argumento Autor JPhC 818 Name xfarc preenche parte de uma elipse xfarcxywha1a2 Parâmetros xywh quatro valores reais definindo um retângulo a1a2 valores reais definindo um vetor Descrição xfarc preenche parte de uma elipse contida no retângulo xywh ponto superior esquerdo largura altura no setor definido pelo ângulo alpha1 e o ângulo alpha1alpha2 alpha1 e alpha2 são respectivamente a164 graus e a264 graus Esta função usa a cor e a escala gráfica corrente Exemplos escala de isovisualização plot2d001031 2222 xfarc05051109064 xsetcolor2 xfarc050511036064 Ver Também xarc xarcs xfarcs Autor JPhC 819 Name xfarcs preenche partes de um conjunto de elipses xfarcsarcsstyle Parâmetros arcs matriz de tamanho 6n descrevendo as elipses style vetor linha de tamanho n fornecendo as cores a serem utilizadas Descrição xarcs preenche parte de um conjunto de elipses descritas por arcs arcsx y w h a1 a2x y w h a1 a2 onde cada elipse é definida por 6 parâmetros xywha1a2 ver xfarc x y w h são especificados nas coordenadas do usuário stylei fornece o número da cor para preencher a elipse número i Exemplos plot2d001031 1111 arcs10 00 05 x superior esquerdo 10 00 05 y superior esquerdo 05 10 05 largura 05 05 10 altura 00 00 00 ângulo 1 18064 36064 9064 ângulo 2 xfarcsarcs123 Ver Também xarc xfarc xfarc Autor JPhC 820 Name xfpoly preenche um polígono xfpolyxvyvclose Parâmetros xvyv dois vetores de mesmo tamanho os pontos do polígono close inteiro Se close 1 a linha poligonal é fechada o valor padrão é 0 Descrição xfpoly preenche um polígono com a cor corrente Se close é igual a 1 um ponto é adicionado à poligonal xvyv para definir o polígono Exemplos xsin2pi045 ycos2pi045 plot2d001010 2222 xsetcolor5 xfpolyxy apenas para novo estilo de gráficos egce retorna a última entidade corrente a última criada aqui é a poligonal efillmodeoff eclosed off a poligonal está aberta agora xsetdefault Ver Também xfpolys xpoly xpolys Autor JPhC 821 Name xfpolys preenche um conjunto de polígonos xfpolysxpolsypolsfill Parâmetros xpolsypols matrizes de mesmo tamanho pn pontos dos polígonos fill vetor de tamanho n ou tamanho pn Descrição xfpolys preenche um conjunto de polígonos de mesmo tamanho definidos pelas matrizes xpols e ypols As coordenadas de cada polígono são armazenadas em uma coluna de xpols e ypols Os polígonos podem ser preenchidos por uma dada cor preenchimento monótono ou pintados com cores interpoladas preenchimento por graduação preenchimento monótono Neste caso fill deve ser um vetor de tamanho n O padrão para preenchimento de um polígono de número i é dado por filli se filli0 o polígono é preenchido com padrão de identificador filli se filli0 o polígono é desenhado no estilo de traço ou cor corrente e não é preenchido se filli0 o polígono é preenchido com padrão de identificador filli Então seu contorno é desenhado com o estilo de traço ou cor corrente e fechado se necessário preenchimento interpolado Neste caso fill deve ser uma matriz com o mesmo mesmo tamanho de xpols e ypols Note que p deve ser igual a 3 ou 4 fillki fornece a cor da k ésima borda do polígono i Exemplos agcaadatabounds01021040aforegroundcolorred x1010203020100 y1153030150015 xpolsx1 x1 x1 x1 xpolsxpols060120180onesx1 ypolsy1 y1 y1 y1 xfpolysxpolsypols1012 cores interpoladas clf fgcf agcaadatabounds0104030aisoviewon x10102010 y11001020 clinspace21004 xpolsx1 x120 x110 x110 ypolsy1 y1 y110 y110 xfpolys 822 cols c c11 c3 4 1 2 c fcolormapjetcolormapmaxcols xfpolysxpolsypolscols cores interpoladas clf fgcf x11020200y1110103030c1110103030 x12x11y12y1120c12202011c1230301010 x2103030022y2120203030c2120203030 x22x21y22y2110c2230302020 x3104040055y31003030c31003030 x32x31y32y3130c32303000 Xx11 x12 x21 x22 x31 x32Yy11 y12 y21 y22 y31 y32Cc11 c12 c21 c22 c31 c3215 agcaaisoviewon adataboundsminXminYmaxXmaxY fgcffcolormapgraycolormapmaxC xfpolysXYC Ver Também xfpoly xpoly xpolys Autor JPhC 823 Name xfrect preenche um retângulo xfrectxywh xfrectrect rect xywh Parâmetros xywh quatro valores reais definindo um retângulo Descrição xrect preenche um retângulo definido por xywh ponto superior esquerdo largura altura usando a escala e o estilo correntes Exemplos plot2d001010 2222 xsetcolor5 xfrect1122 xsetdefault Ver Também xrect xrects Autor JPhC 824 Name xget retorna valores correntes do contexto gráfico Esta função está obsoleta x1xgetstrflag xget Parâmetros str string flag opcional Ajustado para 1 fornece um modo verboso Descrição Aviso esta função está obsoleta Use a representação de objetos gráficos do Scilab ver as ajudas de set e get bem como a página graphicsentities Esta função é utilizada para se obter valores de um contexto de gráficos no tópico especificado pelo string str Quando chamada sem argumento um menu de escolha é criado exibindo os valores cor rentes e mudanças podem ser realizadas através de botões de alternância numberxgetalufunction recebe o número da função lógica usada para desenhar Ver xset strxgetauto clear recebe o status de autolimpeza on ou off colorxgetbackground recebe a cor de fundo da janela de gráficos corrente rectxgetclipping recebe a zona de recorte como o retângulo rectxywh ponto superior esquerdo largura al tura cxgetcolor recebe a cor padrão para funções de preenchimento desenho de linha ou texto c é um inteiro projetado no intervalo 0whiteid 0 significa preenchimento com preto e whiteid preenchimento com branco O valor de whitid xgetwhite cmapxgetcolormap recebe o mapa decores utilizado para a janela de gráficos corrente como uma matriz m x 3 RGB vermelho verde azul dashxgetdashes recebe o estilo de traço dash dashnumber onde dashnumber é o identifcador do traço Esta palavrachave está obsoleta use xgetcolor ou xgetline style ao invés fontxgetfont recebe fontfontidfontsize a fonte padrão e o tamanho padrão para fontes fontsizexgetfont size recebe o tamanho padrão para fontes colorxgetforeground recebe a cor de primeiro plano do objeto Axes corrente O resultado é um índice do mapa de cores correspondente à cor xget 825 strxgetfpf recebe o formato em ponto flutuante do número do número de exibição em funções de contorno Note que str é quando o formato padrão é utilizado colorxgethidden3d recebe o número de cor para faces escondidas em plot3d patxgetlastpattern recebe o identificador do último padrão ou cor disponível no mapa de cores da janela corrente Na verdade pat1 e pat2 também estão disponíveis e correspondem a padrões preto e branco respectivamente typexgetline mode recebe o modo de desenho de linha type1 é o modo absoluto e type0 é o modo relativo Aviso type0 tem defeitos xgetline style recebe o estilo de linhas padrão1 sólido 1 para linhas tracejadas markxgetmark recebe o identificador do estilo de marcas padrão e o tamanho de marcas padrão markmarkidmarksize marksizexgetmark size recebe o tamanho de marcas padrão patxgetpattern recebe o padrão corrente ou a cor corrente pat é um inteiro no intervalo 1last Quando se usa preto ou branco 0 é usado para preenchimento com preto e last para preenchimento com branco O valor de last pode ser obtido com xgetlastpattern valuexgetthickness recebe a espessura das linhas em pixel 0 e 1 têm o mesmo significado 1 pixel de espessura flagxgetuse color recebe o flag 0 para uso apenas de preto e branco ou 1 uso de cores Ver xset xyxgetviewport recebe a posição corrente da parte visível de gráficos dimxgetwdim recebe a largura e a altura da janela de gráficos corrente dimlarguraaltura winxgetwindow recebe o número de janela corrente win posxgetwpos recebe a posição do ponto superior esquerdo da janela de gráficos posxy Ver Também xset getcolor getsymbol ged set graphicsentities Autor JPhC 826 Name xgetech retorna a escala de gráficos corrente wrectfrectlogflagarectxgetech Parâmetros wrectfrect vetores de reais logflag string de tamanho 2 xy Descrição xgetech retorna a escala de gráficos corrente da janela corrente O retângulo xminyminxmaxymax dado por frect é o tamanho de toda a janela de gráficos O esboço será feito na região da janela de gráficos corrente especificada por wrect wrectxywh ponto superior esquerdo largura altura descreve uma região dentro de uma janela de gráficos Os valores em wrect são especificados utilizandose a proporção de largura e altura da janela de gráficos wrect0 0 1 1 significa que toda a janela de gráficos será utilizada wrect05 0 05 1 significa que a região de gráficos é a metade direita da janela de gráficos logflag é um string de tamanho 2 xy onde x e y podem ser n ou l n significa escala normal linear e l significa escala logarítmica x corresponde ao eixo x e y corresponde ao eixo y arectxleft xrightyupydown fornece o tamanho da moldura dentro da sub janela O quadro gráfico é especificado como wrect utilizandose a proporção de largura ou altura da subjanela de gráficos corrente O valor padrão é 181111 Se arect não for fornecido o valor corrente permanece inalterado Exemplos primeira subjanela xsetech001005 plot2d então xsetech é usado para ajustar a segunda subjanela xsetech0051005 grayplot obtendo as escalas gráficas da primeira subjanela xsetech001005 wrectfrectlogflagarectxgetech obtendo as escalas gráficas da segunda subjanela xsetech0051005 wrectfrectlogflagarectxgetech xbasc xsetdefault Ver Também xsetech Autor 828 Name xgetmouse retorna os eventos de mouse e posição corrente rep winxgetmousesel Parâmetros sel vetor de booleanos getmotion getrelease O valor padrão é t f rep vetor de tamanho 3 xyibutton win número da figura onde o evento ocorreu Descrição Se o cursor do mouse estiver localizado na janela de gráficos corrente xgetmouse retorna em rep a posição corrente do cursor xy e o valor ibutton O valor de ibutton indica o tipo de evento ibutton0 o botão esquerdo do mouse foi pressionado ibutton1 o botão do meio do mouse foi pressionado ibutton2 o botão direito do mouse foi pressionado ibutton3 o botão esquerdo do mouse foi clicado ibutton4 o botão do meio do mouse foi clicado ibutton5 o botão direito do mouse foi clicado ibutton10 o botão esquerdo do mouse foi clicado duas vezes ibutton11 o botão do meio do mouse foi clicado duas vezes ibutton12 o botão direito do mouse foi clicado duas vezes ibutton5 o botão esquerdo do mouse foi liberado ibutton4 o botão do meio do mouse foi liberado ibutton3 o botão direito do mouse foi liberado xgetmouse 829 ibutton1 o cursor foi movido ibutton 32 uma tecla com código ASCII asciiibutton foi pressionada ibutton 32 uma tecla com código ASCII asciiibutton foi liberada ibutton 100032 uma tecla com código ASCII asciiibutton1000 foi pressionada enquanto o botão CTRL estava sendo pressionado ibutton1000 a janela de gráficos foi fechada AVISO Em versões anteriores do Scilab 50 o usuário podia fornecer um flag indicador para precisar se a fila de eventos do mouse deveria ser limpa ao se entrar xgetmouse Está opção está obsoleta agora e será removida no Scilab 51 Exemplos seleção de retângulo clf apagandocriando janela agcaadatabounds0 0100 100ajustando cooredenadas do usuário xtitle drawing a rectangle adicionando um título xselect pondo a janela no topo bxcycxclick retornando um ponto xrectxcyc00 desenhando a entidade Rectangle rgce o manipulador do retângulo repxcyc1firstf while rep31 do movimentação do mouse repxgetmouse xc1rep1yc1rep2 oxminixcxc1 oymaxiycyc1 wabsxcxc1habsycyc1 rdataoxoywh mudando a origem largura e altura do retângulo firstf end Ver Também locate xclick seteventhandler Autor S Steer 830 Name xgraduate Graduação de eixos xixanp1np2kMinrkMaxrarxgraduatexmixma Parâmetros xmixma escalares reais xi xa kMinr kMaxr ar escalares reais np1np2 inteiro Descrição xgraduate retorna as graduações de eixos que são utilizadas pelas rotinas de esboço com o flag de embelezamento habilitado Retorna um intervalo xixa que contém o dado intervalo xmixma e tal que xi kMinr10ar xakMaxr10ar e o intervalo pode ser dividido em np2 intervalos e cada intervalo é dividido em np1 subintervalos Exemplos x1xanp1np2kMinrkMaxrarxgraduate0302 Ver Também graduate plot2d Autor JPC 831 Name xgrid adiciona um grid em um esboço 2d xgridstyle Parâmetros style inteiro Descrição xgrid adiciona um grid em um esboço 2d style é o identificador de tipo de tracejado ou de cor utilizado para o esboço do grid Use xset para o significado do identificador Exemplos x0012pi plot2dsinx xgrid2 Ver Também xset plot2d Autor JPhC 832 Name xinfo escreve um string de informação na subjanela de mensagens xinfoinfo Parâmetros info string Descrição xinfo escreve o string info na subjanela de mensagens da janela de gráficos corrente 833 Name xlfont carrega uma fonte em um contexto gráfico ou pergunta a fonte carregada xlfontfontname xlfontfontfilename xlfontreset xlfontfontnamefontid xlfontfontfilenamefontid xlfontfontnamefontidbold xlfontfontnamefontidbolditalic fontsxlfontAVAILABLEFONTS fontsxlfont Parâmetros fontname string nome da família da fonte fontfilename string nome do arquivo de uma fonte true type fontid inteiro 0 fonts um vetor coluna de nomes de fontes bold um booleano t para negrito italic um booleano t para itálico Descrição Sem argumentos xlfont retorna a lista das fontes correntemente carregadas xlfontAVAILABLEFONTS retorna a lista de fontes disponíveis no seu sistema xlfontreset reajusta para o índice de fontes inicial Com argumentos xlfont é usado para carregar uma nova fonte em tamanhos diferentes no contexto gráfico As famílias de fonte padrões são Monospaced 0 Symbol 1 Serif 2 Serif Italic 3 Serif Bold 4 Serif Bold Italic 5 SansSerif 6 SansSerif Italic 7 SansSerif Bold 8 SansSerif Bold Italic 9 Estas fontes são automaticamente carregadas quando necessário então xlfont não é necessariamente requerido para elas Na verdade xlfont é essencialmente útil para carregar uma nova fonte Exemplos xlfontreset xlfont este exemplo pode no funcionar se seu sistema no possuir a fonte Monospaced xlfont 834 xlfontMonospaced10tt xstring10A title figureentity gcf axesentity figureentitychildren titleentity axesentitychildren titleentityfontstyle 10 xlfont xlfontSCIthirdpartyfontsscilabsymbolsttf titleentityfontstyle 11 utilizando a fonte scilabsymbolsttf titleentityfontsize 4 tamanho da fonte scilabsymbolsttf xlfont xlfontreset Ver Também getfont Autor Allan CORNET 835 Name xload carrega gráficos salvos xloadfilenamewinnum Parâmetros filename string o nome do arquivo winnum inteiro o número da janela de gráficos Se não for fornecido a janela de gráficos corrente é utilizada Descrição xload recarrega os gráficos contidos no arquivo filename na janela de gráficos winnum Desde o Scilab 50 todos os manipuladores uimenu ou uicontrol são também carregados Para arquivos contendo novos gráficos a função load pode ser utilizada ao invés de xload xload não recupera o número da janela nem seu tamanho ou dimensões Exemplos novo estilo t000110 subplot211plot2dtsint subplot212plot2dtsin3t saveTMPDIRfooscggcf clf loadTMPDIRfooscg agca curveachildrenchildren manipulador da curva saveTMPDIRfooscgcurve deletecurve loadTMPDIRfooscg Ver Também xsave load save Autor JPhC 836 Name xname muda o nome da janela de gráficos corrente xnamename Parâmetros name string o novo nome da janela de gráficos Descrição xname muda o nome da janela de gráficos corrente Autor JPhC 837 Name xnumb Imprime números xnumbxynumsboxangle Parâmetros xynums vetores de mesmo tamanho box valor inteiro angle vetor opcional de mesmo tamanho de x Descrição xnumb imprime os valores de numsi na posição xiyi na escala corrente Se box tem valor 1 um retângulo é desenhado ao redor dos números Se angle for dado fornece a direção para escrita do string Exemplos plot2d10050010060011022 x0100200 xnumbx500onesx1020351 Ver Também xstring Autor JPhC 838 Name xpause suspende o Scilab xpausemicrosecs Descrição xpause suspende o processo corrente pelo número de microssegundos especificados pelo argumento A suspensão real pode tornarse mais longa devido a outras atividades do sistema ou por causa do tempo gasto no processamento da chamada Autor JPhC 839 Name xpoly desenha uma poligonal ou um polígono xpolyxvyv dtype close Parâmetros xvyv matrizes de mesmo tamanho os pontos da poligonal dtype string estilo de desenho O valor padrão é lines close inteiro Se close 1a poligonal é fechada o valor padrão é 0 Descrição xpoly desenha uma poligonal descrita pelos vetores de coordenadas xv e yv Se xv e yv forem matrizes serão considerados vetores obtidos por concatenação de suas colunas dtype pode ser lines para uso do estilo de linha corrente ou marks para utilizar a marca corrente para de senho da poligonal Exemplos xsin2pi045 ycos2pi045 plot2d001010 2222 xsetcolor5 xpolyxylines1 por padrão é fechado apenas no novo estilo de gráficos egce retorna a entidade corrente a última criada aqui é a poligonal eclosed off a poligonal está agora aberta Ver Também xfpoly xfpolys xpolys Autor JPhC 840 Name xpolys desenha um conjunto de poligonais ou polígonos xpolysxpolsypolsdraw Parâmetros xpolsypols matrizes de mesmo tamanho pn pontos das poligonais draw vetor de tamanho n Descrição xpolys desenha um conjunto de poligonais usando marcas ou linhas tracejadas As coordenadas de cada poligonal são armazenadas em uma coluna de xpols e ypols O estilo da poligonal i é dado por drawi Se drawi for negativo a marca com identificador drawi i é utilizada para desenhar a poligonal i marcas são desenhadas utilizandose o padrão corrente Use xset para ver o sig nificado dos identificadores Se drawi for estritamente positivo o estilo de linha ou cor com identificador drawi é utilizado para desenhar a poligonal i Use xset para ver o significado dos idenficadores Exemplos plot2d001012 0011 randuniform xsetcolor3 xpolysrand35rand3512012 xsetdefault Ver Também xfpoly xfpolys xpoly Autor JPhC 841 Name xrect desenha um retângulo xrectxywh xrectrect rect xywh Parameters xywh quatro valores reais definindo o retângulo Descrição xrect desenha um retângulo definido por xywh ponto superior esquerdo largura altura usando a escala e o estilo correntes AVISO por favor note que a altura é positiva indo para baixo Exemplos plot2d001010 2222 xsetcolor5 xrect1122 xsetdefault Ver Também xfrect xrects Autor JPhC 842 Name xrects desenha ou preenche um conjunto de retângulos xrectsrectsfill Parâmetros rects matrtiz de tamanho 4n fill vetor de tamanho n Descrição xrects desenha ou preenche retângulos Cada coluna de rects descreve um retângulo ponto su perior esquerdo largura altura rectsx1 y1 w1 h1x2 y2 w2 h2 filli fornece o padrão para preenchimento ou desenho do retângulo i Se filli0 o retângulo i é desenhado utilizandose o estilo de linha ou cor filli Se filli0 o retângulo i é preenchido utilizandose o padrão ou cor filli Se filli0 o retângulo i é desenhado utilizandose o estilo de linha corrente ou cor AVISO por favor note que a altura é positiva indo para baixo Exemplos plot2d100500505011022 cols34333220520323334 x40001414 step20 rectsx10onesxsteponesx30onesx xrectsrectscols xnumbx15onesxcols Ver Também xfrect xrect Autor JPhC 843 Name xrpoly desenha um polígono regular xrpolyorignrtheta Parâmetros orig vetor de tamanho 2 n inteiro número de lados r escalar real theta escalar real ângulo em radianos 0 é o valor padrão Descrição xrpoly desenha um polígono regular com n lados contindo no círculo de diâmetro r e com a origem do círculo posta em um ponto orig theta especifica a rotação do ângulo em radianos Esta função utiliza as escalas gráficas correntes Exemplos plot2d001012 001010 xrpoly5555 Ver Também xrect 844 Name xsave salva gráficos em um arquivo xsavefilenamewinnum Parâmetros filename string nome do arquivo winnum inteiro o número da janela de gráficos Se não for forneceido a janela de gráficos corrente é utilizada Descrição xsave salva os gráficos contidos na janela de gráficos winnum no arquivo binário filename e pode ser carregado com xload Desde o Scilab 50 todos os manipuladores uimenu ou uicontrol também são salvos Para novos gráficos xsavefilenamewinnumuse preferivelmente savefilenamescfwinnum Exemplos novo estilo t000110 subplot211plot2dtsint subplot212plot2dtsin3t saveTMPDIRfooscggcf clf loadTMPDIRfooscg agca curveachildrenchildren handle on the curve saveTMPDIRfooscgcurve deletecurve loadTMPDIRfooscg Ver Também xload save load Autor JPhC 845 Name xsegs desenha segmentos desconexos xsegsxvyvstyle Parâmetros xvyv matrizes de mesmo tamanho style vetor ou escalar Se style is a positive scalar it gives the color to use for all segments Se style for negativo então a cor corrente é utilizada Se style for um vetor então stylei fornece a cor a ser utilizada no segmento i Descrição xsegs desenha um conjunto de segmentos desconexos dados por xv e yv Se xv e yv forem matrizes serão considerados como vetores através da concatenação de suas colunas As coordenadas dos dois pontos definindo um segmento são dadas por dois valores consecutivos de xv e yv xviyvixvi1yvi1 Por exemplo utilizando matrizes de tamanho 2n os segmentos são definidos por xvxi1 xi2 xf1 xf2 yvyi1 yi2 yf1 yf2 e os segmentos são xikyikxfkyfk Exemplos x2pi0910 xvsinx9sinx yvcosx9cosx plot2d1010101011022 xsegsxvyv110 Autor JPhC 846 Name xselect restaura a janela de gráficos corrente xselect Descrição xselect restaura a janela de gráficos corrente Se tal janela não existir uma é criada Aviso está função está obsoleta e será removida no Scilab 51 Ela foi substituída pela função showwindow Ver Também showwindow Autores JPhC JeanBaptiste Silvy 847 Name xset ajusta valores para o contexto gráfico Função obsoleta xsetchoicenamex1x2x3x4x5 xset Parâmetros choicename string x1x5 dependem de choicename Descrição Aviso está função está obsoleta Utilize a representação de objetos do Scilab ao invés ver as documentações das funções set e get bem como a página graphicsentities xset é utilizado para ajustar valores padrões do contexto da janela de gráficos corrente Quando chamado sem argumento um menu de escolha é criado exibindo os valores correntes e mudanças podem ser realizadas através e botões de escolha Use xset para exibir ou ajustar a cor corrente marca e fontes utilizadas xsetalufunctionnumber usado para ajustar a função lógica para desenho A função lógica utilizada é ajustada por x1 Os valores usuais são 3 para cópia padrão 6 para animação e 0 para limpeza Ver alufunctions para mais detalhes xsetauto clearonoff alterna o modo de limpeza automática para gráficos entre on e off Quando o modo de limpeza automática é on esboços sucessivos não são superpostos ie uma operação xbasc a janela de gráficos é limpa e os gráficos gravados associados são apagados é realizada antes de cada função gráfica de altonível O valor padrão é off xsetbackgroundcolor ajusta a cor de plano de fundo do objeto Axes corrente O argumento color é um índice no mapa de cores da cor a ser utilizada xsetclippingxywh ajusta a zona de recorte a zona da janela de gráficos onde os esboços podem ser desenhados como sendo o retângulo xywh ponto superior esquerdo largura altura Esta função utiliza a utiliza as coordenadas correntes do esboço xsetcolorvalue ajusta a cor padrão para funções de preechimento linha ou impressão de textos value é um inteiro projetado no intervalo 0whiteid 0 é usado para preenchimento com preto e whiteid para preenchimento com branco O valor do identificador do branco pode ser obtido através de xgetwhite xsetcolormapcmap ajusta o mapa de cores como sendo uma matriz m x 3 m é o número de cores A cor de número i é dada como sendo a tripla cmapi1 cmapi2 cmapi3 correspondentes respectivamente às intensidades de vermelho verde e azul entre 0 e 1 xset 848 xsetdashesi no modo preto e branco xsetuse color0 ajusta o estilo de tracejado como o estilo i 0 para linha sólida No modo colorido xsetuse color1 é utilizado para ajustar a cor da linha da marca e do texto Esta palavrachave está obsoleta utilize xsetcolori ou xsetline stylei ao invés xsetdefault reajusta o contexto gráfico para valores padrões xsetfontfontidfontsize ajusta a fonte corrente e seu tamanho Note que fontsize se aplica a todas as fontes não só a fontid xsetfont sizefontsize ajusta o tamanho da fonte xsetforegroundcolor ajusta a cor de primeiro plano do objeto Axes corrente O argumento color é um índice no mapa de cores da cor a ser utilizada xsetfpfstring ajusta o formato de exibição de ponto flutuante para funções de contorno string é um string fornecendo o formato em sintaxe C por exemplo string3f Use string para retornar ao formato padrão xsethidden3dcolorid ajusta o número de cor para as faces escondidas em um plot3d colorid0 suprime o desen ho de faces escondidas de objetos 3d Isto é tecnicamente chamdo culling e acelera a renderização de superfícies fechadas xsetline modetype esta função é utilizada para se ajustar o modo de desenho da linha O modo absoluto é ajustado com type 1 e o modo relativo com type0 aviso o modo type 0 possui defeitos xsetline stylevalue ajusta o estilo de linha corrente 1 sólida 1 estilos tracejados xsetmarkmarkidmarksize ajusta a marca corrente e seu tamanho Use xset para visualizar as marcas Note que mark size se aplica a todas as marcas não apenas a markid xsetmark sizemarksize ajusta o tamanho da marca xsetpatternvalue ajusta o padrão pattern não confundir com padrão default corrente para funções de preenchi mento O valor é um inteiro projetado no intervalo 0whiteid 0 é utilizado para preenchimento com preto e whiteid para preenchimento com branco O valor de whiteid pode ser obtido com xgetwhite pattern é equivalente a color xsetpixmapflag se flag0 os gráficos são diretamente exibidos na tela Se flag1 os gráficos são feitos em um pixmap mapa de pixel e enviados à janela de gráficos através do comando xsetwshow O pixmap é limpo com o comando xsetwwpc Note que o comando usual xbasc também limpa o pixmap xsetthicknessvalue ajusta o valor de espessura das linhas em pixel 0 e 1 têm o mesmo significado 1 pixel de es pessura xset 849 xsetuse colorflag se flag1 então xsetpattern ou xsetdashes será utilizado de modo a modificar a cor padrão para desenho ou para padrões de preenchimento Se flag0 então retornase ao modo de escalas de cinza e tracejados xsetviewportxy ajusta a posição do cursor xsetwdimwidthheight ajusta a largura e altura da janela de gráficos corrente Esta opção não é utilizada pelo driver Postscript xsetwpdimwidthheight ajusta a largura e altura da janela de gráficos física corrente que pode ser diferente do tamanho atual no modo wresize 1 Esta opção não é utilizada pelo driver Postscript xsetwindowwindownumber ajusta a janela windownumber como sendo a janela corrente e cria a janela se esta não existir xsetwposxy ajusta a posição do ponto superior esquerdo da janela de gráficos xsetwresizeflag se flag 1então o gráfico é automaticamente redimensionado para preencher a janela de gráficos xdel xsetwresize1 plot2d xsetwdim1000500 Se flag0 a escala do gráfico é inalterada quando a janela de gráfico é redimensionada O cursor no canto superior esquerdo ou as setas do teclado podem ser utilizadas para rolar o gráfico xdel plot2d xsetwresize0 xsetwdim1000500 xsetwshow ver xsetpixmap1 acima xsetwwpc ver xsetpixmap1 acima Ver Também xget getcolor getsymbol ged set graphicsentities Autor JPhC 850 Name xsetech ajusta a subjanela de uma janela de gráficos para esboço xsetechwrectfrectlogflag xsetechwrectfrectlogflag arect xsetech Parâmetros wrect vetor de tamanho 4 definindo a subjanela a ser utilizada frect vetor de tamanho 4 logflag string de tamanho 2 xy onde x e y podem ser n ou l n escala normal e l significa escala logarítmica x referese ao eixo x e y ao eixo y arect vetor de tamanho 4 Descrição xsetech é principalmente utilizado para ajustar a subjanela da janela de gráficos que será utilizada para esboço A subjanela é especificada através do parâmetro wrectxywh ponto superior esquerdo largura altura Os valores em wrect a são especificados utilizandose a proporção de largura ou altura da janela de gráficos corrente Por exemplo wrect0011 significa que toda a janela será utilizada e wrect050051 significa que a região gráfica será a metade direita da janela de gráficos xsetech também ajusta as escalas gráficas correntes para esboço 2d e pode ser utilizada juntamente a rotinas gráficas que requerem a escala de gráficos corrente por exemplo strfx0z ou frame flag0 em plot2d frectxminyminxmaxymax é utilizado para ajustar a escala gráfica e é igual ao argumento rect de plot2d Se frect não for fornecido o valor corrente da escala de gráficos permanece inalterado O valor padrão de rect é 0011 na criação de janelas quando se volta para o valor padrão com xsetdefault ou quando se limpa eventos gráficos gravados xbasc arectxleft xrightyupydown é utilizado para ajustar a moldura gráfica dentro da subjanela A moldura gráfica é especificada como wrect utilizandose a proporção de largura ou altura da subjanela de gráficos corrente O valor padrão é 181111 Se arect não for fornecido o valor padrão permanece inalterado Exemplos para obter uma explanação gráfica dos parâmetros de xsetech entre com execSCImodulesgraphicsdemosxsetechfigsce aqui xsetech é usado para dividir a janela de gráficos em duas partes o primeiro xsetech é usado para se ajustar a primeira subjanela e a escala de gráficos corrente xsetech0010055353 chamamos plot2d com a opção 001 para utilizar a escala de gráficos ajustada por xsetech xsetech 851 plot2d1101101001 então xsetech é usado para ajustar a segunda subjanela xsetech0051005 a escala de gráficos é ajustada por xsetech para 0011 por padrão e nós a modificamos utilizando o argumento rect em plot2d plot2d1101101011 6666 quatro esboços em uma única janela de gráficos xbasc xsetfont20 xsetech000505 plot3d xsetech0500505 plot2d xsetech05050505 grayplot xsetech0050505 histplot de volta aos valores padrões para a subjanela xsetech0011 um esboço com arect modificado xbasc xsetdefault xsetecharect0000 x10110plot2dxsinx xbasc xsetecharect181811614 x10110plot2dxsinx xbasc xsetdefault Ver Também xgetech subplot isoview square Autor JPhC 852 Name xsetm Abre uma caixa de diálogo para ajustar valores do contexto gráfico Função obsoleta xsetm Descrição Esta função bem como a função xset estão fortemente ligadas ao modo gráfico antigo que não está mais disponível O novo modo gráfico é muito mais flexível quanto ao ajuste de parâmetros ver a ajuda das funções set e get bem como a página de graphicsentities É possível iniciar um editor de propriedades mais conveniente através de ged Ver Também xset ged set graphicsentities Autor JPhC ENPC 853 Name xstring imprime strings xstringxystranglebox Parâmetros xy escalares reais coordenadas do ponto inferior esquerdo dos strings str matriz de strings angle real ângulo horário em graus O valor padrão é 0 box inteio o valor padrão é 0 Descrição xstring imprime a matriz de strings str na localização xy ponto inferior esquerdo na escala de gráficos corrente cada linha da matriz significa uma linha de texto e os elementos das linhas são palavras separadas por espaços em branco Se angle for dado fornece a inclinação em graus para escrever os strings Se box for 1 e angle for 0 uma caixa é desenhada ao redor dos strings Exemplos plot2d01010 xstring0505Scilab não é esilaB outro exemplo alphabeta b c d e f g h i j k l m n o p q r s t u v w x y z xbasc plot2d01020 xstring0118alphabet alfabeto xstring0116alphabet01 alfabeto em uma caixa xstring0114alphabet20 ângulo xsetfont11 usando fontes symbol xstring0101alphabet xsetfont13 mudando tamanho da fonte xstring0103alphabet xsetfont124 xstring0106a alfa grande xsetdefault Ver Também titlepage xnumb xstringb xstringl xtitle Autor JPhC 854 Name xstringb escreve strings em uma caixa xstringbxystrwhoption Parâmetros xywh vetor de 4 escalares reais definindo a caixa str matriz de strings option string Descrição xstringb desenha a matriz de strings str centrada dentro do retângulo rectxywh ponto inferior esquerdo largura altura na escala gráfica corrente Se option for fornecido com o valor fill o tamanho do caractere é computado de modo a preencher o retângulo o máximo possível Entre com o comando xstringb para uma demonstração Exemplos strScilab nãoé elisaB plot2d0011010 0011 r00105 xstringbr1r2strr3r4fill xrectr1r2r4r3r4 rr1r2r4001r3r42 xrectr1r2r4r3r4 xstringbr1r2strr3r4fill rr1r2r4001r3r42 xrectr1r2r4r3r4 xstringbr1r2strr3r4fill Ver Também titlepage xstring xstringl xtitle Autor JPhC 855 Name xstringl computa uma caixa que cerca strings rectxstringlxystrfontIdfontSize Parâmetros rect vetor de reais de 4 entradas definindo a caixa xy escalares reais coordenadas do ponto infeirior esquerdo str matriz de strings fontId um inteiro especificando o tipo de fonte fontSize um inteiro especificando o tamanho da fonte Descrição xstringl retorna em rectxywh ponto superior esquerdo largura altura o tamanho do retângulo na escala de gráficos corrente que cerca os strings str escritos na localização xy ponto inferior esquerdo O resultado pode ser aproximado utilizandose um driver Postscript Exemplos plot2d01010 strScilab nãoé elisaB rxstringl0505str xrectsr1 r2r4 r3 r4 xstringr1r2str plot2d01010 strScilab nãoé Matlab r2 xstringl0505str25 xrectsr21 r22r24 r23 r24 xstringr21r22str txt2gce txt2fontsize 5 txt2fontstyle 2 Ver Também titlepage xstring xstringl xtitle stringbox Autor JPhC 856 Name xtitle adidciona títulos a janelas de gráficos xtitletitlexlabelylabelzlabeloptsargs Parâmetros titlexlabelylabel zlabel matrizes de strings optargs uma seqüência de declarações key1value1 key2value2 onde keys podem ser boxed ver abaixo Nesse caso a ordem não tem valor especial boxed um valor inteiro Se for 1 um retângulo é desenhado ao redor de cada título Descrição xtitle adiciona títulos a um esboço 2d ou 3d title é o título geral e xlabel ylabel e zlabel são os títulos dos três eixos Se os argumentos são matrizes cada linha das matrizes é exibida em uma linha diferente Entre com o comando xtitle para visualizar uma demonstração Exemplos desenhando uma superfície plot3d pondo os títulos xtitle Minha superfície é azul eixo X eixo Y eixo Z desenhando uma caixa ao redor dos títulos xtitle Minha superfície é azul eixo X eixo Y eixo Z boxed 1 Ver Também titlepage labelproperties Autor JPhC 857 Name zoomrect Amplia uma seleção da figura gráfica corrente zoomrect zoomrectrect zooomrecth zoomrecthrect Parâmetros rect vetor de tamanho 4 xminyminxmaxymax fornece o retângulo a ser ampliado h manipulador gráfico do tipo Figure ou Axes Especifica sobre que eixos se realizará a ampliação Descrição zoomrect é a função utilizada para realizar ampliações dentro de um conjunto de objetos Axes O argumento de entrada h especifica sobre que eixos se realizará a ampliação Se h for um manipulador do tipo Figure então a ampliação ocorrerá sobre seus galhos Axes Se h for um manipulador Axes a ampliação será aplicada apenas sobre este objeto Se h não for especificado então a ampliação será aplicada sobre a entidade Figure corrente Se o argumento de entrada rect for especificada então a propriedade zoombox dos eixos ampli ados será modificada por este argumento ver axesproperties Seus limites ao longo dos eixos X e Y serão substituídos por rect Se rect não for especificado zoomrect será uma ampliação interativa Requerse que o usuário selecione um retângulo utilizando o mouse A nova propriedade zoombox dos eixos ampliados é então computada encontrandose as interseções do retângulo com suas caixas de eixos Exemplos clf x00016pi plot2dxsinx2 zoomrect161181 mais zoom zoomrect1601621 de volta ao original unzoom ajustando o zoom através de axesproperties agca azoombox1601621 azoombox ajustando zoom de subesboços clf x00016pi subplot211 plot2dxcosx subplot212 plot2dxcos2x zoomrect 858 rect3 2 7 10 um retângulo especificado nas coordenadas dos eixos correntes os últimos zoomrectrect unzoom ajustando os eixos subjascentes globais como sendo os correntes fgcfsetcurrentaxesfchildren rect04 0 06 1 um retângulo especificado em razão do tamanho da janela zoomrectrect rect04 02 06 08 um retângulo especificado em razão do tamanho da janela zoomrectrect ampliação interativa sob a figura corrente zoomrect ou zoomrectgcf Ver Também unzoom axesproperties Autor Serge Steer INRIA JeanBaptiste Silvy INRIA 859 Name Math rendering in Scilab graphics Display mathematical equations in Scilab graphics through the LaTeX or MathML languages Usage Starting from Scilab 52 it is possible to write LaTeX or MathML expression LaTeX texts must start and end by dollar symbol while MathML texts must start by and end by and being syntactically valide On the first use these libraries are loading on the fly only when needed note that the MathML engine is slower to load than LaTeX Example with LaTeX MathML ticks plot2d agca mathmlmrowmfracmrowmidmimiymimrowmrowmidmimixmimrowmfracmomo mfracmn1mnmsupmiymimn2mnmsupmfracmrow LaTeX and MathML mixed expression axtickslabelsmathml1sinx3cosa test567 LaTeX description The rendering engine is based on the Java library JLaTeXMath JLaTeXMath is an implementation of the mathematic mode of LaTeX All LaTeX base commands are handle dont hesitate to submit a bug report if missing On the contrary TeX commands like over are not supported Since Scilab 521 greek cyrillic and complete unicode for latin alphabets characters are handled in the Scilab graphics xtitle extstylesumn1inftyfrac1n2fracpi26 xtitlebigbigg xtitlemboxVector field for ddot hetasin heta xtitleJLaTeXMath mathfrakand mathttScilab xstring0505overbrace underbrace µ JLaTeXMath provides several fonts with the commands mathbb mathscr mathcal mathbf mathit mathsf mathtt mathfrak mathds mathrm with their bold versions when they are available with the command boldsymbol xtitlemathbbSCILAB mathsfor boldsymbolmathfrakScilab xtitlemathscrCmbox nest pas boldsymbolmathcalC Different LaTeX packages are available amsmath amssymb stmaryrd amsxtra and ac cents with some commands of graphics Most of the commands of these packages are available some of amsmath are missing for example xtitlesidesetalphabetagammadeltaprod xtitlehataccentsetstarhat hundertildeABC Math rendering in Scilab graphics 860 xtitlebeginpmatrixmathfrakaalphamathbbAmathcalAendpmatrixmbox or beginbmatrixmathfrakaalphamathbbAmathcalAendbmatrix xstring0505leftfracpisqrt32middlesqrtfrac1frac1xxrightrangle xtitledoublecupddagfatbslashllloplusoveecircledcirccirclearrowright xtitlerotatebox180boxedJLaTeXMath reflectboxJLaTeXMath xtitlescalebox06sumn1inftyfrac1n2fracpi26 xtitlefcolorboxblackTanJLaTeXMath xtitle extcolorMagentamathfrakScilabmbox and extcolorGreenmathcalSCILAB It is also possible to define new commands or new environments xtitle ewcommandopleft ewcommandcpright opfrac12cp xtitle ewcommandmyfrac2fracmathfrak1mathcal2myfracAB MathML description The MathML rendering is based on Jeuclid Jeuclid is a MathML implementation which covers the whole specification Therefor all the MathML language is supported within Scilab Due to the size of the Jeuclid library on the first use it can take up to a few seconds to load However next uses are much faster plot3d agetcurrentaxes axlabelfontsize 5 axlabeltextmrowmfracmrowmn1mnmrowmrowmn2mnmrowmfracmomomfenced open close mrowmfracmrowmfracmrowmiamimrowmrowmibmimrowmfracmrowmrowmfracmrow micmimrowmrowmidmimrowmfracmrowmfracmrowmfencedmrow See Also xtitle axesproperties labelproperties legendproperties textproperties xstringb xstringl xstring Parte VII Gráficos exportando e imprimindo 862 Name driver seleciona um driver gráfico driverdrivername currentdriverdriver Parâmetros drivername string driver a ser selecionado Descrição Esta função seleciona um driver gráfico ou sem argumentos retorna o nome do driver gráfico cor rente Na maioria das vezes o usuário pode ignorar esta função e modificar o driver por uma chamada a funções de alto nível como xbasc O driver selecionado pode ser um dos seguintes X11 saída para a tela do computador Pos saída em formato Postscript Rec saída para a tela do computador É o mesmo que X11 Fig saída em formato XFig GIF saída em formato Gif PPM saída em formato PPM Observação Para converter arquivos GIF ou PPM para outro formato de imagem para construir uma animação podese utilizar o programa convert para ImageMagic httpwwwimagemagickorg Por exemplo se é gerada uma seqüência de arquivos Gif nomeada imggif é possível construir um arquivo Gif animado chamado animgif por convert delay 10 imggif animgif Ver Também xbasc Autor JPhC 863 Name xend termina uma sessão de gráficos xend Descrição xend é usado para encerrar uma sessão de gráficos Sob os drivers Postscript Xfig ou Gif xend fecha o arquivo que foi aberto por xinit Exemplos driverPos xinitfoops plot2d xend driverX11 Ver Também xinit Autor JPhC 864 Name xinit inicialização de um driver de gráficos xinitFileName xinit Parâmetros FileName string nome do arquivo a exportar Descrição Para os drivers Postscript Xfig Gif ou PPM FileName deve ser especificado É o nome do arquivo onde todas as operações gráficas são registradas Para os drivers X11 ou Rec xinit deve ser chamado sem nenhum argumento e abre uma janela de gráficos vazia Exemplos driverPos xinitfoops plot2d xend driverX11 Ver Também driver xend scf Autores JPhC JeanBaptiste Silvy 865 Name xs2bmp envia gráficos para um arquivo em sintaxe BMP xs2bmpwinnumfilen Parâmetros winnum escalar inteiro filen string nome do arquivo Descrição xs2bmp envia os gráficos gravados em uma janela winnum para o arquivo filen no formato BMP Exemplos scf0 plot2d Exportando para BMP xs2bmp0foobmp Ver Também xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf Autor AC 866 Name xs2emf envia gráficos para um arquivo em sintaxe EMF apenas para Windows xs2emfwinnumfilen orientation Parâmetros winnum escalar inteiro filen string o nome do arquivo orientation caractere opcional com valores possíveis p retrato ou l paisagem O valor padrão é p Descrição xs2emf envia os gráficos gravados em uma janela winnum para o arquivo filen no formato EMF Para o formato EMF criamos um arquivo EPS que será convertido para o formato EMFpor pstoedit Exemplos if MSDOS then scf0 plot2d Exportando para EMF xs2emf0fooemf end Ver Também xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig Autor AC 867 Name xs2eps salva gráficos em um arquivo Postscript xs2epswinnumfilen orientation Parâmetros winnum vetor de inteiros ou escalar inteiro filen string nome do arquivo orientation caractere opcional com possíveis valores p retrato ou l paisagem O valor padrão é p Descrição xs2eps salva os gráficos gravados da janela winnum em um arquivo filen em sintaxe Postscript Note que filen não deve ter extensão xs2eps produz um arquivo Postscript encapsulado completo Exemplos scf0 plot2d Exportando para EPS filenamefooeps xs2eps0filename Ver Também figuresize property toprint printfigure xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2pdf xs2svg xs2ps xs2fig xs2emf 868 Name xs2fig envia gráficos para um arquivo em sintaxe FIG xs2figwinnum filen orientation Parâmetros winnum escalar inteiro filen string nome do arquivo orientation caractere opcional com valores possíveis p retrato ou l paisagem O valor padrão é p Descrição xs2fig envia os gráficos gravados da janela winnum para o arquivo filen em formato FIG Para o formato FIG criamos um arquivo EPS que será convertido para o formato FIG por pstoedit Para exportar arquivos FIG o GPL Ghostscript 32bits precisa estar instalado Link para GPL Ghostscript httpwwwghostscriptcomawki Exemplos exemplo simples scf0 plot2d xs2fig0foofig Ver Também xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2emf Autor SK 869 Name xs2gif envia gráficos a um arquivo em sintaxe GIF xs2gifwinnumfilen Parâmetros winnum escalar inteiro ou vetor de inteiros filen string nome do arquivo Descrição xs2gif envia os gráficos gravados da janela window winnum para o arquivo filen em formato GIF Para converter uma seqüência de arquivos GIF em um arquivo GIF animado podese usar o programa convert para ImageMagic httpwwwimagemagickorg Por exemplo se for gerada uma seqüência de arquivos GIF chamada imggif é possível construir um arquivo GIF animado chamado animgif através da seqüência convert delay 10 imggif animgif Exemplos scf0 plot2d Exportando para GIF xs2gif0foogif Ver Também xs2bmp xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf 870 Name xs2jpg envia gráficos a um arquivo em sintaxe JPG xs2jpgwinnumfilen Parâmetros winnum escalar inteiro filen string nome do arquivo Descrição xs2jpg envia os gráficos gravados da janela winnum para o arquivo filen em formato JPG Exemplos scf0 plot2d Exportando para JPG xs2jpg0foojpg Ver Também xs2bmp xs2gif xs2png xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf Autor SK 871 Name xs2pdf salva gráficos a um arquivo PDF xs2pdfwinnumfilen orientation Parâmetros winnum escalar inteiro filen string nome do arquivo orientation caractere opcional com possíveis valores p retrato ou l paisagem O valor padrão é p Descrição xs2pdf salva os gráficos gravados da janela winnum em um arquivo filen in PDF syntax em sintaxe Postscript Note que filen não deve ter extensão Exemplos scf0 plot2d Exportando para PDF filenamefoo Sem extensão xs2pdf0filename Ver Também figuresize property toprint printfigure xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2svg xs2ps xs2fig xs2emf 872 Name xs2png envia gráficos a um arquivo em sintaxe PNG xs2pngwinnumfilen Parâmetros winnum escalar inteiro filen string nome do arquivo Descrição xs2png envia os gráficos gravados da janela winnum em um arquivo filen em formato PNG Exemplos scf0 plot2d Exportando para PNG xs2png0foopng Ver Também xs2bmp xs2gif xs2jpg xs2ppm xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf Autor SK 873 Name xs2ppm envia gráficos para um arquivo em sintaxe PPM xs2ppmwinnumfilen Parâmetros winnum vetor de inteiros ou escalar inteiro filen string o nome do arquivo Descrição xs2ppm envia os gráficos gravados em uma janela winnum para o arquivo filen em formato PPM Exemplos scf0 plot2d exportando para PPM xs2ppm0fooppm Ver Também xs2bmp xs2gif xs2jpg xs2png xs2eps xs2pdf xs2svg xs2ps xs2fig xs2emf 874 Name xs2ps envia gráficos a um arquivo em sintaxe PS xs2pswinnumfilenorientation Parâmetros winnum vetor de inteiros ou escalar inteiro filen string nome do arquivo orientation caractere opcional com possíveis valores p retrato ou l paisagem O valor padrão é p Descrição xs2ps salva os gráficos gravados da janela winnum em um arquivo filen em sintaxe Postscript Note que filen não deve ter extensão Note que o arquivo Postscript gerado não pode ser impresso diretamente desde requer cabeçalho A função xs2eps pode ser usada diretamente para produzir um arquivo Postscript encapsulado com cabeçalho Exemplos scf0 plot2d exportando para Postscript filenamefoops xs2ps0filename Ver Também figuresize property toprint printfigure xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2svg xs2fig xs2emf 875 Name xs2svg Salva gráficos em um arquivo SVG xs2svgwinnumfilen orientation Parâmetros winnum vetor de inteiros ou escalar inteiro filen string nome do arquivo orientation caractere opcional com possíveis valores p retrato ou l paisagem O valor padrão é p Descrição xs2svg salva os gráficos gravados da janela winnum em um arquivo filen em sintaxe Postscript Note que filen não deve ter extensão Exemplos scf0 plot2d exportando para SVG filenamefoosvg xs2svg0filename Ver Também figuresize property toprint printfigure xs2bmp xs2gif xs2jpg xs2png xs2ppm xs2eps xs2pdf xs2ps xs2fig xs2emf Parte VIII Booleanos 877 Name bool2s converte uma matriz de valores booleanos para uma matriz de valores 0 ou 1 bool2sx Parâmetros x um vetor ou matriz de valores booleanos ou uma matriz constante Descrição Se x é uma matriz de valores booleanos bool2sx retorna uma matriz onde os valores true ver dadeiro são substituidos por 1 e os valores false falso são substituidos por 0 Se x é uma matriz padrão bool2sx retorna uma matriz onde os valores nãonulos são substituídos por 1 Exemplos bool2st t f t bool2s23 0 10 1 Ver Também boolean find 878 Name find encontra índices de elementos verdadeiros em uma matriz ou vetor de booleanos iifindx nmax i1i2findx nmax Parâmetros x pode ser um vetor matriz ou hipermatriz de booleanos uma matriz ou hipermatriz padrão nmax um inteiro fornecendo o número máximo de índices a serem retornados o valor padrão é 1 que significa todos Esta opção pode ser usada por eficiência para evitar uma busca por todos os índices ii i1 i2 vetores de índices inteiros ou matrizes vazias Descrição Se x é uma matriz booleana iifindx retorna o vetor de índices i para os quais xi é true verdadeiroSe nenhum elemento true for encontrado retorna uma matriz vazia i1i2findx retorna vetores de índices i1 para linhas e i2 para colunas tais que xi1ni2n ié true verdadeiro Se nenhum elemento true for encontrado retorna matrizes vazias em i1 i2 Se x é uma matriz ou hipermatriz padrão findx é interpretado como findx0 find retorna Exemplos Arand120 wfindA04 Aw wfindA100 Brand120 wfindB042 no máximo dois valores retornados Hrand435 uma hipermatriz ijkfindH09 Hi1j1k1 Ver Também boolean extraction insertion vectorfind Parte IX CACSD 880 Name black diagrama de Black carta de Nichols black slfminfmax step comments black slfrq comments blackfrqdbphi comments blackfrqrepf comments Parâmetros sl lista sistema linear syslin fminfmax reais limites de freqüência frq vetor linha ou matriz freqüências dbphi vetores linhas ou matrizes módulo fase repf vetores linhas ou matrizes resposta de freqüência complexa step real comments string Descrição Diagrama de Black carta de Nichols para um sistema linear sl sl pode ser um sistema SIMO de tempo contínuo ou discreto ver syslin No caso de múltiplas saídas elas são esboçadas com símbolos diferentes As freqüências são dadas pelos limites fminfmax em Hz ou por um vetor linha ou uma matriz para múltiplas saídas frq step é o passo de discretização logarítmica ver calfrq para escolha do valor padrão comments é um vetor de strings legendas dbphi são matrizes de módulos em Db e fases em graus Uma linha para cada resposta repf matriz de números complexos Uma linha para cada resposta Para esboçar o grid de isoganho e isofase de y1y use chart Valores padrões para fmin e fmax são 1d3 1d3 se sl for de tempo contínuo ou 1d3 05sldt freqüência de Nyquist se sl for de tempo discreto Exemplos spoly0s hsyslincs220910s100s2203101s10201 black 881 clfblackh001100 chartlist10 h1hsyslincs2201151s22801s220915s225 clf blackh1h001100h1h chartlist10 Ver Também bode nyquist chart freq repfreq calfrq phasemag 882 Name bode diagrama de Bode bodeslfminfmax step comments bodeslfrq comments bodefrqdbphi comments bodefrq repf comments Parâmetros sl syslin lista sistema linear SISO ou SIMO em tempo contínuo ou discreto fminfmax real limites de freqüência em Hz step real passo logarítmico comments vetor de strings legendas frq vetor linha ou matriz freqüências em Hz uma linha para cada subsistema SISO db vetor linha ou matriz magnitudes em Db um para cada subsistema SISO phi vetor linha ou matriz fases em graus um para cada subsistema SISO repf vetor linha ou matriz de números complexos freqüência de resposta complexa Descrição Diagrama de bode ie magnitude e fase da freqüência de resposta de sl sl pode ser um sistema SIMO de tempo contínuo ou discreto ver syslin No caso de múltiplas saídas elas são esboçadas com símbolos diferentes As freqüências são dadas pelos limites fminfmax em Hz ou por um vetor linha ou uma matriz para múltiplas saídas frq step é o passo de discretização logarítmica ver calfrq para escolha do valor padrão comments é um vetor de strings legendas dbphi são matrizes de módulos em Db e fases em graus Uma linha para cada resposta repf matriz de números complexos Uma linha para cada resposta Valores padrões para fmin e fmax são 1d3 1d3 se sl for de tempo contínuo ou 1d3 05 sldt freqüência de Nyquist se sl for de tempo discreto Discretização automática das freqüências é feita por calfrq Exemplos bode 883 spoly0s hsyslincs220910s100s2203101s10201 tits220910s100s2203101s10201 bodeh001100tit h1hsyslincs2201151s22801s220915s225 clf bodeh1h001100h1h Ver Também black nyquist gainplot repfreq gmargin pmargin calfrq phasemag 884 Name chart carta de Nichols chartflags chartgain flags chartgainphase flags Parâmetros gain vetor de reais ganhos em DB decibel phase vetor de reais fases em graus flags uma lista de no máximo quatro flags sup leg cm cphi sup 1 indica superposição sobre o esboço anterior e 0 indica que nenhuma superposição é feita leg 1 indica que as legendas são impressas 0 indica sem legendas cm número da cor para curvas de ganho cphi número da cor para curvas de fase Descrição Esboça a carta de Nichols curvas de nível de isoganho e isofase dey1y no plano de faseganho chart pode ser utilizado em conjunção a black Os valore padrões para gain e phase são respectivamente 12 8 6 5 4 3 2 14 1 5 025 05 07 1 14 2 23 3 4 5 6 8 12 110 2010160 Exemplos spoly0s hsyslincs220910s100s2203101s10201 blackh001100 chartlist1023 clf h1hsyslincs2201151s22801s220915s225 blackh1h001100h1h setgcadatabounds180 30180 30 aumentando a moldura chartlist10 Ver Também nyquist black 886 Name evans lugar geométrico das raízes Evans evansH kmax Parâmetros H lista sistema linear syslin kmax real ganho máximo desejado para o esboço Descrição Fornece o lugar geométrico das raízes Evans para um sistema linear em estadoespaço ou forma de transferência Hs lista syslin Este é o lugar geométrico das raízes de 1kHs1kNs Ds no plano dos complexos Para uma amostra seleta de ganhos k kmax a parte imaginária das raízes de DskNs é esboçada versus a parte real Para obter o ganho num dado ponto do lugar geométrico você pode simplesmente executar a seguinte instrução k1realhornerh1ilocate1 e clicar no ponto desejado sobre lugar geométrico das raízes Se as coordenadas dos pontos selecionados estão no vetor de reais 2 x 1 Plocate1 este k resolve a equação kNw Dw 0 com wP1iP21 iP Exemplos Hsyslinc352poly5spoly002000200251sc evansH100 P30548543 88491842i Pponto selecionado k1realhornerHP NsHnumDsHden rootsDskNs contém P como raiz particular outro clfspoly0sn1s drealpoly1 2 i is evansnd100 clfnrealpoly01i 01i10s evansnd80 Ver Também kpure krac2 locate 887 Name gainplot esboço de magnitude gainplotslfminfmax step comments gainplotfrqdbphi comments gainplotfrq repf comments Parâmetros sl lista sistema linear syslin SIMO fminfmax escalares reais intervalo de freqüência step real passo de discretização escala logarítmica comments string frq matriz freqüências linha por linha dbphi matrizes magnitudes e fases correspondentes a frq repf matriz de complexos Uma linha para cada resposta de freqüência Descrição É o mesmo que Bode mas esboça apenas a magnitude Exemplos spoly0s hsyslincs220910s100s2203101s10201 gainploth001100s220910s100s2203101s10201 clf h1hsyslincs2201151s22801s220915s225 gainploth1h001100h1h Ver Também bode black nyquist freq repfreq gmargin pmargin 888 Name mcircle esboça os contornos de isoganho y1y plano complexo mcircle mcirclegain Parâmetros gain vetor de ganhos em DB decibel O valor padrão é gain 12 8 6 5 4 3 2 14 1 5 025 05 07 1 14 2 23 3 4 5 6 8 12 Descrição mcircle desenha os contornos de isoganho fornecidos pelo argumento gain no plano complexo ReIm O valor padrão para gain é 12 8 6 5 4 3 2 14 1 5 025 05 07 1 14 2 23 3 4 5 6 8 12 mcircle é utilizado com nyquist Exemplos Exemplo 1 spoly0s hsyslincs220910s100s2203101s10201 nyquisth001100s220910s100s2203101s10201 mcircle Exemplo 2 xbasc h1hsyslincs2201151s22801s220915s225 nyquisth1h001100h1h mcircle8 6 4 Ver Também nyquist chart black Autor SSteer 889 Name nyquist diagrama de Nyquist nyquist slfminfmax step comments nyquist sl frq comments nyquistfrqdbphi comments nyquistfrq repf comments Parâmetros sl syslin sistema linear SIMO em tempo contínuo ou discreto fminfmax reais limites de freqüência em Hz step real passo de discretização logarítmica comments vetor de strings legendas frq vetor linha ou matriz freqüências em Hz um linha para cada saída de sl dbphi vetores linhas ou matrizes de módulo em Db e fases uma linha para cada saída de sl repf vetor linha ou matriz de números complexos freqüência de resposta complexa uma para cada saída de sl Descrição Diagrama de Nyquist ie parte imaginária versus parte real da freqüência de resposta de sl Para sistmeas de tempo contínuo sl2ipiw é esboçado Para sistemas de tempo discreto ou sistemas discretizados slexp2ipiwfd é utilizado fd1 para sistemas de tempo discreto e fdsldt para sistemas discretizados sl para sistemas discretizados syslin No caso de múltiplas saídas elas são esboçadas com símbolos diferentes As freqüências são dadas pelos limites fminfmax em Hz ou por um vetor linha ou uma matriz para múltiplas saídas frq step é o passo de discretização logarítmica ver calfrq para escolha do valor padrão comments é um vetor de strings legendas dbphi são matrizes de módulos em Db e fases em graus Uma linha para cada resposta repf é uma matriz de números complexos Uma linha para cada resposta Valores padrões para fmin e fmax são 1d3 1d3 se sl for de tempo contínuo 1d3 05 sldt freqüência de Nyquist se sl for de tempo discreto Discretização automática das freqüências é feita por calfrq nyquist 890 Exemplos clf spoly0s hsyslincs220910s100s2203101s10201 comms220910s100s2203101s10201 nyquisth001100comm h1hsyslincs2201151s22801s220915s225 clf nyquisth1h001100h1h clfnyquisth1h Ver Também bode black calfrq freq repfreq phasemag 891 Name routht tabela de Routh rrouthth k Parâmetros h matriz quadrada de razões de polinômios Descrição rrouththk computa a tabela de Routh do denominador do sistema descrito pela matriz de transferência SISO h com a resposta pelo ganho k se kpoly0k teremos uma matriz de polinômios com variável livre k expressão formal da tabela de Routh 892 Name sgrid esboça linhas de grid de um splano sgrid sgridnew sgridzetawn color Descrição Usado em conjunto com evans esboça linhas de taxa de amortecimento constante zeta e freqüência natural wn sgrid adiciona um grid sobre uma raiz do splano contínuo existente com valores padrões para zeta e wn sgridnew limpa a tela de gráficos e então esboça um grid de splano padrão sgridzetawn color é o mesmo que sgrid mas utiliza a taxa de amortecimento e a freqüência natural fornecidas Exemplos Hsyslinc352poly5spoly002000200251sc evansH100 sgrid sgrid0627 Ver Também evans 893 Name zgrid esboçode um zgrid zgrid Descrição Esboça as linhas de grid de um Zplano linhas de fator constante de amortecimento zeta e freqüência natural Wn são esboçadas dentro do círculo unitário do Zplano Curvas de isofreqüência são exibidas em freqüênciapasso no intervalo 005 O limite superior corresponde à freqüência de Shannon 1dt 2f Ver Também frep2tf freson 894 Name abcd statespace matrices ABCDabcdsl Parameters sl linear system syslin list in statespace or transfer form ABCD real matrices of appropriate dimensions Description returns the ABCD matrices from a linear system Sl Utility function For transfer matrices Sl is converted into statespace form by tf2ss The matrices ABCD are the elements 2 to 5 of the syslin list Sl ie ABCD Sl25 Examples Adiag123B111C222 syssyslincABC sysA sysC A1B1C1D1abcdsys A1 systfss2tfsys abcdabcdsystf speca cbCB cabCAB See Also syslin ssrand 895 Name abinv AB invariant subspace XdimsFUkZabinvSysalphabetaflag Parameters Sys syslin list containing the matrices ABCD alpha optional real number or vector possibly complex location of closed loop poles beta optional real number or vector possibly complex location of closed loop poles flag optional character string ge default or st or pp X orthogonal matrix of size nx dim of state space dims integer row vector dimsdimRdimVgdimVnocnos with dimRdimVgdimVnocnos If flagst resp pp dims has 4 resp 3 components F real matrix state feedback k integer normal rank of Sys Z nonsingular linear system syslin list Description Output nulling subspace maximal unobservable subspace for Sys linear sys tem defined by a syslin list containing the matrices ABCD of Sys The vector dimsdimRdimVgdimVnocnos gives the dimensions of subspaces defined as columns of X according to partition given below The dimV first columns of X ie VX1dimV span the ABinvariant subspace of Sys ie the unobservable subspace of ABFCDF dimVnx iff C1DX The dimR first columns of X ie RX1dimR spans the controllable part of Sys in V dimRdimV dimR0 for a left invertible system R is the maximal controllability subspace of Sys in kernelC The dimVg first columns of X spans Vgmaximal ABstabilizable subspace of Sys dimRdimVgdimV F is a decoupling feedback for XVX2 X2XdimV1nx one has X2A BFV0 and CDFV0 The zeros od Sys are given by X0XdimR1dimV specX0ABFX0 ie there are dimVdimR closedloop fixed modes abinv 896 If the optional parameter alpha is given as input the dimR controllable modes of ABF in V are set to alpha or to alpha1 alpha2 alpha can be a vector real or complex pairs or a real number Default value alpha1 If the optional real parameter beta is given as input the nocdimV controllable modes of ABF outside V are set to beta or beta1beta2 Default value beta1 In the XU bases the matrices XABFXXBUCDFXDU are displayed as follows A11 B11 0A22 0 00A33 0 000A44 0 B42 0000A55 0 0 00000A66 0 0 000 0 D2 where the Xpartitioning is defined by dims and the Upartitioning is defined by k A11 is dimR x dimR and has its eigenvalues set to alphais The pair A11B11 is controllable and B11 has nuk columns A22 is a stable dimVgdimR x dimVgdimR matrix A33 is an unstable dimVdimVg x dimVdimVg matrix see stility A44 is nocdimV x nocdimV and has its eigenvalues set to betais The pair A44B42 is controllable A55 is a stable nosnoc x nosnoc matrix A66 is an unstable nxnos x nxnos matrix see stility Z is a column compression of Sys and k is the normal rank of Sys ie SysZ is a columncompressed linear system k is the column dimensions of B42B52B62 and D2 B42B52B62D2 is full column rank and has rank k If flagst is given a five blocks partition of the matrices is returned and dims has four components If flagpp is given a four blocks partition is returned In case flagge one has dimsdimRdimVgdimVdimVnc2dimVns2 where nc2 resp ns2 is the dimension of the controllable resp stabilizable pair A44B42 resp A440A55 B420 In case flagst one has dimsdimRdimVgdimVgncdimVgns and in case flagpp one has dimsdimRdimRncdimRns nc resp ns is here the di mension of the controllable resp stabilizable subspace of the blocks 3 to 6 resp 2 to 6 This function can be used for the exact disturbance decoupling problem DDPS Find uFxRdFRxd which rejects Qd and stabilizes the plant xdot AxBuQd y CxDuTd DDPS has a solution if ImQ is included in Vg ImB and stabilizability assumption is satisfied Let GXdimVg1 left annihilator of Vg ie GVg0 B2GB Q2GQ DDPS solvable iff B2DR Q2T 0 has a solution The pair FR is the solution with Foutput of abinv ImQ2 is in ImB2 means rowcompression of B2rowcompression of Q2 Then CsIABF1DQBR 0 GQBR0 abinv 897 Examples nu3ny4nx7 nrt2ngt3ng03nvt5rk2 flaglistonnrtngtng0nvtrk Sysssrandnynunxflagmyalpha1mybeta2 XdimsFUkZabinvSysmyalphamybeta ABCDabcdSysdimVdims3dimRdims1 VX1dimVX2XdimV1nx X2ABFV CDFV X0XdimR1dimV specX0ABFX0 trzerosSys specABF nr2 evals at 1 and nocdimV2 evals at 2 cleanss2tfSysZ 2nd Example nx6ny3nu2 Adiag16A227A559B120304050000 CzerosnynyeyenynyD010203 slsyslincABCDslss2ssslrand66rand22 ABCDabcdsl The matrices of sl myalpha1mybeta2 XdimsFUkZabinvslmyalphamybetadimVgdims2 cleanXABFX cleanXBU cleanCDFX cleanDU GXdimVg1 B2GBnd3 RrandnundQ2TB2DR psizeG1Q2Q2T1pTQ2Tp1 QGQ2 a valid QT since GBDR GQT is zero closedsyslincABFQBRCDFTDR closed loop dy ss2tfclosed Closed loop is zero specclosedA The plant is not stabilizable nsncWsl1stilitysl ABCDabcdsl1AA1ns1nsBB1nsCC1ns slnewsyslincABCD Now stabilizable FnewstabilslnewAslnewB11 slnewAslnewAslnewBFnew slnewCslnewCslnewDFnew XdimsFUkZabinvslnewmyalphamybetadimVgdims2 ABCDabcdslnew GXdimVg1 B2GBnd3 RrandnundQ2TB2DR psizeG1Q2Q2T1pTQ2Tp1 QGQ2 a valid QT since GBDR GQT is zero closedsyslincABFQBRCDFTDR closed loop dy ss2tfclosed Closed loop is zero specclosedA abinv 898 See Also cainv stility ssrand ss2ss ddp Authors FD 899 Name arhnk Hankel norm approximant slmarhnkslordtol Parameters sl linear system syslin list ord integer order of the approximant tol threshold for rank determination in equil1 Description computes slm the optimal Hankel norm approximant of the stable continuoustime linear system sl with matrices ABCD Examples Adiag12345Brand51Crand15 slsyslincABC slapproxarhnksl2 nkWhankelsvslnk nkredWredhankelsvslapproxnkred See Also equil equil1 hankelsv 900 Name arl2 SISO model realization by L2 transfer approximation harl2yden0n imp harl2yden0n impall dennumerrarl2yden0n imp dennumerrarl2yden0n impall Parameters y real vector or polynomial in z1 it contains the coefficients of the Fouriers series of the rational system to approximate the impulse response den0 a polynomial which gives an initial guess of the solution it may be poly1zc n integer the degree of approximating transfer function degree of den imp integer in 012 verbose mode h transfer function numden or transfer matrix column vector when flag all is given den polynomial or vector of polynomials contains the denominators of the solutions num polynomial or vector of polynomials contains the numerators of the solutions err real constant or vector the l2error achieved for each solutions Description dennumerrarl2yden0n imp finds a pair of polynomials num and den such that the transfer function numden is stable and its impulse response approximates with a minimal l2 norm the vector y assumed to be completed by an infinite number of zeros If yz y11zy21z2 yny1zny then l2norm of numden yz is err n is the degree of the polynomial den The numden transfer function is a L2 approximant of the Fouriers series of the rational system Various intermediate results are printed according to imp dennumerrarl2yden0n impall returns in the vectors of polynomials num and den a set of local optimums for the problem The solutions are sorted with increasing errors err In this case den0 is already assumed to be poly1zc Examples arl2 901 vones120 clf plot2d1enn0vzeros8012051 10510015 dnearl2vpoly1zc1 plot2d1enn0ldivnd1002000 dnearl2vd3 plot2d1enn0ldivnd1003000 dnearl2vd8 plot2d1enn0ldivnd1005000 dnearl2vpoly1zc4all plot2d1enn0ldivn1d110010000 See Also ldiv imrep2ss timeid armax frep2tf 902 Name arma Scilab arma library Description Armax processes can be coded with Scilab tlist of type ar armac is used to build Armax scilab object An ar tlist contains the fields abdnynusig armac this function creates a Scilab tlist which code an Armax process Az1y Bz1u Dz1siget ararmac1234111sig ara ans 1 2 arsig ans 1 armapar out Display the armax equation associated with ar armappar out Display the armax equation associated with ar using polynomial matrix display ABDarmap2par extract polynomial matrices from ar representation armax is used to identify the coefficients of a ndimensional ARX process Az1y Bz1u siget armax1 armax1 is used to identify the coefficients of a 1dimensional ARX process Az1y Bz1u Dz1siget arsimul armax trajectory simulation narsimul armax simulation using rtitr odedi Simple tests of ode and arsimul Tests the option discret of ode prbsa pseudo random binary sequences generation reglin Linear regression Example arma 903 Example extracted from the demo arma3demsce in the cacsd module Spectral power estimation form Sawaragi et all m 18 a 1131361440110919083527 b 000131370023543010775003516 u rand11000n z arsimulab00u Using macro mese smfrmesezm The theorical result function gxgxxzab w expi2piz04 gx absbw2absaw2 endfunction res for xfr res res gxxxab end using armax estimation of order 44 its a bit tricky because we are not supposed to know the order arclalbsigresidarmax44zu res1 for xfr res1 res1 gxxxla1lb1 end visualization of the results plot2dfrfrfr20log10smsm120log10resres120log10res1res11211 legendUsing macro meseTheoretical valueArma identification xtitleSpectral powerfrequencyspectral estimate Authors JPC 904 Name arma2p extract polynomial matrices from ar representation ABDarma2par Parameters ABD three polynomial matrices ar Scilab ar tlist for arma storage see armac Description this function extract polynomial matrices ABD from an armax description Examples a1285127170865eye22 b011111 d10702eye22 sigeye22 ararmacabd21sig extract polynomial matrices from ar representation ABDarma2par See Also arma armax armax1 arsimul armac 905 Name armac Scilab description of an armax process ararmacabdnynusig Parameters aIda1ar is a matrix of size nyrny bb0bs is a matrix of size nys1nu dIdd1dp is a matrix of size nypny ny dimension of the output y nu dimension of the output u sig a matrix of size nyny Description This function creates a description as a tlist of an ARMAX process ar is defined by artlistarabdnynusigabdnynusig and thus the coefficients of ar can be retrieved by eg ara Examples a1285127170865eye22 b011111 d10702eye22 sigeye22 ararmacabd21sig extract polynomial matrices from ar representation ABDarma2par See Also arma armax armax1 arsimul arma2p tlist 906 Name armax armax identification arclalbsigresidarmaxrsyub0fprf Parameters y output process ynyn ny dimension of y n sample size u input process unun nu dimension of u n sample size r and s autoregression orders r 0 et s 1 b0f optional parameter Its default value is 0 and it means that the coefficient b0 must be identified if bof1 the b0 is supposed to be zero and is not identified prf optional parameter for display control If prf 1 the default value a display of the identified Arma is given arc a Scilab arma object see armac la is the listaaetaaeta la a in dimension 1 where eta is the estimated standard deviation aIda1a2ar where each ai is a matrix of size nyny lb is the listbbetbbetb lb b in dimension 1 where etb is the estimated standard deviation bb0bs where each bi is a matrix of size nunu sig is the estimated standard deviation of the noise and resid siget0 Description armax is used to identify the coefficients of a ndimensional ARX process Az1y Bz1u siget where et is a ndimensional white noise with variance I sig an nxn matrix and Az and Bz Az 1a1zarzr r0 Az1 Bz b0b1zbs zs s1 Bz0 for the method see Eykhoff in trends and progress in system identification page 96 with ztyt1ytrututs and coef a1 arb0bs we can write yt coef zt siget and the algorithm minimises sumt1N yt coefzt2 where t0maximaxirs11 armax 907 Examples Ex1 Arma model yt 02ut1001et1 ny1nu1sig001 Armaarmac100201nynusig defining the above arma model urand11000normal a random input sequence u yarsimulArmau simulation of a y output sequence associated with u Armaestarmax01yu Identified model given u and y AcoeffArmaesta Coefficients of the polynomial Ax BcoeffArmaestb Coefficients of the polynomial Bx DcoeffArmaestd Coefficients of the polynomial Dx AxBxDxarma2pArmaest Results in polynomial form Ex2 Arma1 yt 08yt1 02yt2 siget ny1nu1sig0001 First step simulation the Arma1 model for that we define Arma2 yt 08yt1 02yt2 sigut with normal deviates for ut Arma2armac10802sig0nynu0 Definition of the Arma2 arma model a model with Bsig and without noise urand110000normal An input sequence for Arma2 yarsimulArma2u y output of Arma2 with input u can be seen as output of Arma1 Second step identification We look for an Arma model yt a1yt1 a2 yt2 siget Arma1estarmax21y ABDarma2pArma1est See Also imrep2ss timeid arl2 armax frep2tf Authors JPh Chancelier 908 Name armax1 armax identification arcresidarmax1rsqyu b0f Parameters y output signal u input signal rsq auto regression orders with r 0 s 1 b0f optional parameter Its default value is 0 and it means that the coefficient b0 must be identified if bof1 the b0 is supposed to be zero and is not identified arc is tlist with type ar and fields a b d ny nu sig a is the vector 1a1ar b is the vector b0bs d is the vector 1d1dq sig resid sigechap1 Description armax1 is used to identify the coefficients of a 1dimensional ARX process Az1y Bz1u Dz1siget et is a 1dimensional white noise with variance 1 Az 1a1zarzr r0 Az1 Bz b0b1zbs zs s1 Bz0 Dz 1d1zdqzq q0 Dz1 for the method see Eykhoff in trends and progress in system identification page 96 with ztyt1ytrut utset1etq and coef a1arb0bsd1dq armax1 909 yt coef zt siget a sequential version of the AR estimation where eti is replaced by an estimated value is used RLLS With q0 this method is exactly a sequential version of armax Important notice In Scilab versions up to 412 the returned value in arcsig is the square of sig square To be conform with the help the display of arma models and the armax function starting from Scilab50 version the returned arcsig is sig Authors JPhC 910 Name arsimul armax simulation zarsimulabdsiguupypep zarsimularuupypep Parameters ar an armax process See armac a is the matrix Ida1ar of dimension nr1n b is the matrix b0bs of dimension ns1m d is the matrix Idd1dt of dimension nt1n u is a matrix mN which gives the entry ujuj sig is a nn matrix ek is an ndimensional Gaussian process with variance I up yp optional parameter which describe the past up u0u1us1 yp y0y1yr1 ep e0e1er1 if they are omitted the past value are supposed to be zero z zy1yN Description simulation of an ndimensional armax process Az1 zk Bz1uk Dz1sigek Az Ida1zarzr r0 AzId Bz b0b1zbs zs s1 Bz Dz Idd1zdt zt t0 DzId z et e are in Rn et u in Rm Method a statespace representation is constructed and ode with the option discr is used to compute z Authors JPhC 911 Name augment augmented plant PraugmentG PraugmentGflag1 PraugmentGflag1flag2 Parameters G linear system syslin list the nominal plant flag1 one of the following upper case character string S R T SR ST RT SRT flag2 one of the following character string o stands for output this is the default value or i stands for input P linear system syslin list the augmented plant r 1x2 row vector dimension of P22 G Description If flag1SRT default value returns the full augmented plant I G S 0 I R P 0 G T I G S R T refer to the first three block rows of P respectively If one of these letters is absent in flag1 the corresponding row in P is missing If G is given in statespace form the returned P is minimal P is calculated by I000I0 I0II00IG0II0 The augmented plant associated with input sensitivity functions namely I I S input sensitivity G G R Ginput sensitivity P 0 I T KGinput sensitivity G G is obtained by the command PraugmentGflagi For statespace G this P is calcu lated by II000I000I0IGII and is thus generically minimal augment 912 Note that weighting functions can be introduced by leftmultiplying P by a diagonal system of appro priate dimension eg P sysdiagW1W2W3eyeGP Sensitivity functions can be calculated by lft One has For output sensitivity functions PraugmentPSRT lftPrKinveyeGKKinveyeGKGKinveyeGK For input sensitivity functions PraugmentPSRTi lftPrKinveyeKGGinveyeKGKGinveyeGK Examples Gssrand232 Plant Kssrand322 Compensator PraugmentGT TlftPrK Complementary sensitivity function Ktfss2tfKGtfss2tfG Ttfss2tfTT11Ttf11 OloopGtfKtf TnOloopinveyeOloopOloop cleanT11Tn11 PiraugmentGTi T1lftPirKT1tfss2tfT1 Input Complementary sensitivity function OloopKtfGtf T1nOloopinveyeOloopOloop cleanT1tf11T1n11 See Also lft sensi 913 Name balreal balanced realization slb U balrealsl Parameters slslb linear systems syslin lists Description Balanced realization of linear system slABCD sl can be a continuoustime or discretetime statespace system sl is assumed stable slbinvUAU invUB CU D is the balanced realization slb is returned as a syslin list Examples Adiag12345Brand52Crand15 slsyslincABC slbUbalrealsl Wccleanctrgramslb W0cleanobsgramslb See Also ctrgram obsgram hankelsv equil equil1 914 Name bilin general bilinear transform sl1bilinslv Parameters slsl1 linear systems syslin lists v real vector with 4 entries vabcd Description Given a linear system in state space form slsyslindomABCD syslin list sl1bilinslv returns in sl1 a linear system with matrices A1B1C1D1 such that the transfer function H1sC1invseyeA1B1D1 is obtained from HzCinvzeyeABD by replacing z by zasbcsd One has wbilinbilinwabcddbca Examples spoly0szpoly0z wssrand113 wtfss2tfwv2314av1bv2cv3dv4 hornerwtfazbczdss2tfbilinwabcd cleanss2tfbilinbilinwabcddbcawtf See Also horner cls2dls 915 Name bstap hankel approximant QbstapSl Parameters sl linear system syslin list assumed continuoustime and antistable Q best stable approximation of Sl syslin list Description Computes the best approximant Q of the linear system Sl where T is the Hinfinity norm of the Hankel operator associated with Sl See Also syslin 916 Name cainv Dual of abinv XdimsJYkZcainvSlalfabetaflag Parameters Sl syslin list containing the matrices ABCD alfa real number or vector possibly complex location of closed loop poles beta real number or vector possibly complex location of closed loop poles flag optional character string ge default or st or pp X orthogonal matrix of size nx dim of state space dims integer row vector dimsnd1nu1dimSdimSgdimN 5 entries nondecreasing orderIf flagst resp pp dims has 4 resp 3 components J real matrix output injection Y orthogonal matrix of size ny dim of output space k integer normal rank of Sl Z nonsingular linear system syslin list Description cainv finds a bases XY of state space and output space resp and output injection matrix J such that the matrices of Sl in bases XY are displayed as A11 0A22 XAJCX 00A33 XBJD 000A44 0 0000A55 0 00000A66 0 YCX 00C13 YD 00000C26 0 The partition of X is defined by the vector dimsnd1nu1dimSdimSgdimN and the par tition of Y is determined by k cainv 917 Eigenvalues of A11 nd1 x nd1 are unstable Eigenvalues of A22 nu1nd1 x nu1nd1 are stable The pair A33 C13 dimSnu1 x dimSnu1 k x dimSnu1 is observable and eigenvalues of A33 are set to alfa Matrix A44 dimSgdimS x dimSgdimS is unstable Matrix A55 dimNdimSgdimN dimSg is stable The pair A66C26 nxdimN x nxdimN is observable and eigenvalues of A66 set to beta The dimS first columns of X span S smallest CA invariant subspace which contains ImB dimSg first columns of X span Sg the maximal complementary detectability subspace of Sl The dimN first columns of X span the maximal complementary observability subspace of Sl dimS0 if BkerD0 If flagst is given a five blocks partition of the matrices is returned and dims has four com ponents If flagpp is given a four blocks partition is returned see abinv This function can be used to calculate an unknown input observer DDEP dotxA x Bu Gd y Cx observation z Hx zvariable to be estimated ddisturbance Find dotw Fw Ey Ru such that zhat Mw Ny zHx goes to zero at infinity Solution exists iff Ker H contains SgACG inter KerC assuming detectability ie H is such that For any W which makes a column compression of Xp1dimSgC with XpX and XdimsJYkZcainvsyslincAGC Xp1dimSgCW 0 one has HW 0 with at least as many aero columns as above See Also abinv dtility uiobserver 918 Name calfrq frequency response discretization frqbndssplitcalfrqhfminfmax Parameters h Linear system in state space or transfer representation see syslin fminfmax real scalars min and max frequencies in Hz frq row vector discretization of the frequency interval bnds vector Rmin Rmax Imin Imax where Rmin and Rmax are the lower and upper bounds of the frequency response real part Imin and Imax are the lower and upper bounds of the frequency response imaginary part split vector of frq splitting points indexes Description frequency response discretization frq is the discretization of fminfmax such that the peaks in the frequency response are well represented Singularities are located between frqsplitk1 and frqsplitk for k1 Examples spoly0s hsyslincs220910s100s2203101s10201 h1hsyslincs2201151s22801s220915s225 f1bndssplcalfrqh10011000 rfrepfreqh1f1 plot2drealrfimagrf See Also bode black nyquist freq repfreq logspace 919 Name canon canonical controllable form AcBcUindcanonAB Parameters AcBc canonical form U current basis square nonsingular matrix ind vector of integers controllability indices Description gives the canonical controllable form of the pair AB AcinvUAU BcinvUB The vector ind is made of the epsilonis indices of the pencil sI A B decreasing order For example with ind32 Ac and Bc are as follows 10000 0 Ac 01000 Bc0 00010 0 If AB is controllable by an appropriate choice of F the entries of AcBcF can be arbitrarily set to desired values pole placement Examples A12345 10000 01000 67890 00010 B12 00 00 21 00 Xrand55AXAinvXBXB Controllable pair AcBcUindcanonAB Two indices ind32 index1for k1sizeind1indexindex1sumind1kend AcstarAcindexBcstarBcindex spoly0s p1s32s25s3p2s5s3 p1 and p2 are desired closedloop polynomials with degrees 32 c1coeffp1c1c1111c2coeffp2c2c2111 canon 920 Acstardesiredc100000c2 Acstardesiredindex is companion matrix with char polp1p2 FBcstarAcstardesiredAcstar Feedbak gain AcBcF Companion form specABFU FU is the gain matrix in original basis See Also obsvmat contmat ctrgram contrss ppol contr stabil Authors FD 921 Name ccontrg central Hinfinity controller KccontrgPrgamma Parameters P syslin list linear system in statespace representation r 1x2 row vector dimension of the 22 part of P gamma real number Description returns a realization K of the central controller for the general standard problem in statespace form Note that gamma must be gopt ouput of gamitg P contains the parameters of plant realization ABCD syslin list with B B1 B2 C C1 D D11 D12 C2 D21 D22 r1 and r2 are the dimensions of D22 rows x columns See Also gamitg hinf Authors P Gahinet INRIA 922 Name cls2dls bilinear transform sl1cls2dlsslT fp Parameters slsl1 linear systems syslin lists T real number the sampling period fp prevarping frequency in hertz Description given slABCD syslin lista continuous time system cls2dls returns the sampled sys tem obtained by the bilinear transform s2Tz1z1 Examples spoly0szpoly0z slsyslincs1s25s2 Continuoustime system in transfer form slsstf2sssl Now in statespace form sl1cls2dlsslss02 sl1 output of cls2dls sl1tss2tfsl1 Converts in transfer form sl2hornersl202z1z1 Compare sl2 and sl1 See Also horner 923 Name colinout innerouter factorization InnXGbarcolinoutG Parameters G linear system syslin list ABCD Inn inner factor syslin list Gbar outer factor syslin list X rowcompressor of G syslin list Description Innerouter factorization and column compression of lxp G ABCD with lp G is assumed to be fat lp without zero on the imaginary axis and with a D matrix which is full row rank G must also be stable for having Gbar stable Dual of rowinout See Also syslin rowinout 924 Name colregul removing poles and zeros at infinity StmpWscolregulSlalfabeta Parameters SlStmp syslin lists alfabeta reals new pole and zero positions Description computes a prefilter Ws such that StmpSlWs is proper and with full rank D matrix Poles at infinity of Sl are moved to alfa Zeros at infinity of Sl are moved to beta Sl is a assumed to be a left invertible linear system syslin list in statespace representation with possibly a polynomial D matrix See Also invsyslin inv rowregul rowshuff Authors F D R N 925 Name contfrm transfer to controllable statespace slcontfrmNUMden Parameters NUM polynomial matrix den polynomial sl syslin list slABCD Description controllable statespace form of the transfer NUMden Examples spoly0sNUM1ssdens25s1 slcontfrmNUMden slssss2tfsl Compare with NUMden See Also tf2ss canon contr 926 Name contmat controllability matrix CccontmatAB Cccontmatsl Parameters ab two real matrices of appropriate dimensions sl linear system syslin list Description contmat returns the controllability matrix of the pair AB resp of the system slABCD CcB AB A2 B An1 B See Also ctrgram contr canon stility 927 Name contr controllability controllable subspace staircase ncontrAB tol nUcontrAB tol nUindVAcBccontrABtol Parameters A B real matrices tol tolerance parameter n dimension of controllable subspace U orthogonal change of basis which puts AB in canonical form V orthogonal matrix change of basis in the control space Ac block Hessenberg matrix AcUAU Bc is UBV ind p integer vector associated with controllability indices dimensions of subspaces B B ABind1ind1ind2 Description nUcontrABtol gives the controllable form of an AB pairdxdt A x B u or xn1 A xn b un The n first columns of U make a basis for the controllable subspace If VU1n then VAV and VB give the controllable part of the AB pair The pair Bc Ac is in staircase controllable form B sIA 1 11 A sIA 21 22 UBVsI UAU 0 0 A sIA pp1 pp 0 0 0 sIA p1p1 contr 928 Reference Slicot library see ab01od in SCImodulescacsdsrcslicot Examples Wssrand235listco3 cont subspace has dim 3 AWABWB nUcontrABn A1UAU specA1n1n1 uncontrollable modes specABrand35 See Also canon contmat unobs stabil stility 929 Name contrss controllable part slccontrsssl tol Parameters sl linear system syslin list tol is a threshold for controllability see contr default value is sqrteps Description returns the controllable part of the linear system sl ABCD in statespace form Examples A1102B10C11slsyslincABC Non minimal slccontrsssl sl1ss2tfslsl2ss2tfslc Compare sl1 and sl2 See Also contmat ctrgram contfrm contr 930 Name copfac right coprime factorization NMXTYTcopfacG polfpolctol Parameters G syslin list continuoustime linear system polf polc respectively the poles of XT and YT and the poles of n and M default values 1 tol real threshold for detecting stable poles default value 100eps NMXTYT linear systems represented by syslin lists Description NMXTYTcopfacGpolfpolctol returns a right coprime factorization of G G NM1 where N and M are stable proper and right coprime ie N M leftinvertible with stability XT and YT satisfy XT YTM N eye Bezout identity G is assumed stabilizable and detectable See Also syslin lcf 931 Name csim simulation time response of linear system y xcsimutslx0 tol Parameters u function list or string control t real vector specifying times with t1 is the initial time x0xt1 sl list syslin y a matrix such that yyti i1n x a matrix such that xxti i1n tol a 2 vector atol rtol defining absolute and relative tolerances for ode solver see ode Description simulation of the controlled linear system sl sl is assumed to be a continuoustime system repre sented by a syslin list u is the control and x0 the initial state y is the output and x the state The control can be 1 a function inputsut 2 a list listutparameter1parametern such that inputsuttparameter1parametern ut is a function 3 the string impuls for impulse response calculation here sl is assumed SISO without direct feed through and x00 4 the string step for step response calculation here sl is assumed SISO without direct feed through and x00 5 a vector giving the values of u correponding to each t value Examples spoly0srandseed0wssrand113wAwA2eye t00055 impulsew step s w clf0xsetwindow0xselect plot2dttcsimstepttf2sssw0t clf1xsetwindow1xselect csim 932 plot2dttcsimimpulsetw0t stepw impulse s1 w clf3xsetwindow3xselect plot2dttcsimsteptw0t clf4xsetwindow4xselect plot2dttcsimimpulsettf2ss1sw0t input defined by a time function deffuinputtuabssint clfplot2dttcsiminputtw0t See Also syslin dsimul flts ltitr rtitr ode impl 933 Name ctrgram controllability gramian GcctrgramAB dom Gcctrgramsl Parameters AB two real matrices of appropriate dimensions dom character string c default value or d sl linear system syslin list Description Controllability gramian of AB or sl a syslin linear system dom character string giving the time domain d for a discrete time system and c for continuous time default case Examples Adiag123Brand32 WcctrgramAB Urand33A1UAUB1UB Wc1ctrgramA1B1 Not invariant See Also equil1 obsgram contr contmat contfrm contrss Authors S Steer INRIA 1988 934 Name dbphi frequency response to phase and magnitude representation dbphi dbphirepf Parameters dbphi vector of gains db and phases degrees repf vector of complex frequency response Description dbk is the magnitude of repfk expressed in dB ie dbk20logabsrepfk log10 and phik is the phase of repfk expressed in degrees See Also repfreq bode 935 Name dcf double coprime factorization NMXYNTMTXTYTdcfGpolfpolctol Parameters G syslin list continuoustime linear system polf polc respectively the poles of XT and YT and the poles of N and M default values 1 tol real threshold for detecting stable poles default value 100eps NMXTYTNTMTXY linear systems represented by syslin lists Description returns eight stable systems NMXYNTMTXTYT for the doubly coprime factorization G must be stabilizable and detectable See Also copfac 936 Name ddp disturbance decoupling ClosedFGddpSyszeroedB1D1 ClosedFGddpSyszeroedB1D1flagalfabeta Parameters Sys syslin list containing the matrices AB2CD2 zeroed integer vector indices of outputs of Sys which are zeroed B1 real matrix D1 real matrix B1 and D1 have the same number of columns flag string ge or st default or pp alpha real or complex vector loc of closed loop poles beta real or complex vector loc of closed loop poles Description Exact disturbance decoupling output nulling algorithm Given a linear system and a subset of out puts z which are to be zeroed characterize the inputs w of Sys such that the transfer function from w to z is zero Sys is a linear system AB2CD2 with one input and two outputs ie Sys uzy part the following system defined from Sys and B1D1 xdot A x B1 w B2 u z C1 x D11 w D12 u y C2 x D21 w D22 u outputs of Sys are partitioned into zy where z is to be zeroed ie the matrices C and D2 are CC1C2 D2D12D22 C1Czeroed D12D2zeroed The matrix D1 is partitioned similarly as D1D11D21 with D11D1zeroed The control is uFxGw and one looks for matriced FG such that the closed loop system wz given by xdot AB2F x B1 B2G w z C1D12F x D11D12G w has zero transfer transfer function ddp 937 flaggeno stability constraints flagst look for stable closed loop system AB2F sta ble flagpp eigenvalues of AB2F are assigned to alfa and beta Closed is a realization of the wy closed loop system xdot AB2F x B1 B2G w y C2D22F x D21D22G w Stability resp pole placement requires stabilizability resp controllability of AB2 Examples randseed0nx6nz3nu2ny1 Adiag16A227A559B2120304050000 C1zerosnznzeyenznzD12010203 Sys12syslincAB2C1D12 CC1randnynxD2D12randnysizeD122 SyssyslincAB2CD2 AB2C1D12abcdSys12 The matrices of Sys12 myalpha1mybeta2flagge XdimsFUkZabinvSys12myalphamybetaflag cleanXAB2FX cleanXB2U cleanC1D12FX cleanD12U Calculating an adhoc B1D1 G1randsizeB223 B1B2G1 D11D12G1 D1D11randnysizeB12 ClosedFGddpSys1nzB1D1stmyalphamybeta closedsyslincAB2FB1B2GC1D12FD11D12G ss2tfclosed See Also abinv uiobserver Authors FD 938 Name des2ss descriptor to statespace Sldes2ssABCDE tol Sldes2ssDes Parameters ABCDE real matrices of appropriate dimensions Des list Sl syslin list tol real parameter threshold default value 100eps Description Descriptor to statespace transform Sldes2ssABCDE returns a linear system Sl equivalent to the descriptor system EABCD For index one EA pencil explicit formula is used and for higher index pencils rowshuff is used Sldes2ssDes with DeslistdesABCDE returns a linear system Sl in state space form with possibly a polynomial D matrix A generalized Leverrier algorithm is used Examples spoly0sG1s1s12s3 S1tf2desGS2tf2desGwithD W1des2ssS1W2des2ssS2 cleanss2tfW1 cleanss2tfW2 See Also des2tf glever rowshuff 939 Name des2tf descriptor to transfer function conversion Sdes2tfsl BfsBischisdes2tfsl Parameters sl list linear system in descriptor form Bfs Bis two polynomial matrices chis polynomial S rational matrix Description Given the linear system in descriptor form ie SllistdesABCDE des2tf converts sl into its transfer function representation SCsEA1BD Called with 3 outputs arguments des2tf returns Bfs and Bis two polynomial matrices and chis polynomial such that SBfschis Bis chis is the determinant of sEA up to a xcative constant Examples spoly0s G1s1s1s23s3 Descriptf2desGTf1des2tfDescrip Descrip2tf2desGwithDTf2des2tfDescrip2 ABCDEDescrip226Tf3CinvsEABD See Also glever pol2des tf2des ss2tf des2ss rowshuff Authors F D 940 Name dhinf Hinfinity design of discretetime systems AKBKCKDKRCOND dishinABCDnconnmeasgamma Parameters A the nbyn system state matrix A B the nbym system input matrix B C the pbyn system output matrix C D the pbym system matrix D ncon the number of control inputs m ncon 0 pnmeas ncon nmeas the number of measurements p nmeas 0 mncon nmeas gamma the parameter gamma used in Hinfinity design It is assumed that gamma is sufficiently large so that the controller is admissible gamma 0 AK the nbyn controller state matrix AK BK the nbynmeas controller input matrix BK CK the nconbyn controller output matrix CK DK the nconbynmeas controller matrix DK RCOND a vector containing estimates of the reciprocal condition numbers of the matrices which are to be inverted and estimates of the reciprocal condition numbers of the Riccati equations which have to be solved during the computation of the controller See the description of the algorithm in 1 RCOND 1 contains the reciprocal condition number of the matrix R3 RCOND 2 contains the reciprocal condition number of the matrix R1 R2invR3R2 RCOND 3 contains the reciprocal condition number of the matrix V21 RCOND 4 contains the reciprocal condition number of the matrix St3 RCOND 5 contains the reciprocal condition number of the matrix V12 dhinf 941 RCOND 6 contains the reciprocal condition number of the matrix Im2 DKHATD22 RCOND 7 contains the reciprocal condition number of the XRiccati equation RCOND 8 contains the reciprocal condition number of the ZRiccati equation Description AKBKCKDKRCOND dhinfABCDnconnmeas gamma To compute the matrices of an Hinfinity suboptimal nstate controller AK BK K CK DK for the discretetime system A B1 B2 A B P C1 D11 D12 C D C2 D21 D22 and for a given value of gamma where B2 has column size of the number of control inputs ncon and C2 has row size of the number of measurements nmeas being provided to the controller References 1 PHr Petkov DW Gu and MM Konstantinov Fortran 77 routines for Hinf and H2 design of linear discretetime control systems Report998 Department of Engineering Leicester University April 1999 Examples example from Niconet report SLWN199912 Hinf A07 0 03 0 05 01 06 02 04 03 0 0 05 07 01 0 0 08 07 0 0 05 1 0 0 03 06 09 01 04 05 08 0 0 02 09 B1 2 2 1 0 1 0 1 2 1 3 4 0 2 2 1 2 1 0 1 0 1 2 0 3 1 0 3 1 2 C 1 1 2 2 0 3 3 0 1 1 1 0 0 2 0 4 0 2 dhinf 942 1 3 0 0 3 1 0 1 2 1 0 2 D1 1 2 0 0 0 1 0 1 0 2 1 3 0 1 0 1 0 1 1 0 0 1 2 1 ncon2 nmeas2 gam11130 AKBKCKDK dhinfABCDnconnmeasgam See Also hinf hinf 943 Name dhnorm discrete Hinfinity norm hinfnormdhnormsltolnormax Parameters sl the state space system syslin list discretetime tol tolerance in bisection step default value 001 normax upper bound for the norm default value is 1000 hinfnorm the discrete infinity norm of Sl Description produces the discretetime infinity norm of a statespace system the maximum over all frequencies on the unit circle of the maximum singular value See Also hnorm linfn 944 Name dscr discretization of linear system sld rdscrsldt m Parameters sl syslin list containing ABCD dt real number sampling period m covariance of the input noise continuous timedefault value0 r covariance of the output noise discrete time given if m is given as input sld sampled discretetime linear system syslin list Description Discretization of linear system sl is a continuoustime system dxdtAxBu noise sld is the discretetime system obtained by sampling sl with the sampling period dt Examples spoly0s Syssyslinc11s12ss221s ss2tfdscrtf2ssSys01 See Also syslin flts dsimul 945 Name dsimul state space discrete time simulation ydsimulslu Parameters sl syslin list describing a discrete time linear system u real matrix of appropriate dimension y output of sl Description Utility function If ABCDabcdsl and x0slX0 dsimul returns yCltitrABux0Du ie the time response of sl to the input u sl is assumed to be in state space form syslin list Examples zpoly0z h12zz202z1 sltf2ssh uzeros120u11 x1dsimulslu Impulse response uones120 x2dsimulslu Step response See Also syslin flts ltitr 946 Name dtility detectability test k n U Sld dtilitySl tol Parameters Sl linear system syslin list n dimension of unobservable subspace k dimension of unstable unobservable subspace kn U orthogonal matrix Sld linear system syslin list tol threshold for controllability test Description Detectability test for sl a linear system in statespace representation U is a basis whose k first columns span the unstable unobservable subspace of Sl intersection of unobservable subspace of AC and unstable subspace of A Detectability means k0 Sld UAUUBCUD displays the detectable part of SlABCD ie UAU 0 00 CU 00 with A33C3 observable dimension nxn A22 stable dimension nk and A11 unstable di mension k Examples A211021003 C001 Xrand33AinvXAXCCX WsyslincAC knUW1dtilityW W1A W1C See Also contr stility unobs stabil 947 Name dtsi stable antistable decomposition GaGsGidtsiGtol Parameters G linear system syslin list Ga linear system syslin list antistable and strictly proper Gs linear system syslin list stable and strictly proper Gi real matrix or polynomial matrix for improper systems tol optional parameter for detecting stables poles Default value 100eps Description returns the stableantistable decomposition of G G Ga Gs Gi Gi Goo G can be given in statespace form or in transfer form See Also syslin pbig psmall pfss 948 Name equil balancing of pair of symmetric matrices TequilPQ Parameters P Q two positive definite symmetric matrices T nonsingular matrix Description equil returns t such that TPT and invTQinvT are both equal to a same diagonal and positive matrix Examples Prand44PPP Qrand44QQQ TequilPQ cleanTPT cleaninvTQinvT See Also equil1 balanc ctrgram 949 Name equil1 balancing nonnegative pair of matrices T sizequil1PQ tol Parameters P Q two nonnegative symmetric matrices T nonsingular matrix siz vector of three integers tol threshold Description equil1 computes t such that P1TPT and Q1invTQinvT are as follows P1 diagS1S200 and Q1 diagS10S30 with S1S2S3 positive and diag onal matrices with respective dimensions sizn1n2n3 tol is a threshold for rank determination in SVD Examples S1rand22S1S1S1 S2rand22S2S2S2 S3rand22S3S3S3 PsysdiagS1S2zeros44 QsysdiagS1zeros22S3zeros22 Xrand88 PXPXQinvXQinvX Tsizequil1PQ P1cleanTPT Q1cleaninvTQinvT See Also balreal minreal equil hankelsv Authors S Steer 1987 950 Name feedback feedback operation SlSl1Sl2 Parameters Sl1Sl2 linear systems syslin list in statespace or transfer form or ordinary gain matrices Sl linear system syslin list in statespace or transfer form Description The feedback operation is denoted by slashdot This command returns SlSl1I Sl2Sl11 ie the negative feedback of Sl1 and Sl2 Sl is the transfer v y for y Sl1 u u v Sl2 y The result is the same as SlLFT0IISl2Sl1 Caution do not use with decimal point eg 11 is ambiguous Examples S1ssrand223S2ssrand222 WS1S2 ss2tfS1S2 Same operation by LFT ss2tflftzeros22eye22eye22S2S1 Other approach with constant feedback BigSsysdiagS1S2 Fzeros22eye22eye22zeros22 BigclosedBigSF W1Bigclosed1212 W1W in statespace ss2tfW1 Inverting ss2tfS1inveyeS2S1 See Also lft sysdiag augment obscont 951 Name findABCD discretetime system subspace identification SYSK findABCDSNLRMETHNSMPLTOLPRINTW SYS findABCDSNLRMETH SYSKQRySRCND findABCDSNLRMETHNSMPLTOLPRINTW SYSRCND findABCDSNLRMETH Parameters S integer the number of block rows in the blockHankel matrices N integer the system order L integer the number of output R matrix relevant part of the R factor of the concatenated blockHankel matrices computed by a call to findr METH integer an option for the method to use 1 MOESP method with past inputs and outputs 2 N4SID method 3 combined method A and C via MOESP B and D via N4SID Default METH 3 NSMPL integer the total number of samples used for calculating the covariance matrices and the Kalman predictor gain This parameter is not needed if the covariance matrices andor the Kalman predic tor gain matrix are not desired If NSMPL 0 then K Q Ry and S are not computed Default NSMPL 0 TOL the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine precision PRINTW integer switch for printing the warning messages PRINTW 1 print warning messages PRINTW 0 do not print warning messages Default PRINTW 0 findABCD 952 SYS computes a statespace realization SYS ABCD an syslin object K the Kalman predictor gain K if NSMPL 0 Q state covariance Ry output covariance S stateoutput crosscovariance RCND vector reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions Description Finds the system matrices and the Kalman gain of a discretetime system given the system order and the relevant part of the R factor of the concatenated blockHankel matrices using subspace identifi cation techniques MOESP andor N4SID SYSK findABCDSNLRMETHNSMPLTOLPRINTW computes a state space realiza tion SYS ABCD an ss object and the Kalman predictor gain K if NSMPL 0 The model structure is xk1 Axk Buk Kek k 1 yk Cxk Duk ek where xk and yk are vectors of length N and L respectively SYSKQRySRCND findABCDSNLRMETHNSMPLTOLPRINTW also returns the state output and stateoutput crosscovariance matrices Q Ry and S used for computing the Kalman gain as well as the vector RCND of length lr containing the reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions where lr 4 if Kalman gain matrix K is not required and lr 12 if Kalman gain matrix K is required Matrix R computed by findR should be determined with suitable arguments METH and JOBD METH 1 and JOBD 1 must be used in findR for METH 1 in findABCD METH 1 must be used in findR for METH 3 in findABCD Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 findABCD 953 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15 RN1SVAL findRSYU N3 SYS1 findABCDSN1R SYS1dt01 SYS1X0 inistateSYS1YU Y1fltsUSYS1 clfplot2d1nsmpYY1 See Also findAC findBD findBDK findR sorder sident 954 Name findAC discretetime system subspace identification AC findACSNLRMETHTOLPRINTW ACRCND findACSNLRMETHTOLPRINTW Parameters S integer the number of block rows in the blockHankel matrices N integer L integer R matrix relevant part of the R factor of the concatenated blockHankel matrices computed by a call to findr METH integer an option for the method to use 1 MOESP method with past inputs and outputs 2 N4SID method Default METH 3 TOL the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine precision PRINTW integer switch for printing the warning messages PRINTW 1 print warning messages 0 do not print warning messages Default PRINTW 0 A matrix state system matrix C matrix output system matrix RCND vector of length 4 condition numbers of the matrices involved in rank decision findAC 955 Description finds the system matrices A and C of a discretetime system given the system order and the relevant part of the R factor of the concatenated blockHankel matrices using subspace identification tech niques MOESP or N4SID AC findACSNLRMETHTOLPRINTW computes the system matrices A and C The mod el structure is xk1 Axk Buk Kek k 1 yk Cxk Duk ek where xk and yk are vectors of length N and L respectively ACRCND findACSNLRMETHTOLPRINTW also returns the vector RCND of length 4 containing the condition numbers of the matrices involved in rank decisions Matrix R computed by findR should be determined with suitable arguments METH and JOBD Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15L1 RNSVAL findRSYU N3 METH3TOL1 AC findACSNLRMETHTOL See Also findABCD findBD findBDK findR sorder sident 956 Name findBD initial state and system matrices B and D of a discretetime system x0 B D V rcnd findBDjobx0comuse jobA BC DY Utolprintwldwork Parameters jobx0 integer option to specify whether or not the initial state should be computed 1 compute the initial state x0 2 do not compute the initial state possibly because x0 is known to be zero comuse integer option to specify whether the system matrices B and D should be computed or used 1 compute the matrices B and D as specified by job 2 use the matrices B and D as specified by job 3 do not computeuse the matrices B and D job integer option to determine which of the system matrices B and D should be computed or used 1 computeuse the matrix B only D is known to be zero 2 computeuse the matrices B and D job must not be specified if jobx0 2 and comuse 2 or if comuse 3 A state matrix of the given system B optionnal input matrix of the given system C output matrix of the given system D optionnal direct feedthrough of the given system Y the tbyl outputdata sequence matrix Column j of Y contains the t values of the jth output component for consecutive time increments U the tbym inputdata sequence matrix input when jobx0 1 and comuse 2 or comuse 1 Column j of U contains the t values of the jth input component for consecutive time increments findBD 957 tol optionnal tolerance used for estimating the rank of matrices If tol 0 then the given value of tol is used as a lower bound for the reciprocal condition number an mbyn matrix whose estimated condition number is less than 1tol is considered to be of full rank Default mnepsilonmachine where epsilonmachine is the relative machine precision printw optionnal switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default printw 0 ldwork optional the workspace size Default computed by the formula LDWORK MAX minimum workspace size needed 2CSIZE3 CSIZE m l t 2n n m l lm where CSIZE is the cache size in double precision words x0 initial state vector Br system input matrix Dr system direct feedthrough matrix V the nbyn orthogonal matrix which reduces A to a real Schur form output when jobx0 1 or comuse 1 rcnd optional the reciprocal condition numbers of the matrices involved in rank decisions Description findBD function for estimating the initial state and the system matrices B and D of a discretetime system using SLICOT routine IB01CD x0BrVrcnd findBD111ACYU x0BrDrVrcnd findBD112ACYU BrVrcnd findBD211ACYU BDrVrcnd findBD212ACYU x0Vrcnd findBD121ABCYU x0Vrcnd findBD122ABCDYU x0rcnd findBD22 Set x0 0 rcnd 1 x0Vrcnd findBD13ACY Note the example lines above may contain at the end the parameters tol printw ldwork FINDBD estimates the initial state andor the system matrices Br and Dr of a discretetime system given the system matrices A C and possibly B D and the input and output trajectories of the system The model structure is findBD 958 xk1 Axk Buk k 1 yk Cxk Duk where xk is the ndimensional state vector at time k uk is the mdimensional input vector yk is the ldimensional output vector and A B C and D are real matrices of appropriate dimensions Comments 1 The nbym system input matrix B is an input parameter when jobx0 1 and comuse 2 and it is an output parameter when comuse 1 2 The lbym system matrix D is an input parameter when jobx0 1 comuse 2 and job 2 and it is an output parameter when comuse 1 and job 2 3 The nvector of estimated initial state x0 is an output parameter when jobx0 1 but also when jobx0 2 and comuse 2 in which case it is set to 0 4 If ldwork is specified but it is less than the minimum workspace size needed that minimum value is used instead Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15L1 RNSVAL findRSYU N3 METH3TOL1 AC findACSNLRMETHTOL X0BD findBD112ACYU SYS1syslin1ABCDX0 Y1fltsUSYS1 clfplot2d1nsmpYY1 findBD 959 See Also inistate findx0BD findABCD findAC findBD Authors V Sima Katholieke Univ Leuven Belgium May 2000 Revisions V Sima July 2000 960 Name findBDK Kalman gain and B D system matrices of a discretetime system BDK findBDKSNLRACMETHJOBNSMPLTOLPRINTW BDRCND findBDKSNLRACMETHJOB BDKQRySRCND findBDKSNLRACMETHJOBNSMPLTOLPRINTW Parameters S integer the number of block rows in the blockHankel matrices N integer L integer R matrix relevant part of the R factor of the concatenated blockHankel matrices computed by a call to findR A square matrix C matrix METH integer an option for the method to use 1 MOESP method with past inputs and outputs 2 N4SID method Default METH 2 JOB an option specifying which system matrices should be computed 1 compute the matrix B 2 compute the matrices B and D Default JOB 2 NSMPL integer the total number of samples used for calculating the covariance matrices and the Kalman predictor gain This parameter is not needed if the covariance matrices andor the Kalman predic tor gain matrix are not desired If NSMPL 0 then K Q Ry and S are not computed Default NSMPL 0 TOL the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine precision findBDK 961 PRINTW integer switch for printing the warning messages PRINTW 1 print warning messages PRINTW 0 do not print warning messages Default PRINTW 0 SYS computes a statespace realization SYS ABCD an syslin object K the Kalman predictor gain K if NSMPL 0 Q state covariance Ry output covariance S stateoutput crosscovariance RCND he vector of length 12 containing the reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions Description finds the system matrices B and D and the Kalman gain of a discretetime system given the system order the matrices A and C and the relevant part of the R factor of the concatenated blockHankel matrices using subspace identification techniques MOESP or N4SID BDK findBDKSNLRACMETHJOBNSMPLTOLPRINTW computes the system ma trices B if JOB 1 B and D if JOB 2 and the Kalman predictor gain K if NSMPL 0 The model structure is xk1 Axk Buk Kek k 1 yk Cxk Duk ek where xk and yk are vectors of length N and L respectively BDRCND findBDKSNLRACMETHJOB also returns the vector RCND of length 4 con taining the reciprocal condition numbers of the matrices involved in rank decisions BDKQRySRCND findBDKSNLRACMETHJOBNSMPLTOLPRINTW also re turns the state output and stateoutput crosscovariance matrices Q Ry and S used for comput ing the Kalman gain as well as the vector RCND of length 12 containing the reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions Matrix R computed by findR should be determined with suitable arguments METH and JOBD METH 1 and JOBD 1 must be used in findR for METH 1 in findBDK Using METH 1 in FINDR and METH 2 in findBDK is allowed The number of output arguments may vary but should correspond to the input arguments eg findBDK 962 B findBDKSNLRACMETH1 or BD findBDKSNLRACMETH2 or BDRCND findBDKSNLRACMETH2 Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15L1 RNSVAL findRSYU N3 METH3TOL1 AC findACSNLRMETHTOL BDK findBDKSNLRAC SYS1syslin1ABCD SYS1X0 inistateSYS1YU Y1fltsUSYS1 clfplot2d1nsmpYY1 See Also findABCD findAC findBD findR sorder sident 963 Name findR Preprocessor for estimating the matrices of a linear timeinvariant dynamical system RN SVALRCND findRSYUMETHALGJOBDTOLPRINTW RN findRSY Parameters S the number of block rows in the blockHankel matrices Y U METH an option for the method to use 1 MOESP method with past inputs and outputs 2 N4SI15 0 1 1 1000D method Default METH 1 ALG an option for the algorithm to compute the triangular factor of the concatenated blockHankel matrices built from the inputoutput data 1 Cholesky algorithm on the correlation matrix 2 fast QR algorithm 3 standard QR algorithm Default ALG 1 JOBD an option to specify if the matrices B and D should later be computed using the MOESP approach 1 the matrices B and D should later be computed using the MOESP approach 2 the matrices B and D should not be computed using the MOESP approach Default JOBD 2 This parameter is not relevant for METH 2 TOL a vector of length 2 containing tolerances TOL 1 is the tolerance for estimating the rank of matrices If TOL1 0 the given value of TOL1 is used as a lower bound for the reciprocal condition number Default TOL1 prodsizematrixepsilonmachine where epsilonmachine is the rela tive machine precision findR 964 TOL 2 is the tolerance for estimating the system order If TOL2 0 the estimate is indicated by the index of the last singular value greater than or equal to TOL2 Singular values less than TOL2 are considered as zero When TOL2 0 then Sepsilonmachinesval1 is used instead TOL2 where sval1 is the maximal singular value When TOL2 0 the estimate is indicated by the index of the singular value that has the largest logarithmic gap to its successor Default TOL2 1 PRINTW a switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default PRINTW 0 R N the order of the discretetime realization SVAL singular values SVAL used for estimating the order RCND vector of length 2 containing the reciprocal condition numbers of the matrices involved in rank decisions or least squares solutions Description findR Preprocesses the inputoutput data for estimating the matrices of a linear timeinvariant dynam ical system using Cholesky or fast QR factorization and subspace identification techniques MOE SP or N4SID and estimates the system order RN findRSYUMETHALGJOBDTOLPRINTW returns the processed upper triangular fac tor R of the concatenated blockHankel matrices built from the inputoutput data and the order N of a discretetime realization The model structure is xk1 Axk Buk wk k 1 yk Cxk Duk ek The vectors yk and uk are transposes of the kth rows of Y and U respectively RNSVALRCND findRSYUMETHALGJOBDTOLPRINTW also returns the singular val ues SVAL used for estimating the order as well as if meth 2 the vector RCND of length 2 con taining the reciprocal condition numbers of the matrices involved in rank decisions or least squares solutions RN findRSY assumes U and default values for the remaining input arguments Examples generate data from a given linear system findR 965 A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC Uones11000rand11000normal YfltsUSYS05rand11000normal Compute R RNSVAL findR15YU SVAL N See Also findABCD findAC findBD findBDK sorder sident 966 Name findx0BD Estimates state and B and D matrices of a discretetime linear system X0BD findx0BDACYUWITHX0WITHDTOLPRINTW x0BDVrcnd findx0BDACYU Parameters A state matrix of the system C C matrix of the system Y system output U system input WITHX0 a switch for estimating the initial state x0 1 estimate x0 0 do not estimate x0 Default WITHX0 1 WITHD a switch for estimating the matrix D 1 estimate the matrix D 0 do not estimate the matrix D Default WITHD 1 TOL the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine precision PRINTW a switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default PRINTW 0 X0 intial state of the estimated linear system findx0BD 967 B B matrix of the estimated linear system D D matrix of the estimated linear system V orthogonal matrix which reduces the system state matrix A to a real Schur form rcnd estimates of the reciprocal condition numbers of the matrices involved in rank decisions Description findx0BD Estimates the initial state andor the matrices B and D of a discretetime linear system given the estimated system matrices A C and a set of inputoutput data X0BD findx0BDACYUWITHX0WITHDTOLPRINTW estimates the initial state X0 and the matrices B and D of a discretetime system using the system matrices A C output data Y and the input data U The model structure is xk1 Axk Buk k 1 yk Cxk Duk The vectors yk and uk are transposes of the kth rows of Y and U respectively x0BDVrcnd findx0BDACYU also returns the orthogonal matrix V which reduces the system state matrix A to a real Schur form as well as some estimates of the reciprocal condition numbers of the matrices involved in rank decisions B findx0BDACYU00 returns B only and BD findx0BDACYU0 returns B and D only Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal Compute R S15L1 RNSVAL findRSYU N3 METH3TOL1 AC findACSNLRMETHTOL findx0BD 968 X0BDVrcnd findx0BDACYU SYS1syslin1ABCDX0 Y1fltsUSYS1 clfplot2d1nsmpYY1 See Also findBD inistate 969 Name flts time response discrete time sampled system y xfltsusl x0 yfltsusl past Parameters u matrix input vector sl list linear system syslin x0 vector initial state default value0 past matrix of the past default value0 xy matrices state and output Description Statespace form sl is a discrete linear system given by its state space representation see syslin slsyslindABCD xt1 A xt B ut yt C xt D ut or more generally if D is a polynomial matrix p degreeDz Dz D0 z D1 z2 D2 zp Dp yt C xt D0 ut D1 ut1 Dp utp Transfer form yfltsuslpast Here sl is a linear system in transfer matrix representation ie slsyslindtransfermatrix see syslin past u u nd 1 y y nd 1 is the matrix of past values of u and y nd is the maximum of degrees of lcms of each row of the denominator matrix of sl flts 970 uu0 u1 un input yy0 y1 yn output p is the difference between maximum degree of numerator and maximum degree of denominator Examples slsyslind111u110 yfltsusl plot2dy y1x1fltsu15sly2fltsu610slx1 yy1y2 With polynomial D zpoly0z D1zz2 p degreeD slsyslind111D yfltsusly1x1fltsu15sl y2fltsu5p110slx1 update yy1y2 Delay transfer form fltsu1z Usual responses zpoly0z hsyslin0112zz203z1 imprepfltseye120tf2ssh Impulse response clf plotimprepb uones120 stprepfltsones120tf2ssh Step response plotstprepg Other examples A1 2 30 2 40 0 1B1 00 00 1Ceye33SyssyslindABC Hss2tfSys u11110 yhfltsuH ysfltsuSys normyhys1 hot restart ys1xfltsu14Sysys2fltsu510Sysx normys1ys2ys1 yh1fltsu14Hyh2fltsu510Hu24yh24 normyh1yh2yh1 with Dltgt0 D3 84 0522 09 SyssyslindABCD Hss2tfSys u11110 rhfltsuH rsfltsuSys normrhrs1 hot restart ys1xfltsu14Sysys2fltsu510Sysx normys1ys2rs1 With H yh1fltsu14Hyh2fltsu510Hu24 yh124 flts 971 normyh1yh2rh See Also ltitr dsimul rtitr 972 Name fourplan augmented plant to four plants P11P12P21P22fourplanPr Parameters P syslin list linear system r 1x2 row vector dimension of P22 P11P12P21P22 syslin lists Description Utility function P being partitioned as follows P P11 P12 P21 P22 with sizeP22r this function returns the four linear systems P11P12P21P22 See Also lqg lqg2stan lqr lqe lft 973 Name frep2tf transfer function realization from frequency response h errfrep2tffrqrepfdg domtolsweight Parameters frq vector of frequencies in Hz repf vector of frequency response dg degree of linear system dom time domain c or d or dt tols a vector of size 3 giving the relative and absolute tolerance and the maximum number of iterations default values are rtol1e2 atol1e4 N10 weight vector of weights on frequencies h SISO transfer function err error for example if domc sumabsh2ipifrq rep2sizefrq Description Frequency response to transfer function conversion The order of h is a priori given in dg which must be provided The following linear system is solved in the least square sense weightkn phik dphikrepk0 k1n where phik 2ipifrq when domc and phikexp2ipidomfrq if not If the weight vector is not given a default penalization is used when domc A stable and minimum phase system can be obtained by using function factors Examples spoly0s hsyslincs1s35s20 frq00053repfrepfreqhfrq cleanfrep2tffrqrepf3 Sysssrand1110 frqlogspace32200 frqreprepfreqSysfrq Frequency response of Sys frep2tf 974 Sys2errfrep2tffrqrep10Sys2cleanSys2Sys2 obtained from freq resp of Sys frqrep2repfreqSys2frq Frequency response of Sys2 clfbodefrqreprep2 Responses of Sys and Sys2 gsortspecSysAgsortrootsSys2den poles dom11000 Sampling time zpoly0z hsyslindomz205z301z205z008 frq000105domrepfrepfreqhfrq Sys2errfrep2tffrqrepf3dom frqrep2repfreqSys2frq Frequency response of Sys2 clfplot2d1onnfrqabsrepfrep2 See Also imrep2ss arl2 timeid armax frfit 975 Name freq frequency response xfreqABC Df xfreqNUMDENf Parameters A B C D real matrices of respective dimensions nxn nxp mxn mxp NUMDEN polynomial matrices of dimension mxp x real or complex matrix Description xfreqABC Df returns a real or complex mxpt matrix such that xkpk1p CinvfkeyeAB D Thus for f taking values along the imaginary axis or on the unit circle x is the continuous or discrete time frequency response of ABCD xfreqNUMDENf returns a real or complex matrix x such that columns kp11 to kp of x contain the matrix NUMfkDENfk Examples spoly0s syss1s35s4 repfreqsysnumsysden00911231020 hornersys0hornersys20 Systf2sssys ABCDabcdSys freqABC00911231020 See Also repfreq horner 976 Name freson peak frequencies frfresonh Parameters h syslin list fr vector of peak frequencies in Hz Description returns the vector of peak frequencies in Hz for the SISO plant h Examples hsyslinc1s32ss25001ss2 frfresonh bodeh g20logabsrepfreqhfrlog10 See Also frep2tf zgrid hnorm 977 Name fspecg stable factorization gmfspecgg Parameters ggm syslin lists linear systems in statespace representation Description returns gm with gm and gm1 stable such that gtildgg gtildgmgm g and gm are continuoustime linear systems in statespace form Imaginaryaxis poles are forbidden 978 Name fstabst Youlas parametrization JfstabstPr Parameters P syslin list linear system r 1x2 row vector dimension of P22 J syslin list linear system in statespace representation Description Parameterization of all stabilizing feedbacks P is partitioned as follows P P11 P12 P21 P22 in statespace or transfer form automatic conversion in statespace is done for the computations r size of P22 subsystem 22 block of P J J11 J12 J21 J22 K is a stabilizing controller for P ie P22 iff KlftJrQ with Q stable The central part of J J11 is the lqg regulator for P This J is such that defining T as the 2port lft of P and J TrtlftPrJr one has that T12 is inner and T21 is coinner Examples ny2nu3nx4 P22ssrandnynunx bigQrandnxnunxnubigQbigQbigQ bigRrandnxnynxnybigRbigRbigR Prlqg2stanP22bigQbigR JfstabstPr Qssrandnuny1QA1 Stable Q KlftJrQ AhclPrK specA fstabst 979 See Also obscont lft lqg lqg2stan 980 Name gmargin gain margin and associated crossover frequency gmgmarginh gmfrgmarginh Parameters h a SISO linear system see syslin gm a number the gain margin in dB if any of Inf fr a number the associated frequency in hertz or an empty matrix if the gain margin does not exist Description Given a SISO linear system in continuous or discrete time gmargin returns gm the gain margin in dB of h and fr the achieved corresponding frequency in hz The gain margin if it exists is the minimal value of the system gain at points where the nyquist plot crosses the negative real axis In other words the gain margin is 20log101g where g is the open loop gain of h when the frequency response phase of h equals 180 The algorithm uses polynomial root finder to solve the equations hshs for the continuous time case hzh1z for the discrete time case Examples hsyslinc1s32ss2 continuous time case gfrgmarginh gfrgmarginh10 nyquisth10 h syslin01004798z00464z2181z09048discrete time case g frgmarginh showmarginsh See Also pmargin showmargins repfreq black bode chart nyquist Authors Serge Steer INRIA 981 Name gamitg Hinfinity gamma iterations goptgamitgGrprec options Parameters G syslin list plant realization r 1x2 row vector dimension of G22 prec desired relative accuracy on the norm option string t gopt real scalar optimal Hinfinity gain Description goptgamitgGrprec options returns the Hinfinity optimal gain gopt G contains the statespace matrices ABCD of the plant with the usual partitions B B1 B2 C C1 D D11 D12 C2 D21 D22 These partitions are implicitly given in r r1 and r2 are the dimensions of D22 rows x columns With optiont gamitg traces each bisection step ie displays the lower and upper bounds and the current test point See Also ccontrg hinf Authors P Gahinet 982 Name gcare control Riccati equation XFgcareSl Parameters Sl linear system syslin list X symmetric matrix F real matrix Description Generalized Control Algebraic Riccati Equation GCARE X solution F gain The GCARE for SlABCD is ABSiDCXXABSiDCXBSiBXCRiC0 where SeyeDD SiinvS ReyeDD RiinvR and FSiDC BX is such that ABF is stable See Also gfare 983 Name gfare filter Riccati equation ZHgfareSl Parameters Sl linear system syslin list Z symmetric matrix H real matrix Description Generalized Filter Algebraic Riccati Equation GFARE Z solution H gain The GFARE for SlABCD is ABDRiCZZABDRiCZCRiCZBSiB0 where SeyeDD SiinvS ReyeDD RiinvR and H BDZCRi is such that AHC is stable See Also gcare 984 Name gfrancis Francis equations for tracking LMTgfrancisPlantModel Parameters Plant syslin list Model syslin list LMT real matrices Description Given the the linear plant x Fx Gu y Hx Ju and the linear model xm Axm Bum ym Cxm Dum the goal is for the plant to track the model ie e y ym 0 while keeping stable the state xt of the plant u is given by feedforward and feedback u Lxm Mum KxTxm K LKT xxm Mum The matrices TLM satisfy generalized Francis equations FT GL TA HT JL C GM TB JM D The matrix K must be chosen as stabilizing the pair FG See example of use in directory de mostracking Examples Plantssrand135 FGHJabcdPlant nw4nuu2Arandnwnw gfrancis 985 stmaxirealspecAAAsteyeA BrandnwnuuC2rand1nwD0randCB ModelsyslincABCD LMTgfrancisPlantModel normFTGLTA1 normHTJLC1 normGMTB1 normJMD1 See Also lqg ppol 986 Name gtild tilde operation GtgtildG GtgtildGflag Parameters G either a polynomial or a linear system syslin list or a rational matrix Gt same as G flag character string either c or d optional parameter Description If G is a polynomial matrix or a polynomial GtgtildGc returns the polynomial matrix GtsGs If G is a polynomial matrix or a polynomial GtgtildGd returns the polynomial matrix GtG1zzn where n is the maximum degree of G For continuoustime systems represented in statespace by a syslin list Gt gtildGc returns a statespace representation of Gs ie the ABCD matrices of Gt are AC B D If G is improper D Ds the D matrix of Gt is Ds For discretetime systems represented in statespace by a syslin list Gt gtildGd re turns a statespace representation of G1z ie the possibly improper statespace representation of zCinvzABC D1z For rational matrices Gt gtildGc returns the rational matrix GtsGs and Gt gtildGd returns the rational matrix Gtz G1z The parameter flag is necessary when gtild is called with a polynomial argument Examples Continuous time spoly0sGss32s3s25 GtgtildGc GthornerGs continuoustime interpretation GtgtildGd GthornerG1ss3 discretetime interpretation Gssrand223GtgtildG Statespace G is cont time by default cleanhornerss2tfGsss2tfGt Check Discretetime zpoly0z Gssssrand223Gssdtd discretetime Gss51201 With a constant D matrix Gss2tfGssGt1hornerG1z GtgtildGss Gt2cleanss2tfGt cleanGt1Gt2 Check gtild 987 Improper systems zpoly0z Gssssrand223Gss7d discretetime Gss5zz21z3 Dz is polynomial Gss2tfGssGt1hornerG1z Calculation in transfer form GtgtildGss in statespace Gt2cleanss2tfGtcleanGt1Gt2 Check See Also syslin horner factors 988 Name h2norm H2 norm nh2normSl tol Parameters Sl linear system syslin list n real scalar Description produces the H2 norm of a linear continuous time system Sl For Sl in statespace form h2norm uses the observability gramian and for Sl in transfer form h2norm uses a residue method 989 Name hcl closed loop matrix AclhclPrK AclhclP22K Parameters P P22 linear system syslin list augmented plant or nominal plant respectively r 1x2 row vector dimensions of 22 part of P rrowscolssizeP22 K linear system syslin list controller Acl real square matrix Description Given the standard plant P with rsizeP22 and the controller K this function returns the closed loop matrix Acl The poles of Acl must be stable for the internal stability of the closed loop system Acl is the Amatrix of the linear system I P22K I1 ie the Amatrix of lftPrK See Also lft Authors F D 990 Name hinf Hinfinity central controller SkrohinfPrrominromaxnmax SkrkrohinfPrrominromaxnmax Parameters P syslin list continuoustime linear system augmented plant given in statespace form or in transfer form r size of the P22 plant ie 2vector outputsinputs rominromax a priori bounds on ro with ro1gama2 romin0 usually nmax integer maximum number of iterations in the gamaiteration Description hinf computes Hinfinity optimal controller for the continuoustime plant P The partition of P into four subplants is given through the 2vector r which is the size of the 22 part of P P is given in statespace eg PsyslincABCD with ABCD constant matrices or PsyslincH with H a transfer matrix SkroHinfPrrominromaxnmax returns ro in rominromax and the central controller Sk in the same representation as P All calculations are made in statespace ie conversion to statespace is done by the function if necessary Invoked with three LHS parameters SkrkroHinfPrrominromaxnmax returns ro and the Parameterization of all stabilizing controllers a stabilizing controller K is obtained by KlftSkrPHI where PHI is a linear system with dimensions r and satisfy HnormPHI gamma rk r is the size of the Sk22 block and ro 1gama2 after nmax iterations Algorithm is adapted from SafonovLimebeer Note that P is assumed to be a continuoustime plant See Also gamitg ccontrg leqr Authors FDelebecque INRIA 1990 991 Name hinfst static Hinfinity problem KoptgamaopthinfstatDr Parameters D real matrix r 1x2 vector Kopt matrix Description computes a matrix Kopt such that largest singular value of lftDrKD11D12 KinvID22K D21 is minimal Static Hinfinity four blocks problem D is partionned as DD11 D12 D21 D22 where sizeD22rr1 r2 Authors FD 992 Name hnorm Hinfinity norm hinfnorm frequencyhnormsl rerr Parameters sl the state space system syslin list rerr max relative error default value 1e8 hinfnorm the infinity norm of Sl frequency frequency at which maximum is achieved Description produces the infinity norm of a statespace system the maximum over all frequencies of the maximum singular value See Also linfn linf svplot 993 Name hankelsv Hankel singular values nk2Whankelsvsl tol nk2hankelsvsl tol Parameters sl syslin list representing the linear system statespace tol tolerance parameter for detecting imaginary axis modes default value is 1000eps Description returns nk2 the squared Hankel singular values of sl and W PQ controllability gramian times observability gramian nk2 is the vector of eigenvalues of W Examples Adiag123 slsyslincArand32rand23nk2Whankelsvsl QMpbigWnk22epsc slrprojslslQMhankelsvslr See Also balreal equil equil1 994 Name hinf Hinfinity design of continuoustime systems AKBKCKDKRCOND hinfABCDnconnmeasgamma Parameters A the nbyn system state matrix A B the nbym system input matrix B C the pbyn system output matrix C D the pbym system matrix D ncon the number of control inputs m ncon 0 pnmeas ncon nmeas the number of measurements p nmeas 0 mncon nmeas gamma the parameter gamma used in Hinfinity design It is assumed that gamma is sufficiently large so that the controller is admissible gamma 0 AK the nbyn controller state matrix AK BK the nbynmeas controller input matrix BK CK the nconbyn controller output matrix CK DK the nconbynmeas controller matrix DK RCOND a vector containing estimates of the reciprocal condition numbers of the matrices which are to be inverted and estimates of the reciprocal condition numbers of the Riccati equations which have to be solved during the computation of the controller See the description of the algorithm in 1 RCOND 1 contains the reciprocal condition number of the control transformation matrix TU RCOND 2 contains the reciprocal condition number of the measurement transformation matrix TY RCOND 3 contains an estimate of the reciprocal condition number of the XRiccati equation RCOND 4 contains an estimate of the reciprocal condition number of the YRiccati equation hinf 995 Description AKBKCKDKRCOND hinfABCDnconnmeasgamma To compute the ma trices of an Hinfinity suboptimal nstate controller AK BK K CK DK for the continuoustime system A B1 B2 A B P C1 D11 D12 C D C2 D21 D22 and for a given value of gamma where B2 has column size of the number of control inputs ncon and C2 has row size of the number of measurements nmeas being provided to the controller References 1 PHr Petkov DW Gu and MM Konstantinov Fortran 77 routines for Hinf and H2 design of continuoustime linear control systems Report9814 Department of Engineering Leicester Univer sity August 1998 Examples example from Niconet report SLWN199912 Hinf A1 0 4 5 3 2 2 4 7 2 0 3 6 9 5 0 2 1 8 4 7 1 3 0 2 5 8 9 1 4 3 5 8 0 2 6 B3 4 2 1 0 2 0 1 5 2 5 7 0 7 2 4 6 1 1 2 3 9 8 0 5 1 2 3 6 2 C 1 1 2 4 0 3 3 0 5 1 1 1 7 5 0 8 2 2 9 3 4 0 3 7 0 1 2 1 6 2 D 1 2 3 0 0 0 4 0 1 0 5 3 4 0 1 hinf 996 0 1 0 1 3 0 0 1 7 1 Gamma1018425636157899 AKBKCKDK hinfABCD22Gamma See Also dhinf 997 Name imrep2ss statespace realization of an impulse response slimrep2ssv deg Parameters v vector coefficients of impulse response vk is the kth sample deg integer order required sl syslin list Description Impulse response to linear system conversion one input v must have an even number of columns Examples spoly0s H1s052s04 strictly proper np20wldivHnumHdennp repw1npwnp12np The impulse response H1ss2tfimrep2ssrep zpoly0z H2z234z15z216z08 Proper transfer function uzeros120u11 reprtitrHnumHdenu Impulse rep repldivHnumHden20 wzimrep2ssrep Realization with shifted impulse response ie strictly proper to proper H2ss2tfw See Also frep2tf arl2 timeid armax markp2ss ldiv 998 Name inistate Estimates the initial state of a discretetime system X0 inistateSYSYUTOLPRINTW X0 inistateABCYU X0 inistateACY x0Vrcnd inistateSYSYUTOLPRINTW Parameters SYS given system syslindtABCD Y the output of the system U the input of the system TOL TOL is the tolerance used for estimating the rank of matrices If TOL 0 then the given value of TOL is used as a lower bound for the reciprocal condition number Default prodsizematrixepsilonmachine where epsilonmachine is the relative machine pre cision PRINTW PRINTW is a switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default PRINTW 0 X0 the estimated initial state vector V orthogonal matrix which reduces the system state matrix A to a real Schur form rcnd estimate of the reciprocal condition number of the coefficient matrix of the least squares problem solved Description inistate Estimates the initial state of a discretetime system given the estimated system matrices and a set of inputoutput data X0 inistateSYSYUTOLPRINTW estimates the initial state X0 of the discretetime system SYS ABCD using the output data Y and the input data U The model structure is xk1 Axk Buk k 1 inistate 999 yk Cxk Duk The vectors yk and uk are transposes of the kth rows of Y and U respectively Instead of the first input parameter SYS an syslin object equivalent information may be specified using matrix parameters for instance X0 inistateABCYU or X0 inistateACY x0Vrcnd inistateSYSYUTOLPRINTW returns besides x0 the orthogonal matrix V which reduces the system state matrix A to a real Schur form as well as an estimate of the reciprocal condition number of the coefficient matrix of the least squares problem solved See Also findBD findx0BD 1000 Name invsyslin system inversion sl2invsyslinsl1 Parameters sl1sl2 syslin lists linear systems in state space representation Description Utility function Computes the state form of the inverse sl2 of the linear system sl1 which is also given in state form The Dmatrix is supposed to be full rank Old stuff used by invS when S is a syslin list See Also rowregul inv 1001 Name kpure continuous SISO system limit feedback gain Kkpuresys tol KRkpuresys tol Parameters sys SISO linear system syslin tol vector with 2 elements epsK epsI epsK is a tolerance used to determine if two values of K can be considered as equal epsI is a tolerance used to determine if a root is imaginary or not The default value is 1e6 1e6 K Real vector the vector of gains for which at least one closed loop pole is imaginary R Complex vector the imaginary closed loop poles associated with the values of K Description Kkpuresys computes the gains K such that the system sys feedback by Ki sysKi has poles on imaginary axis Examples spoly0s hsyslincs115ss2s3 clfevansh Kkpureh hfhK1 rootsdenomhf See Also evans krac2 1002 Name krac2 continuous SISO system limit feedback gain gkrac2sys Parameters sys SISO linear system syslin g constant Description krac2sys computes the gains g such that the system sys fedback by g sysg has 2 real equal poles Examples hsyslinc352poly5spoly002000200251sc clfevansh100 gkrac2h hf1hg1rootsdenomhf1 hf2hg2rootsdenomhf2 See Also evans kpure 1003 Name lcf normalized coprime factorization NMlcfsl Parameters sl linear system given in state space or transfer function syslin list NM two linear systems syslin list Description Computes normalized coprime factorization of the linear dynamic system sl sl M1 N Authors F D 1004 Name leqr Hinfinity LQ gain full state KXerrleqrP12Vx Parameters P12 syslin list Vx symmetric nonnegative matrix should be small enough KX two real matrices err a real number l1 norm of LHS of Riccati equation Description leqr computes the linear suboptimal Hinfinity LQ fullstate gain for the plant P12AB2C1D12 in continuous or discrete time P12 is a syslin list eg P12syslincAB2C1D12 C1 Q S C1 D12 D12 S R Vx is related to the variance matrix of the noise w perturbing x usually Vxgama2B1B1 The gain K is such that A B2K is stable X is the stabilizing solution of the Riccati equation For a continuous plant AB2invRSXXAB2invRSXB2invRB2VxXQSinvRS0 KinvRB2XS For a discrete time plant XAbarinvinvXB2invRB2VxAbarQbar0 KinvRB2invinvXB2invRB2VxAbarS with AbarAB2invRS and QbarQSinvRS leqr 1005 The 3blocks matrix pencils associated with these Riccati equations are discrete continuous I Vx 0 A 0 B2 I 0 0 A Vx B2 z0 A 0 Q I S s0 I 0 Q A S 0 B2 0 S 0 R 0 0 0 S B2 R See Also lqr Authors FD 1006 Name lft linear fractional transformation P1lftPK P1lftPrK P1r1lftPrPsrs Parameters P linear system syslin list the augmented plant implicitly partitioned into four blocks two input ports and two output ports K linear system syslin list the controller possibly an ordinary gain r 1x2 row vector dimension of P22 Ps linear system syslin list implicitly partitioned into four blocks two input ports and two output ports rs 1x2 row vector dimension of Ps22 Description Linear fractional transform between two standard plants P and Ps in state space form or in transfer form syslin lists r sizeP22 rssizeP22s lftPr K is the linear fractional transform between P and a controller K K may be a gain or a controller in state space form or in transfer form lftPK is lftPrK with rsize of K transpose P1 P11P12K IP22K1 P21 P1r1lftPrPsrs returns the generalized 2 ports lft of P and Ps P1 is the pair twoport interconnected plant and the partition of P1 into 4 blocks in given by r1 which is the dimension of the 22 block of P1 P and R can be PSSDs ie may admit a polynomial D matrix Examples spoly0s P1s 1s1 1s22s K 1s1 lftPK lftP11K P11P12Kinv1P22KP21 Numerically dangerous ss2tflfttf2ssPtf2ssK lftP1 lft 1007 f0001wPf w11 Improper plant PID control W1111s201sK11ss lftW11K ss2tflfttf2ssW11tf2ssK See Also sensi augment feedback sysdiag 1008 Name lin linearization ABCDlinsimx0u0 sllinsimx0u0 Parameters sim function x0 u0 vectors of compatible dimensions ABCD real matrices sl syslin list Description linearization of the nonlinear system yxdotsimxu around x0u0 sim is a function which computes y and xdot The output is a linear system syslin list sl or the four matrices ABCD For example if ftz is the function passed to ode eg zdftztzu and if we assume that yx zodex0t0tflistftzu compute xtf If simula is the following function deffyxdsimulaxuxdftztfxu yx the tangent linear system sl can be obtained by ABCDlinsimulazu sl syslincABCDx0 Examples deffyxdotsimxuxdotusinxux2yxdot1xdot2 sllinsim12 See Also external derivat 1010 Name linf infinity norm linfg epstol Parameters g is a syslin linear system eps is error tolerance on n tol threshold for imaginary axis poles Description returns the Linfinity norm of g nsup sigmaxgjw w sigmax largest singular value See Also hnorm linfn 1011 Name linfn infinity norm xfreqlinfnGPRECRELTOLoptions Parameters G is a syslin list PREC desired relative accuracy on the norm RELTOL relative threshold to decide when an eigenvalue can be considered on the imaginary axis options available options are trace or cond x is the computed norm freq vector Description Computes the Linf or Hinf norm of G This norm is welldefined as soon as the realization GABCD has no imaginary eigenvalue which is both controllable and observable freq is a list of the frequencies for which G is attainedie such that G j om G If 1 is in the list the norm is attained at infinity If 2 is in the list G is allpass in some direction so that G j omega G for all frequencies omega The algorithm follows the paper by G Robel AC34 pp 882884 1989 The case D0 is not treated separately due to superior accuracy of the general method when ABC is nearly non minimal The trace option traces each bisection step ie displays the lower and upper bounds and the current test point The cond option estimates a confidence index on the computed value and issues a warning if computations are illconditioned In the general case A neither stable nor antistable no upper bound is prespecified If by contrast A is stable or anti stable lower and upper bounds are computed using the associated Lyapunov solutions See Also hnorm Authors P Gahinet 1012 Name linmeq Sylvester and Lyapunov equations solver Xsep linmeqtaskABCflagtransschur Parameters task integer option to determine the equation type 1 solve the Sylvester equation 1a or 1b 2 solve the Lyapunov equation 2a or 2b 3 solve for the Cholesky factor opX the Lyapunov equation 3a or 3b A real matrix B real matrix C real matrix flag optional integer vector of length 3 or 2 containing options task 1 flag has length 3 flag1 0 solve the continuoustime equation 1a otherwise solve the discretetime equation 1b flag2 1 A is quasi upper triangular flag2 2 A is upper Hessenberg otherwise A is in general form flag3 1 B is quasi upper triangular flag3 2 B is upper Hessenberg otherwise B is in general form task 2 flag has length 2 linmeq 1013 flag1 if 0 solve continuoustime equation 2a otherwise solve discretetime equation 2b flag2 1 A is quasi upper triangular otherwise A is in general form task 3 flag has length 2 flag1 0 solve continuoustime equation 3a otherwise solve discretetime equation 3b flag2 1 A is quasi upper triangular otherwise A is in general form Default flag1 0 flag2 0 flag3 0 trans optional integer specifying a transposition option 0 solve the equations 1 3 with opM M 1 solve the equations 1 3 with opM M 2 solve the equations 1 with opA A opB B 3 solve the equations 1 with opA A opB B Default trans 0 schur optional integer specifying whether the HessenbergSchur or Schur method should be used Available for task 1 1 HessenbergSchur method one matrix is reduced to Schur form 2 Schur method two matrices are reduced to Schur form Default schur 1 X sep optional estimator of SepopAopA for 2a or SepdAA for 2b Description linmeq function for solving Sylvester and Lyapunov equations using SLICOT routines SB04MD SB04ND SB04PD SB04QD SB04RD SB03MD and SB03OD X linmeq1ABCflagtransschur Xsep linmeq2ACflagtrans X linmeq2ACflagtrans X linmeq3ACflagtrans linmeq 1014 linmeq solves various Sylvester and Lyapunov matrix equations opAX XopB C 1a opAXopB X C 1b opAX XopA C 2a opAXopA X C 2b opAopXopX opXopXopA opCopC 3a opAopXopXopA opXopX opCopC 3b where opM M or M Comments 1 For equation 1a or 1b when schur 1 the HessenbergSchur method is used reducing one matrix to Hessenberg form and the other one to a real Schur form Otherwise both matrices are reduced to real Schur forms If one or both matrices are already reduced to SchurHessenberg forms this could be specified by flag2 and flag3 For general matrices the HessenbergSchur method could be significantly more efficient than the Schur method 2 For equation 2a or 2b matrix C is assumed symmetric 3 For equation 3a or 3b matrix A must be stable or convergent respectively 4 For equation 3a or 3b the computed matrix X is the Cholesky factor of the solution ie the real solution is opXopX where X is an upper triangular matrix Revisions V Sima Katholieke Univ Leuven Belgium May 1999 May Sep 2000 V Sima University of Bucharest Romania May 2000 Examples 1a n40m30 ArandnnCrandnmBrandmm X linmeq1ABC normAXXBC1 1b flag100 X linmeq1ABCflag normAXBXC1 linmeq 1015 2a ArandnnCrandACCC X linmeq2AC normAX XA C1 2b X linmeq2AC1 0 normAXA XC1 3a Arandnn AAmaxrealspecA1eye shift eigenvalues CrandA Xlinmeq3AC normAXXXXA CC1 3b A 002 002010 002003 012 002 014 012010002014 010 012 005 003004004 002010 003006 008 011 003002004 008 014007 012014004 011007 004 CrandA Xlinmeq3AC1 0 normAXXA XX CC1 See Also sylv lyap Authors H Xu TU Chemnitz FR Germany Dec 1998 1016 Name lqe linear quadratic estimator Kalman Filter KXlqeP21 Parameters P21 syslin list K X real matrices Description lqe returns the Kalman gain for the filtering problem in continuous or discrete time P21 is a syslin list representing the system P21AB1C2D21 P21syslincAB1C2D21 or P21syslindAB1C2D21 The input to P21 is a white noise with variance B1 Q S BigV B1 D21 D21 S R X is the solution of the stabilizing Riccati equation and AKC2 is stable In continuous time ASinvRC2XXASinvRC2XC2invRC2XQSinvRS0 KXC2SinvR In discrete time XAXAAXC2B1D21pinvC2XC2D21D21C2XAD21B1B1B1 KAXC2B1D21pinvC2XC2D21D21 xhatt1 Ext1 y0yt onestep predicted x satisfies the recursion xhatt1AKC2xhatt Kyt Examples Assume the equations lqe 1017 x Ax Ge y Cx v with E ee Qe Evv R Eev N This is equivalent to x Ax B1 w y C2x D21 w with E Ge Ge v E B1w B1w D21w bigR v D21w B1B1 B1D21 D21B1 D21D21 GQeG GN NG R To find B1D21 given GQeRN form bigR GQeG GNNG R Then WWtfullrfbigR B1W1sizeG1 D21W1sizeC21 P21syslincAB1C2D21 KXlqeP21 Example nx5ne2ny3 Adiag1nxGonesnxne Conesnynx Qenene1 Rdiag1ny Nzerosneny bigR GQeG GNNG R WWtfullrfbigRB1W1sizeG1 D21W1sizeC1 C2C P21syslincAB1C2D21 KXlqeP21 Riccati check SGNQB1B1 ASinvRC2XXASinvRC2XC2invRC2XQSinvRS Stability check specAKC See Also lqr observer Authors F D 1018 Name lqg LQG compensator KlqgPr Parameters P syslin list augmented plant in statespace form r 1x2 row vector number of measurements number of inputs dimension of the 22 part of P K syslin list controller Description lqg computes the linear optimal LQG H2 controller for the augmented plant PsyslincABCD continuous time or PsyslindABCD discrete time The function lqg2stan returns P and r given the nominal plant weighting terms and variances of noises K is given by the following ABCD matrices ABKcKfCKfDKcKfKc0 where KclqrP12 is the controller gain and KflqeP21 is the filter gain See example in lqg2stan See Also lqg2stan lqr lqe hinf obscont Authors FD 1019 Name lqg2stan LQG to standard problem Prlqg2stanP22bigQbigR Parameters P22 syslin list nominal plant in statespace form bigQ QSSN symmetric weighting matrix bigR RTTV symmetric covariance matrix r 1x2 row vector number of measurements number of inputs dimension of the 22 part of P P syslin list augmented plant Description lqg2stan returns the augmented plant for linear LQG H2 controller design P22syslindomAB2C2 is the nominal plant it can be in continuous time domc or discrete time domd x Ax w1 B2u y C2x w2 for continuous time plant xn1 Axn w1 B2u y C2x w2 for discrete time plant The instantaneous cost function is x u bigQ xu The covariance of w1w2 is Ew1w2 w1w2 bigR If B1D21 is a factor of bigQ C1D12 is a factor of bigR and AB2C2D22 is a re alization of P22 then P is a realization of AB1B2C1C20D12D21D22 The negative feedback computed by lqg stabilizes P22 ie the poles of clP22K are stable Examples ny2nu3nx4 P22ssrandnynunx bigQrandnxnunxnubigQbigQbigQ lqg2stan 1020 bigRrandnxnynxnybigRbigRbigR Prlqg2stanP22bigQbigRKlqgPr KLQGcontroller spechclPrK Closed loop should be stable Same as ClP22K specClA spoly0s lqg2stan1s2eye22eye22 See Also lqg lqr lqe obscont hinf augment fstabst feedback Authors FD 1021 Name lqgltr LQG with loop transform recovery kfkclqgltrslmuro Parameters sl linear system in statespace form syslin list muro real positive numbers chosen small enough kfkc controller and observer Kalman gains Description returns the Kalman gains for x ax bu lw1 sl y cx muIw2 z hx Cost function oo J E ztzt ro2ututdt lqg 0 The lqgltr approach looks for LmuHro such that Jlqg Jfreq where oo J trS W W S trT Tdw freq 0 and S I GK1 T GKIGK1 See Also syslin 1022 Name lqr LQ compensator full state KXlqrP12 Parameters P12 syslin list statespace linear system KX two real matrices Description lqr computes the linear optimal LQ fullstate gain for the plant P12AB2C1D12 in contin uous or discrete time P12 is a syslin list eg P12syslincAB2C1D12 The cost function is l2norm of zz with zC1 x D12 u ie xu BigQ xu where C1 Q S BigQ C1 D12 D12 S R The gain K is such that A B2K is stable X is the stabilizing solution of the Riccati equation For a continuous plant AB2invRSXXAB2invRSXB2invRB2XQSinvRS0 KinvRB2XS For a discrete plant XAXAAXB2C1D12pinvB2XB2D12D12B2XAD12C1C1C1 KpinvB2XB2D12D12B2XAD12C1 An equivalent form for X is XAbarinvinvXB2invrB2AbarQbar lqr 1023 with AbarAB2invRS and QbarQSinvRS The 3blocks matrix pencils associated with these Riccati equations are discrete continuous I 0 0 A 0 B2 I 0 0 A 0 B2 z0 A 0 Q I S s0 I 0 Q A S 0 B2 0 S 0 R 0 0 0 S B2 R Caution It is assumed that matrix R is non singular In particular the plant must be tall number of outputs number of inputs Examples Arand22Brand21 two states one input Qdiag25R2 Usual notations xQx uRu BigsysdiagQR Now we calculate C1 and D12 wwpfullrfBigC1wp12D12wp3 C1D12C1D12Big PsyslincABC1D12 The plant continuoustime KXlqrP specABK check stability normAXXAXBinvRBXQ1 Riccati check PsyslindABC1D12 Discrete time plant KXlqrP specABK check stability normAXAAXBpinvBXBRBXAQX1 Riccati check See Also lqe gcare leqr Authors FD 1024 Name ltitr discrete time response state space XltitrABUx0 xfXltitrABUx0 Parameters AB real matrices of appropriate dimensions UX real matrices x0xf real vectors default value0 for x0 Description calculates the time response of the discrete time system xt1 Axt But The inputs uis are the columns of the U matrix Uu0u1un x0 is the vector of initial state default value 0 X is the matrix of outputs same number of columns as U Xx0x1x2xn xf is the vector of final state xfXn1 Examples Aeye22B11 x012 u12345 xltitrABux0 x1Ax0Bu1 x2Ax1Bu2 x3Ax2Bu3 See Also rtitr flts 1025 Name macglov Mac Farlane Glover problem PrmacglovSl Parameters Sl linear system syslin list P linear system syslin list augmented plant r 1x2 vector dimension of P22 Description PrmacglovSl returns the standard plant P for the GloverMcFarlane problem For this problem rooptimal 1hankelnormNM with NMlcfsl Normalized coprime factorization ie gamaoptimal 1sqrtrooptimal Authors F Delebecque INRIA 1026 Name markp2ss Markov parameters to statespace slmarkp2ssmarkparnnoutnin Parameters markpar matrix nnoutnin integers Sl syslin list Description given a set of n Markov parameters stacked in the rowmatrix markpar of size noutXnnin markp2ss returns a statespace linear system sl syslin list such that with ABCDabcdsl CB markpar1nout1nin CAB markpar1noutnin12nin Examples Wssrand234 random system with 2 outputs and 3 inputs abcdabcdW markparcbcabca2bca3bca4b Smarkp2ssmarkpar523 ABCDabcdS MarkparCBCABCA2BCA3BCA4B normmarkparMarkpar1 Caution ca5b is not CA5B See Also frep2tf tf2ss imrep2ss 1027 Name minreal minimal balanced realization slbminrealsl tol Parameters slslb syslin lists tol real threshold Description aebeceminrealabcdomain tol returns the balanced realization of linear system sl syslin list sl is assumed stable tol threshold used in equil1 Examples Aeye22rand22zeros222eye22 Brand22zeros22Crand24 slsyslincABC slbminrealsl ss2tfsl ss2tfslb ctrgramsl cleanctrgramslb cleanobsgramslb See Also minss balreal arhnk equil equil1 Authors S Steer INRIA 1987 1028 Name minss minimal realization slcminss sl tol Parameters slslc syslin lists linear systems in statespace form tol real threshold for rank determination see contr Description minss returns in slc a minimal realization of sl Examples slsyslinc1 00 2102 1 ssprintsl ssprintminsssl See Also contr minreal arhnk contrss obsvss balreal 1029 Name mucomp mu structured singular value calculation BOUND D G mucompZ K T Parameters Z the complex nbyn matrix for which the structured singular value is to be computed K the vector of length m containing the block structure of the uncertainty T the vector of length m indicating the type of each block TI 1 if the corresponding block is real TI 2 if the corresponding block is complex BOUND the upper bound on the structured singular value D G vectors of length n containing the diagonal entries of the diagonal matrices D and G respectively such that the matrix ZD2Z sqrt1GZZG bound2D2 is negative semidefinite Description To compute an upper bound on the structured singular value for a given square complex matrix and given block structure of the uncertainty Reference Slicot routine AB13MD 1030 Name narsimul armax simulation using rtitr znarsimulabdsiguupypep znarsimularuupypep Description ARMAX simulation Same as arsimul but the method is different the simulation is made with rtitr Authors JPh Chancelier ENPC Cergrene 1031 Name nehari Nehari approximant xnehariR tol Parameters R linear system syslin list x linear system syslin list tol optional threshold Description xnehariR tolreturns the Nehari approximant of R R linear system in statespace representation syslin list R is strictly proper and R is stable ie R is anti stable R X oo min R Y oo Y in Hoo 1032 Name noisegen noise generation bnoisegenpasTmaxsig Description generates a Scilab function bNoiset where Noiset is a piecewise constant function constant on kpask1pas The value on each constant interval are random values from iid Gaussian variables of standard deviation sig The function is constant for t0 and tTmax Examples noisegen053010 x500135 yfevalxNoise plotxy 1033 Name obsgram observability gramian GoobsgramAC dom Goobsgramsl Parameters AC real matrices of appropriate dimensions dom string d or c default value sl syslin list Description Observability gramian of the pair AC or linear system sl syslin list dom is the domain which can be c continuous system default d discrete system Examples Adiag13Crand23 GoobsgramACc wsyslincAC Goobsgramw normGoAAGoCC1 normlyapACCcGo1 AA4 GoobsgramACd discrete time case normlyapACCdGo1 See Also ctrgram obsvss obsvmat lyap 1034 Name obscont observer based controller KobscontPKcKf JrobscontPKcKf Parameters P syslin list nominal plant in statespace form continuous or discrete time Kc real matrix full state controller gain Kf real matrix filter gain K syslin list controller J syslin list extended controller r 1x2 row vector Description obscont returns the observerbased controller associated with a nominal plant P with matrices ABCD syslin list The fullstate control gain is Kc and the filter gain is Kf These gains can be computed for example by pole placement ABKc and AKfC are usually assumed stable K is a statespace representation of the compensator K yu in xdot A x B u yC x D u zdot A Kf Cz Kf y B u uKc z K is a linear system syslin list with matrices given by KABKcKfCKfDKcKf Kc The closed loop feedback system Cl v y with negative feedback K ie y P u u v K y or xdot A x B u y C x D u zdot A Kf C z Kf y B u u v F z is given by Cl PK The poles of Cl specclA are located at the eigenvalues of ABKc and AKfC Invoked with two output arguments obscont returns a square linear system K which parametrizes all the stabilizing feedbacks via a LFT obscont 1035 Let Q an arbitrary stable linear system of dimension r2xr1 ie number of inputs x number of outputs in P Then any stabilizing controller K for P can be expressed as KlftJrQ The controller which corresponds to Q0 is KJ1nu1ny this K is returned by KobscontPKcKf r is sizeP ie the vector number of outputs number of inputs Examples ny2nu3nx4PssrandnynunxABCDabcdP KcppolAB1111 Controller gain KfppolAC2222KfKf Observer gain clPobscontPKcKfspecclA closed loop system JrobscontPKcKf Qssrandnuny3QAQAmaxirealspecQA05eyeQA Q is a stable parameter KlftJrQ spechclPK closedloop A matrix should be stable See Also ppol lqg lqr lqe hinf lft syslin feedback observer Authors FD 1036 Name observer observer design ObsobserverSysJ ObsUmobserverSys flagalfa Parameters Sys syslin list linear system J nx x ny constant matrix output injection matrix flag character strings pp or st default alfa location of closedloop poles optional parameter default1 Obs linear system syslin list the observer U orthogonal matrix see dtility m integer dimension of unstable unobservable st or unobservable pp subspace Description ObsobserverSysJ returns the observer ObssyslintdAJCBJD JeyeA obtained from Sys by a J output injection td is the time domain of Sys More gen erally observer returns in Obs an observer for the observable part of linear system Sys dotxA x Bu yCx Du represented by a syslin list Sys has nx state variables nu inputs and ny outputs Obs is a linear system with matrices AoBoIdentity where Ao is no x no Bo is no x nuny Co is no x no and nonxm Input to Obs is uy and output of Obs is xhatestimate of x modulo unobservable subsp case flagpp or xhatestimate of x modulo unstable unobservable subsp case flagst case flagst zHx can be estimated with stable observer iff HU1m0 and assignable poles of the observer are set to alfa1alfa2 case flagpp zHx can be estimated with given error spectrum iff HU1m0 all poles of the observer are assigned and set to alfa1alfa2 If H satifies the constraint HU1m0 kerH contains unobssubsp of Sys one has HU0H2 and the observer for zHx is H2Obs with H2HUm1nx ie Co the Cmatrix of the observer for Hx is CoH2 In the particular case where the pair AC of Sys is observable one has m0 and the lin ear system UObs resp HUObs is an observer for x resp Hx The error spectrum is alpha1alpha2alphanx observer 1037 Examples nx5nu1ny1un3us2Sysssrandnynunxlistdtususun nx5 states nu1 input ny1 output un3 unobservable states us2 of them unstable ObsUmobserverSys Stable observer default WUHWm1nxABCDabcdSys HU0eyenono Sys2ss2tfsyslincABH Transfer uz IdueyenunuSys3ss2tfHUm1ObsIduSys Transfer uuySysuObsxhatHUxhatzhat ie uoutput of Obs this transfer must equal Sys2 the uz transfer H2eye Assume a Kalman model dotx A x B u G w y C x D u H w v with Eww QN Evv RN Ewv NN To build a Kalman observer 1Form BigR GQNG GQNHGNN HQNGNNG HQNHRN the covariance matrix of the noise vector GwHwv 2Build the plant P21 dotx A x B1 e y C2 x D21 e with e a unit white noise WWtfullrfBigR B1W1sizeG1D21W1sizeC1 C2C P21syslincAB1C2D21 3Compute the Kalman gain L lqeP21 4 Build an observer for the plant ABCD Plant syslincABCD Obs observerPlantL Test example Adiag14 Bones41 CB D 0 G2B H3 QN2 RN5 NN0 BigR GQNG GQNHGNN HQNGNNG HQNHRN WWtfullrfBigR B1W1sizeG1D21W1sizeC1 C2C P21syslincAB1C2D21 L lqeP21 Plant syslincABCD Obs observerPlantL specObsA See Also dtility unobs stabil Authors FD 1038 Name obsvmat observability matrix OobsvmatAC Oobsvmatsl Parameters ACO real matrices sl syslin list Description obsvmat returns the observability matrix OC CA CA2 CAn1 See Also contrss obsvss obsgram 1039 Name obsvss observable part AoBoCoobsvssABC tol sloobsvsssl tol Parameters ABCAoBoCo real matrices slslo syslin lists tol real threshold default value 100eps Description sloAoBoCo is the observable part of linear system slABC syslin list tol threshold to test controllability see contr default value 100eps See Also contr contrss obsvmat obsgram 1040 Name pmargin phase margin and associated crossover frequency phmfr pmarginh phmpmarginh Parameters h a SISO linear system see syslin phm a number the phase margin in degree if it exists or an empty matrix fr a number the corresponding frequency in hz or an empty matrix Description Given a SISO linear system in continuous or discrete time pmargin returns phm the phase margin in degree of h and fr the achieved corresponding frequency in hz The phase margin is the values of the phase at frequency points where the nyquist plot of h crosses the unit circle In other words the phase margin is the difference between the phase of the frequency response of h and 180 when the gain of h is 1 The algorithm uses polynomial root finder to solve the equations hshs1 for the continuous time case hzh1z1 for the discrete time case Examples continuous case hsyslinc1s32ss2 pfrpmarginh pfrpmarginh07 showmarginsh07nyquist discrete case h syslin01004798z00464z2181z09048ok p fpmarginh showmarginshnyquist See Also pmargin showmargins repfreq black bode chart nyquist Authors Serge Steer INRIA 1041 Name parrot Parrots problem KparrotDr Parameters DK matrices r 1X2 vector dimension of the 22 part of D Description Given a matrix D partionned as D11 D12 D21 D22 where sizeD22rr1r2 compute a matrix K such that largest singular value of D11 D12 D21 D22K is minimal Parrots problem See Also hinfst 1042 Name pfss partial fraction decomposition eltspfssSl eltspfssSlrmax eltspfssSlcord eltspfssSlrmaxcord Parameters Sl syslin list statespace or transfer linear system rmax real number controlling the condition ing of block diagoanalization cord character string c or d Description Partial fraction decomposition of the linear system Sl in statespace form transfer matrices are au tomatically converted to statespace form by tf2ss elts is the list of linear systems which add up to Sl ie eltslistS1S2S3Sn with Sl S1 S2 Sn Each Si contains some poles of S according to the blockdiagonalization of the A matrix of S For non proper systems the polynomial part of Sl is put in the last entry of elts If Sl is given in transfer form it is first converted into statespace and each subsystem Si is then converted in transfer form The A matrix is of the statespace is put into block diagonal form by function bdiag The optional parameter rmax is sent to bdiag If rmax should be set to a large number to enforce blockdiago nalization If the optional flag cordc is given the elements in elts are sorted according to the real part resp magnitude if cordd of the eigenvalues of A matrices Examples Wssrand116 eltspfssW W10for k1sizeelts W1W1ss2tfeltskend cleanss2tfWW1 See Also pbig bdiag coffg dtsi Authors FD 1043 Name phasemag phase and magnitude computation phidbphasemagz mod Parameters z matrix or row vector of complex numbers mod character string modc continuous representation between infinity and 360 degrees default modm representation between 360 and 0 degrees phi phases in degree of z db magnitude in Db Description phasemag computes the phases and magnitudes of the entries of a complex matrix For modcphasemag computes phii1 to minimize the distance with phii ie it tries to obtain a continuous representation of the phase To obtain the phase between pi and pi use phiatanimagzrealz Examples spoly0s hsyslinc1s5s101006ssss3 frqrfrepfreqh01200005 scf plot2dfrqphasemagrfc scf plot2dfrqphasemagrfm See Also repfreq gainplot atan bode 1044 Name ppol pole placement KppolABpoles Parameters AB real matrices of dimensions nxn and nxm poles real or complex vector of dimension n K real matrix negative feedback gain Description KppolABpoles returns a mxn gain matrix K such that the eigenvalues of ABK are poles The pair AB must be controllable Complex number in poles must appear in conjugate pairs An outputinjection gain F for AC is obtained as follows FtppolACpoles FFt The algorithm is by PH Petkov Examples Arand33Brand32 FppolAB123 specABF See Also canon stabil 1045 Name prbsa pseudo random binary sequences generation uprbsanncids Description generation of pseudo random binary sequences uu0u1un1 u takes values in 11 and changes at most nc times its sign ids can be used to fix the date at which u must change its sign ids is then an integer vector with values in 1n Examples uprbsa5010 plot2d2onn150u1151 0155015 1046 Name projsl linear system projection slpprojslslQM Parameters slslp syslin lists QM matrices projection factorization Description slp projected model of sl where QM is the full rank factorization of the projection If ABCD is the representation of sl the projected model is given by MAQMBCQD Usually the projection QM is obtained as the spectral projection of an appropriate auxiliary matrix W eg W product of weighted gramians or product of Riccati equations Examples randseed0slssrand225ABCDabcdslpolesspecA QMpbigA0c keeping unstable poles slredprojslslQMspecslredA slDrand22 making proper system trzerossl zeros of sl wiinvsl wiinverse in statespace qmpsmallwiA2d keeping small zeros poles of wi ie absz2 slred2projslslqm trzerosslred2 zeros of slred2 small zeros of sl Example keeping second order modes Adiag123 slsyslincArand32rand23nk2Whankelsvsl QMpbigWnk22epsc keeping 2 eigenvalues of W slrprojslslQM reduced model hankelsvslr See Also pbig Authors F D 1047 Name reglin Linear regression absigreglinxy Description solve the regression problem yax b in the least square sense sig is the standard deviation of the residual x and y are two matrices of size xpn and yqn where n is the number of samples The estimator a is a matrix of size qp and b is a vector of size q1 simulation of data for a35 and b31 xrand5100 aatestmatrixmagi5aaaa13 bb91011 yaax bbones1100 01rand3100 identification absigreglinxy maxiabsaaa maxiabsbbb an other example fitting a polynom f1100 xff f y 23x 10onesf 01randf abreglinxy See Also pinv leastsq qr 1048 Name repfreq frequency response frq repfrepfreqsysfminfmax step frq repfrepfreqsys frq frqrepfsplitfrepfreqsysfminfmax step frqrepfsplitfrepfreqsys frq Parameters sys syslin list SIMO linear system fminfmax two real numbers lower and upper frequency bounds frq real vector of frequencies Hz step logarithmic discretization step splitf vector of indexes of critical frequencies repf vector of the complex frequency response Description repfreq returns the frequency response calculation of a linear system If syss is the transfer function of Sys repfk equals syss evaluated at s ifrqk2pi for continuous time systems and at exp2ipidtfrqk for discrete time systems dt is the sampling period dbk is the magnitude of repfk expressed in dB ie dbk20log10absrepfk and phik is the phase of repfk expressed in degrees If fminfmaxstep are input parameters the response is calculated for the vector of frequencies frq given by frq10log10fminsteplog10fmax fmax If step is not given the output parameter frq is calculated by frqcalfrqsysfminfmax Vector frq is splitted into regular parts with the split vector frqsplitfksplitfk 11 has no critical frequency sys has a pole in the range frqsplitfkfrqsplitfk1 and no poles outside Examples Adiag12B11C11 SyssyslincABC frq00025wfrq2pi frqfrequencies in Hz wfrequencies in radsec frq1rep repfreqSysfrq dbphidbphirep Systfss2tfSys Transfer function of Sys xhornerSystfw2sqrt1 x is Systfs evaluated at s i w2 repfreq 1049 rep20logabsxlog10 magnitude of x in dB db2 same as rep angatanimagxrealx in rad angang180pi in degrees phi2 repfrepfreqSysfrq repf2x See Also bode freq calfrq horner nyquist dbphi Authors S S 1050 Name ricdesc Riccati equation XricdescH E X1X2zeroricdescH E Parameters HE real square matrices X1X2 real square matrices zero real number Description Riccati solver with hamiltonian matrices as inputs In the continuous time case calling sequence is ricdescrH one input Riccati equation is Ec AX XA XRX Q 0 Defining the hamiltonian matrix H by H A R Q A with the calling sequence X1X2zeroricdescrH the solution X is given by XX1X2 zero L1 norm of rhs of Ec The solution X is also given by XriccatiAQRc In the discretetime case calling sequence is ricdescrHE two inputs The Riccati equation is Ed AXAAXBRBXB1BXACX 0 Defining GBRB and the hamiltonian pencil EH by EeyennG HA 0onesnn 0onesnnA C eyenn with the calling sequence X1X2errricdescrHE the solution X is given by XX1 X2 ricdesc 1051 zero L1 norm of rhs of Ed The solution X is also given by XriccatiAGCd with GBRB See Also riccati 1052 Name ricc Riccati equation XRCONDFERRriccABCcontmethod XRCONDFERRriccFGHdiscmethod Parameters ABC real matrices of appropriate dimensions FGH real matrices of appropriate dimensions X real matrix contdisc imposed string flag for continuous or discrete method schr or sign for continuoustime systems and schr or invf for discretetyme systems Description Riccati solver Continuous time XriccABCcont gives a solution to the continuous time ARE AXXAXBXC0 B and C are assumed to be nonnegative definite AG is assumed to be stabilizable with GG a full rank factorization of B AH is assumed to be detectable with HH a full rank factorization of C Discrete time XriccFGHdisc gives a solution to the discrete time ARE XFXFFXG1G2G1XG11G1XFH F is assumed invertible and G G1invG2G1 One assumes FG1 stabilizable and CF detectable with CC full rank factorization of H Use preferably ricdesc ricc 1053 C D are symmetric It is assumed that the matrices A C and D are such that the corresponding matrix pencil has N eigenvalues with moduli less than one Error bound on the solution and a condition estimate are also provided It is assumed that the matrices A C and D are such that the corresponding Hamiltonian matrix has N eigenvalues with negative real parts Examples Standard formulas to compute Riccati solutions Arand33Brand32Crand33CCCRrand22RRReye BBinvRB XriccABCcont normAXXAXBXC1 HA BC A TdschureyeHHcontTT1d X1T46T13 normX1X1 TdschurHcontTT1d X2T46T13 normX2X1 Discrete time case FABrand32G1BG2RGG1G2G1HC XriccFGHdisc normFXFFXG1G2G1XG1G1XFHX H1eye33 Gzeros33 F H2F zeros33H eye33 TdschurH2H1discTT1dX1T46T13 normX1X1 FiinvF HamiFi FiGHFi FHFiG TdschurHamidTT1d FitinvF HamFGFitH GFitFitH Fit TdschurHamdTT1dX2T46T13 normX2X1 See Also riccati ricdesc schur Authors P Petkov Used Functions See SCImodulescacsdsrcslicotriccpackf 1054 Name riccati Riccati equation XriccatiABCdomtyp X1X2riccatiABCdomtyp Parameters ABC real matrices nxn B and C symmetric dom c or d for the time domain continuous or discrete typ string eigen for block diagonalization or schur for Schur method X1X2X square real matrices X2 invertible X symmetric Description XriccatiABCdomtyp solves the Riccati equation AXXAXBXC0 in continuous time case or AXAAXB1B2B1XB1B1XACX with BB1B2B1 in the discrete time case If called with two output arguments riccati returns X1X2 such that XX1X2 See Also ricc ricdesc 1055 Name rowinout innerouter factorization InnXGbarrowinoutG Parameters G linear system syslin list ABCD Inn inner factor syslin list Gbar outer factor syslin list X rowcompressor of G syslin list Description Innerouter factorization and row compression of lxp G ABCD with lp G is assumed to be tall lp without zero on the imaginary axis and with a D matrix which is full column rank G must also be stable for having Gbar stable G admits the following innerouter factorization G Inn Gbar 0 where Inn is square and inner all pass and stable and Gbar square and outer ie Gbar is square bi proper and bistable Gbar inverse is also proper and stable Note that Gbar XG 0 is a row compression of G where X Inn inverse is allpass ie T X s Xs Identity for the continuous time case See Also syslin colinout 1056 Name rowregul removing poles and zeros at infinity StmpWsrowregulSlalfabeta Parameters SlStmp syslin lists alfabeta real numbers new pole and zero positions Description computes a postfilter Ws such that StmpWsSl is proper and with full rank D matrix Poles at infinity of Sl are moved to alfa Zeros at infinity of Sl are moved to beta Sl is a assumed to be a right invertible linear system syslin list in statespace representation with possibly a polynomial D matrix This function is the dual of colregul see function code Examples ss w1s0ss322s Sltf2ssw StmpWsrowregulSl12 StmpD D matrix of Stmp cleanss2tfStmp See Also invsyslin colregul Authors F D R N 1057 Name rtitr discrete time response transfer matrix yrtitrNumDenu upyp Parameters NumDen polynomial matrices resp dimensions nxm and nxn u real matrix dimension mxt1 upyp real matrices up dimension mxmaxidegreeDen default values0 yp dimension nx maxidegreeDen y real matrix Description yrtitrNumDenu upyp returns the time response of the discrete time linear system with transfer matrix Den1 Num for the input u ie y and u are such that Den y Num u at t01 If d1maxidegreeDen and d2maxidegreeNum the polynomial matrices Denz and Numz may be written respectively as Dz D0 D1 z Dd1 zd1 Nz N0 N1 z Nd2 zd2 and Den y Num u is interpreted as the recursion D0ytD1yt1 Dd1ytd1 N0 ut Nd2 utd2 It is assumed that Dd1 is non singular The columns of u are the inputs of the system at t01T uu0 u1uT The outputs at t01Td1d2 are the columns of the matrix y y y0 y1 yTd1d2 up and yp define the initial conditions for t 0 ie up ud1 u1 rtitr 1058 yp yd1 y1 Depending on the relative values of d1 and d2 some of the leftmost components of up yp are ignored The default values of up and yp are zero up 0onesmd1 yp0onesnd1 Examples zpoly0z Num1zDen1zu12345 rtitrNumDenuu Other examples siso causal n11d1poly1 1zcoeff yjyj1uj1 r10 1 0 1 0 1 0 1 0 1 0 rrtitrn1d1ones110normr1r1 hot restart rrtitrn1d1ones1910normr1211r non causal n2poly1 1 1zcoeffd2d1 yjyj1uj1ujuj1 r22 1 2 1 2 1 2 1 2 rrtitrn2d2ones110normrr21 hot restart rrtitrn2d2ones1912normr229r1 MIMO example causal d1d1diag1 05n11 3 12 4 1r1514r1 rrtitrn1d1ones310normr1r1 rrtitrn1d1ones3911100 normr1211r1 polynomial n1 same ex n111poly1zcrrtitrn1d1ones310normr1r1 rrtitrn1d1ones3911100 normr1211r1 non causal d2d1n2n2n1r2514r2 rrtitrn2d2ones310normr2r rrtitrn2d2ones391111028 normr229r1 Statespace or transfer a 021 063 056 023 031 076 085 066 023 093 0 069 073 022 021 033 088 02 088 031 067 007 054 065 036 b 029 05 092 057 044 004 048 027 048 033 063 026 059 041 041 c 028 078 011 015 084 rtitr 1059 013 021 069 07 041 d 041 011 056 088 02 059 ssyslindabcd hss2tfsnumhnumdenhdendenden11eye22 u1u3100r3fltsus rrtitrnumdenunormr3r1 See Also ltitr exp flts 1060 Name sensi sensitivity functions SeReTesensiGK SiRiTisensiGKflag Parameters G standard plant syslin list K compensator syslin list flag character string o default value or i Se output sensitivity function IGK1 Re KSe Te GKSe output complementary sensitivity function Description sensi computes sensitivity functions If G and K are given in statespace form the systems returned are generically minimal Calculation is made by lft eg Se can be given by the commands P augmentGS SelftPK If flag i SiRiTisensiGKi returns the input sensitivity functions SeReTe inveyeGKKinveyeGKGKinveyeGK SiRiTi inveyeKGGinveyeKGKGinveyeKG Examples Gssrand113Kssrand113 SeReTesensiGK Se1inveyeGK Other way to compute ss2tfSe Se seen in transfer form ss2tfSe1 ss2tfTe ss2tfGKSe1 SiRiTisensiGKi w1ss2tfSiss2tfRiss2tfTi w2ss2tfinveyeKGss2tfGinveyeKGss2tfKGinveyeKG cleanw1w2 See Also augment lft hcl 1061 Name showmargins display gain and phase margin and associated crossover frequencies showmarginsh showmarginshbode showmarginshnyquist Parameters h a SISO linear system see syslin Description Given a SISO linear system in continuous or discrete time showmargins display gain and phase margin and associated crossover frequencies on a bode the defaut or nyquist representation of the frequency response of the system Examples continuous case hsyslinc002909011827s012823s2035659s30256s401s5 0040901827s128225s231909s3256s4s5 showmarginsh showmarginshnyquist discrete case h syslin01001547001599z z2181z09048 showmarginsh showmarginshnyquist See Also pmargin gmargin bode nyquist Authors Serge Steer INRIA 1062 Name sident discretetime statespace realization and Kalman gain ACBDKQRySrcnd sidentmethjobsnlRtoltAi Ciprintw Parameters meth integer option to determine the method to use 1 MOESP method with past inputs and outputs 2 N4SID method 3 combined method A and C via MOESP B and D via N4SID job integer option to determine the calculation to be performed 1 compute all system matrices A B C D 2 compute the matrices A and C only 3 compute the matrix B only 4 compute the matrices B and D only s the number of block rows in the processed input and output block Hankel matrices s 0 n integer the order of the system l integer the number of the system outputs R the 2mlsby2mls part of R contains the processed upper triangular factor R from the QR factorization of the concatenated blockHankel matrices and further details needed for com puting system matrices tol optional tolerance used for estimating the rank of matrices If tol 0 then the given value of tol is used as a lower bound for the reciprocal condition number an mbyn matrix whose estimated condition number is less than 1tol is considered to be of full rank Default mnepsilonmachine where epsilonmachine is the relative machine precision t optional the total number of samples used for calculating the covariance matrices Either t 0 or t 2mls This parameter is not needed if the covariance matrices andor the Kalman predictor gain matrix are not desired If t 0 then K Q Ry and S are not computed Default t 0 sident 1063 Ai real matrix Ci real matrix printw optional switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default printw 0 A real matrix C real matrix B real matrix D real matrix K real matrix kalman gain Q optional the nbyn positive semidefinite state covariance matrix used as state weighting matrix when computing the Kalman gain RY optional the lbyl positive semidefinite output covariance matrix used as output weighting matrix when computing the Kalman gain S optional the nbyl stateoutput crosscovariance matrix used as crossweighting matrix when computing the Kalman gain rcnd optional vector of length lr containing estimates of the reciprocal condition numbers of the matrices involved in rank decisions least squares or Riccati equation solutions where lr 4 if Kalman gain matrix K is not required and lr 12 if Kalman gain matrix K is required Description SIDENT function for computing a discretetime statespace realization ABCD and Kalman gain K using SLICOT routine IB01BD ACBD sidentmeth1snlR ACBDKQRySrcnd sidentmeth1snlRtolt AC sidentmeth2snlR B sidentmeth3snlRtol0AiCi BKQRySrcnd sidentmeth3snlRtoltAiCi sident 1064 BD sidentmeth4snlRtol0AiCi BDKQRySrcnd sidentmeth4snlRtoltAiCi SIDENT computes a statespace realization ABCD and the Kalman predictor gain K of a dis cretetime system given the system order and the relevant part of the R factor of the concatenated blockHankel matrices using subspace identification techniques MOESP N4SID or their combina tion The model structure is xk1 Axk Buk Kek k 1 yk Cxk Duk ek where xk is the ndimensional state vector at time k uk is the mdimensional input vector yk is the ldimensional output vector ek is the ldimensional disturbance vector and A B C D and K are real matrices of appropriate dimensions Comments 1 The nbyn system state matrix A and the pbyn system output matrix C are computed for job 2 2 The nbym system input matrix B is computed for job 2 3 The lbym system matrix D is computed for job 1 or 4 4 The nbyl Kalman predictor gain matrix K and the covariance matrices Q Ry and S are computed for t 0 Examples generate data from a given linear system A 05 0101 02 01 0 0101 04060701 08 0 0606 B 080111 C 1 2 1 0 SYSsyslin01ABC nsmp100 Uprbsansmpnsmp5 YfltsUSYS03rand1nsmpnormal S 15 N 3 METH1 RN1 findRSYUMETH ACBDK sidentMETH1SN1R SYS1syslin1ABCD SYS1X0 inistateSYS1YU sident 1065 Y1fltsUSYS1 clfplot2d1nsmpYY1 METH 2 RN1SVAL findRSYUMETH tol 0 t sizeU12S1 ACBDK sidentMETH1SN1Rtolt SYS1syslin1ABCD SYS1X0 inistateSYS1YU Y1fltsUSYS1 clfplot2d1nsmpYY1 See Also findBD sorder Authors V Sima Research Institute for Informatics Bucharest Oct 1999 Revisions May 2000 July 2000 1066 Name sm2des system matrix to descriptor Dessm2desSm Parameters Sm polynomial matrix pencil system matrix Des descriptor system listdesABCDE Description Utility function converts the system matrix Sm sE A B C D to descriptor system DeslistdesABCDE See Also ss2des sm2ss 1067 Name sm2ss system matrix to statespace Slsm2ssSm Parameters Sm polynomial matrix pencil system matrix Sl linear system syslin list Description Utility function converts the system matrix Sm sI A B C D to linear system in statespace representation syslin list See Also ss2des 1068 Name sorder computing the order of a discretetime system Ronsvalrcnd sordermethalgjobdbatchconctsYUtol printwldworkRi Parameters meth integer option to determine the method to use 1 MOESP method with past inputs and outputs 2 N4SID method alg integer option to determine the algorithm for computing the triangular factor of the concatenated blockHankel matrices built from the inputoutput data 1 Cholesky algorithm on the correlation matrix 2 fast QR algorithm 3 standard QR algorithm jobd integer option to specify if the matrices B and D should later be computed using the MOESP approach 1 the matrices B and D should later be computed using the MOESP approach 2 the matrices B and D should not be computed using the MOESP approach This parameter is not relevant for meth 2 batch integer option to specify whether or not sequential data processing is to be used and for sequential processing whether or not the current data block is the first block an intermediate block or the last block as follows 1 the first block in sequential data processing 2 an intermediate block in sequential data processing 3 the last block in sequential data processing 4 one block only nonsequential data processing sorder 1069 conct integer option to specify whether or not the successive data blocks in sequential data processing belong to a single experiment as follows 1 the current data block is a continuation of the previous data block andor it will be con tinued by the next data block 2 there is no connection between the current data block and the previous andor the next ones This parameter is not used if batch 4 s the number of block rows in the input and output block Hankel matrices to be processed s 0 Y the tbyl outputdata sequence matrix Column j of Y contains the t values of the jth output component for consecutive time increments U optional the tbym inputdata sequence matrix Column j of U contains the t values of the jth input component for consecutive time increments Default U tol optional vector of length 2 containing tolerances tol1 tolerance used for estimating the rank of matrices If tol1 0 then the given value of tol1 is used as a lower bound for the reciprocal condition number an mbyn matrix whose estimated condition number is less than 1tol1 is considered to be of full rank If tol1 0 then a default value mnepsilonmachine is used where epsilonmachine is the relative machine precision tol2 tolerance used for determining an estimate of the system order If tol2 0 the estimate is indicated by the index of the last singular value greater than or equal to tol2 Singular values less than tol2 are considered as zero When tol2 0 an internally computed default value tol2 sepsilonmachinesval1 is used where sval1 is the maximal singular value and epsilonmachine the relative machine precision When tol2 0 the estimate is indicated by the index of the singular value that has the largest logarithmic gap to its successor Default tol12 01 printw optional switch for printing the warning messages 1 print warning messages 0 do not print warning messages Default printw 0 ldwork optional the workspace size Default computed by the formulas nr 2 m l s LDWORK t 2s 3 64 nr if CSIZE MAX nrnr t m l 16 2nr then LDWORK MIN LDWORK CSIZE nrnr t m l 16 else LDWORK MIN LDWORK MAX 2nr CSIZE2 sorder 1070 end if LDWORK MAX minimum workspace size needed LDWORK where CSIZE is the cache size in double precision words If LDWORK is specified less than the minimum workspace size needed that minimum value is used instead Ri optional if batch 2 or 3 the 2mlsby2mls upper triangular if alg 2 part of R must contain the upper triangular matrix R computed at the previous call of this mexfile in sequential data processing If conct 1 R has an additional column also set at the previous call If alg 2 R has ml1 additional columns set at the previous call This parameter is not used for batch 1 or batch 4 Ro if batch 3 or 4 the 2mlsby2mls part of R contains the processed upper triangular factor R from the QR factorization of the concatenated blockHankel matrices and further details needed for computing system matrices If batch 1 or 2 then R contains intermediate results needed at the next call of this mexfile If batch 1 or 2 and conct 1 R has an additional column also set before return If batch 1 or 2 and alg 2 R has ml1 additional columns set before return n the order of the system sval optional the singular values used for estimating the order of the system rcnd optional if meth 2 vector of length 2 containing the reciprocal condition numbers of the matrices involved in rank decisions or least squares solutions Description sorder function for computing the order of a discretetime system using SLICOT routine IB01AD For one block data sequences Y U Rnsvalrcnd sordermethalgjobd4conctsYU For f blocks data sequences Yj Uj j 1 f R sordermethalgjobd1conctsY1U1 for j 2 f 1 R sordermethalgjobd2conctsYjUjtolprintwldworkR end Rnsvalrcnd sordermethalgjobd3conctsYfUftol sorder preprocesses the inputoutput data for estimating the matrices of a linear timeinvariant dynam ical system using Cholesky or fast QR factorization and subspace identification techniques MOE SP and N4SID and then estimates the order of a discretetime realization The model structure is xk1 Axk Buk wk k 1 sorder 1071 yk Cxk Duk ek where xk is the ndimensional state vector at time k uk is the mdimensional input vector yk is the ldimensional output vector wk is the ndimensional state disturbance vector ek is the ldimensional output disturbance vector and A B C and D are real matrices of appropriate dimensions Comments 1 The Cholesy or fast QR algorithms can be much faster for large data blocks than QR algorithm but they cannot be used if the correlation matrix HH is not positive definite In such a case the code automatically switches to the QR algorithm if sufficient workspace is provided and batch 4 2 If ldwork is specified but it is less than the minimum workspace size needed that minimum value is used instead See Also findBD sident Authors V Sima Research Institute for Informatics Bucharest Oct 1999 Revisions V Sima May 2000 July 2000 1072 Name specfact spectral factor W0LspecfactABCD Description Given a spectral density matrix phis 1 1 R CsIA B BsIA C with RDD 0 specfact computes W0 and L such that WsW0LsIA1B is a spectral factor of of PHIs ie phisWsWs Examples Adiag12B11C11D1spoly0s W1syslincABCD phigtildW1cW1 phiscleanss2tfphi cleanphishornerphiss check this is 0 ABCDabcdW1 W0LspecfactABCD WsyslincABLW0 Wsss2tfW hornerWssWs See Also gtild sfact fspecg Authors F D 1073 Name ss2des polynomial statespace to descriptor form Sss2desSl Sss2desSlflag Parameters Sl syslin list proper or improper linear system flag character string withD S list Description Given the linear system in statespace representation Sl syslin list with a D matrix which is either polynomial or constant but not zero ss2des returns a descriptor system as listdesABC0E such that SlCsEA1B If the flag withD is given SlistdesABCDE with a D matrix of maximal rank Examples spoly0s G1s1s1s23s3Sltf2ssG Sss2desSl S1ss2desSlwithD Desdes2ssSDes5cleanDes5 Des1des2ssS1 See Also pol2des tf2des des2ss Authors F D 1074 Name ss2ss statespace to statespace conversion feedback injection Sl1rightleftss2ssSlT F G flag Parameters Sl linear system syslin list in statespace form T square nonsingular matrix Sl1 right left linear systems syslin lists in statespace form F real matrix state feedback gain G real matrix output injection gain Description Returns the linear system Sl1A1B1C1D1 where A1invTAT B1invTB C1CT D1D Optional parameters F and G are state feedback and output injection respectively For example Sl1ss2ssSlTF returns Sl1 with and right is a non singular linear system such that Sl1Slright Sl1invright is a factorization of Sl Sl1ss2ssSlT0FG returns Sl1 with and left is a non singular linear system such that Sl1leftSl rightId if F0 When both F and G are given Sl1leftSlright When flag is used and flag1 an output injection as follows is used and then a feedback is performed F must be of size mpn ss2ss 1075 right and left have the following property Sl1 leftsysdiagsyseyeppright When flag is used and flag2 a feedback F must be of size mn is performed and then the above output injection is applied right and left have the following property Sl1 leftsysdiagsysrighteyepp Examples Slssrand225 trzerosSl zeros are invariant Sl1ss2ssSlrand55rand25rand52 trzerosSl1 trzerosrand22Sl1rand22 output injection A GC BGDG C D 0 p1m2n2 sysssrandpmn feedback mn first and then output injection F1randmn Grandnp sys1rightleftss2sssysrandnnF1G2 Sl1 equiv leftsysdiagsysrighteyepp rescleanss2tfsys1 ss2tfleftsysdiagsysrighteyepp output injection then feedback mpn F2randpn FF1F2 sys2rightleftss2sssysrandnnFG1 Sl1 equiv leftsysdiagsyseyeppright rescleanss2tfsys2ss2tfleftsysdiagsyseyeppright when F2 0 sys1 and sys2 are the same F20randpnFF1F2 sys2rightleftss2sssysrandnnFG1 rescleanss2tfsys2ss2tfsys1 See Also projsl feedback 1076 Name ss2tf conversion from statespace to transfer function hss2tfsl DsNUMchiss2tfsl hss2tfslb DsNUMchiss2tfslb hss2tfslrmax DsNUMchiss2tfslrmax Parameters sl linear system syslin list h transfer matrix Description Called with three outputs DsNUMchiss2tfsl returns the numerator polynomial matrix NUM the characteristic polynomial chi and the polynomial part Ds separately ie h NUMchi Ds Method One uses the characteristic polynomial and detAEijdetACij where C is the adju gate matrix of A With rmax or b argument uses a block diagonalization of slA matrix and applies Leverrier algorithm on blocks If given rmax controls the conditionning see bdiag Examples spoly0s h11s1s21ss22 sltf2ssh hcleanss2tfsl DsNUMchiss2tfsl See Also tf2ss syslin nlev glever 1077 Name stility stabilizability test ns nc U Slo stilitySl tol Parameters Sl syslin list linear system ns integer dimension of stabilizable subspace nc integer dimension of controllable subspace nc ns U basis such that its ns resp nc first components span the stabilizable resp controllable sub space Slo a linear system syslin list tol threshold for controllability detection see contr Description Slo UAU UB CU D Ux0 syslin list displays the stabilizable form of Sl Stabilizability means nsnx dim of A matrix UAU 0 UB 0 00 0 where A11B1 dimA11 nc is controllable and A22 dimA22nsnc is stable Stable means real part of eigenvalues negative for a continuous linear system and magnitude of eigenvalues lower than one for a discretetime system as defined by syslin Examples Adiag0923B001SlsyslincAB nsncUstilitySl UAU UB nsncUstilitysyslindAB UAU UB See Also dtility contr stabil ssrand stility 1078 Authors S Steer INRIA 1988 1079 Name stabil stabilization FstabilABalfa KstabilSysalfabeta Parameters A square real matrix nx x nx B real matrix nx x nu alfa beta real or complex vector in conjugate pairs or real number F real matrix nx x nu Sys linear system syslin list m inputs p outputs K linear system p inputs m outputs Description FstabilABalfa returns a gain matrix F such that ABF is stable if pair AB is stabiliz able Assignable poles are set to alfa1alfa2 If AB is not stabilizable a warning is given and assignable poles are set to alfa1alfa2 If alfa is a number all eigen values are set to this alfa default value is alfa1 KstabilSysalfabeta returns K a compensator for Sys such that ABcontrollable eigenvalues are set to alfa and CAobservable eigenvalues are set to beta All assignable closed loop poles which are given by the eigenvalues of AclosedhclSysK are set to alfais and betajs Examples Gain Sysssrand025listst233 ASysABSysBFstabilAB specA 2 controllable modes 2 unstable uncontrollable modes and one stable uncontrollable mode specABF the two controllable modes are set to 1 Compensator Sysssrand325listst233 3 outputs 2 inputs 5 states 2 controllables modes 3 controllable or stabilizable modes KstabilSys23 Compensator for Sys specSysA spechclSysK K Stabilizes what can be stabilized See Also stility contr ppol 1080 Name svplot singularvalue sigmaplot SVMsvplotslw Parameters sl syslin list continuous discrete or sampled system w real vector optional parameter Description computes for the system slABCD the singular values of its transfer function matrix Gjw CjwIAB1D or Gexpjw CexpjwIAB1D or GexpjwT CexpjwTIAB1D evaluated over the frequency range specified by w T is the sampling period Tsldt for sam pled systems sl is a syslin list representing the system ABCD in statespace form sl can be continuous or discrete time or sampled system The ith column of the output matrix SVM contains the singular values of G for the ith frequency value wi SVM svplotsl is equivalent to SVM svplotsllogspace33 continuous SVM svplotsllogspace3pi discrete Examples xlogspace33 ysvplotssrand224x clfplot2d1olnx20logylog10 xgrid12 xtitleSingular values plotRdsec Db Authors FD 1082 Name sysfact system factorization SSeriessysfactSysGainflag Parameters Sys syslin list containing the matrices ABCD Gain real matrix flag string post or pre S syslin list Series syslin list Description If flag equals post sysfact returns in S the linear system with ABCD matrices A BGain B Gain I and Series a minimal realization of the series system SysS If flag equals pre sysfact returns the linear system AGainC Gain C I and Series a minimal realization of the series system SSys Examples Kalman filter Sysssrand324SysDrand32 SsysfactSyslqrSyspost wwminssSysS ss2tfgtildwwwwSysDSysD Kernel Sysssrand234 XdFUkZabinvSys ss2tfSysZ ss2tfSyssysfactSysFpostU See Also lqr lqe Authors FD 1083 Name syssize size of statespace system rnxsyssizeSl Parameters Sl linear system syslin list in statespace r 1 x 2 real vector nx integer Description returns in r the vector number of outputs number of inputs of the linear system Sl nx is the number of states of Sl See Also size 1084 Name tf2des transfer function to descriptor Stf2desG Stf2desGflag Parameters G linear system syslin list with possibly polynomial D matrix flag character string withD S list Description Transfer function to descriptor form SlistdABCDE Exdot AxBu y Cx Du Note that D0 if the optional parameter flagwithD is not given Otherwise a maximal rank D matrix is returned in the fifth entry of the list S Examples spoly0s G1s1s12s3 S1tf2desGdes2tfS1 S2tf2desGwithDdes2tfS2 See Also pol2des tf2ss ss2des des2tf 1085 Name tf2ss transfer to statespace sltf2ssh tol Parameters h rational matrix tol may be the constant rtol or the 2 vector rtol atol rtol tolerance used when evaluating observability atol absolute tolerance used when evaluating observability sl linear system syslin list slABCDs Description transfer to statespace conversion hCseyeA1BDs Examples spoly0s H2ss1s25 Systf2ssH cleanss2tfSys See Also ss2tf tf2des des2tf 1086 Name timeid SISO least square identification H errtimeidnuy Parameters n order of transfer u one of the following u1 a vector of inputs to the system impuls if y is an impulse response step if y is a step response y vector of response H rational function with degree n denominator and degree n1 numerator if y10 or rational function with degree n denominator and numerator if y10 err y impulsHnpt2 where impulsHnpt are the npt first coefficients of impulse response of H Description Identification of discrete time response If y is strictly proper y10 then timeid com putes the least square solution of the linear equation DenyNumu0 with the constraint coeffDenn1 if y10 then the algorithm first computes the proper part solution and then add y1 to the solution Examples zpoly0z h12zz205z5 rep0ldivhnumhden20 impulse response Htimeid2impulsrep Same example with flts and u uzeros120u11 repfltsutf2ssh impulse response Htimeid2urep step response uones120 repfltsutf2ssh step response Htimeid2steprep Htimeid3urep with u as input and too high order required timeid 1087 See Also imrep2ss arl2 armax frep2tf Authors Serge Steer INRIA 1088 Name trzeros transmission zeros and normal rank trtrzerosSl ntdtrktrzerosSl Parameters Sl linear system syslin list nt complex vectors dt real vector rk integer normal rank of Sl Description Called with one output argument trzerosSl returns the transmission zeros of the linear system Sl Sl may have a polynomial but square D matrix Called with 2 output arguments trzeros returns the transmission zeros of the linear system Sl as trntdt Note that some components of dt may be zeros Called with 3 output arguments rk is the normal rank of Sl Transfer matrices are converted to statespace If Sl is a square polynomial matrix trzeros returns the roots of its determinant For usual statespace system trzeros uses the statespace algorithm of EmamiNaeni and Van Dooren If D is invertible the transmission zeros are the eigenvalues of the A matrix of the inverse system A BinvDC If CB is invertible the transmission zeros are the eigenvalues of NAM where MN is a full rank factorization of eyeABinvCBC For systems with a polynomial D matrix zeros are calculated as the roots of the determinant of the system matrix Caution the computed zeros are not always reliable in particular in case of repeated zeros Examples W1ssrand225trzerosW1 call trzeros rootsdetsystmatW1 roots of detsystem matrix spoly0sW1s11s2W2s3WWntdtrktrzerosW2 trzeros 1089 Stsystmattf2ssW2QZQdZdnumbepsnumbetakroneckSt St1QStZrowfQd1Qd21Qd1Qd2Qd3 colfZd1Zd21Zd1Zd2Zd3 rootsSt1rowfcolf ntdt By Kronecker form See Also gspec kroneck 1090 Name uiobserver unknown input observer UIobsJNuiobserverSysrejectC1D1 UIobsJNuiobserverSysrejectC1D1flagalfabeta Parameters Sys syslin list containing the matrices ABC2D2 reject integer vector indices of inputs of Sys which are unknown C1 real matrix D1 real matrix C1 and D1 have the same number of rows flag string ge or st default or pp alfa real or complex vector loc of closed loop poles beta real or complex vector loc of closed loop poles Description Unknown input observer Sys wu y is a ABC2D2 syslin linear system with two inputs w and u w being the unknown input The matrices B and D2 of Sys are implicitly partitioned as BB1B2 and D2D21D22 with B1Breject and D21D2reject where reject indices of unknown inputs The matrices C1 and D1 define z C1 x D1 wu the tobeestimated output The matrix D1 is implicitly partitioned as D1D11D12 with D11Dreject The data Sys rejectC1 D1 define a 2input 2output system xdot A x B1 w B2 u z C1 x D11 w D12 u y C2 x D21 w D22 u An observer uy zhat is looked for the output z flagge no stability constraints flagst stable observer default flagpp observer with pole placement alfabeta desired location of closed loop poles default 1 2 Jyoutput to x state injection Nyoutput to zestimated output injection UIobs linear system uy zhat such that The transfer function wu z equals the com posed transfer function 0I UIobs Sys wu uy zhat ie transfer function of system ABC1D1 equals transfer function UIobs0I Sys uiobserver 1091 Stability resp pole placement requires detectability resp observability of AC2 Examples Adiag337448 Beye33zeros33 C001234000001 D123000 randseed0wss2sssyslincABCDrand66 ABCDabcdw BBmatrix11863DDmatrix1623 reject13 SyssyslincABCD N123C1N1CD1N1D nwlengthrejectnusizeSysB2nw nysizeSysC1nzsizeC11 UIobsJNuiobserverSysrejectC1D1 WzerosnunweyenunuSysUIobsWUIobsW wu zUIobs0ISyswu cleanss2tfUIobsW wutozsyslincABC1D1cleanss2tfwutoz cleanss2tfwutozss2tfUIobsW1d7 2nd example nx2ny3nwu2Sysssrandnynwunx C1rand1nxD101 UIobsuiobserverSys1C1D1 See Also cainv ddp abinv Authors FD 1092 Name unobs unobservable subspace nUunobsACtol Parameters A C real matrices tol tolerance used when evaluating ranks QR factorizations n dimension of unobservable subspace U orthogonal change of basis which puts AB in canonical form Description nUunobsACtol gives the unobservable form of an AC pair The n first columns of U make a basis for the unobservable subspace The 21 block made of last nxn rows and n first columns of UAU is zero and and the n first columns of CU are zero Examples Adiag123C100 unobsAC See Also contr contrss canon contmat spantwo dtility 1093 Name zeropen zero pencil ZUzeropenSl Parameters Sl a linear system syslin list in statespace form ABCD Z matrix pencil ZsEA U square orthogonal matrix Description Z sE F is the zero pencil of the linear system Sl with matrices ABCD Utility function With U row compression of BD ie UBD0 one has UsIA B Z 0 C D The zeros of Z are the zeros of Sl See Also systmat kroneck Parte X Estructuras de Datos 1095 Name cell cria um cell célula de matrizes vazias ccell ccellm1 ccellm1 m2 ccellm1 m2 mn ccellx Parâmetros x vetor contendo as dimensões do cell a ser criado m1 m2 dimensões do cell a ser criado Descrição retorna um cell de matrizes vazias cell retorna um cell 00 de matrizes vazias cellm1 retorna um cell m1m1 de matrizes vazias cellm1m2 retorna um cell m1m2 de matrizes vazias cellm1m2mn retorna um cell m1m2mn de matrizes vazias cellx retorna um cell de matrizes vazias com a primeira dimensão sendo x1 a segunda sendo x2 Observações cellx não possui o mesmo tamanho que x cell é equivalente a cell0 Se A for um cell você pode acessar os conteúdos de um elemento de A utilizando Am1 m2 mnentries A expressão A11 zeros22 não é válida a sintaxe correta é A11entries zeros22 Se A é um cell você pode obter suas dimensões através de Adims Exemplos acell3 bcell31 ccell234 cell 1096 atribuição em entradas do cell bcell31 atribuindo o primeiro elemento de b utilizando o campo entries b1entries13 atribuindo o segundo elemento de b utilizando o campo entries b2entriesScilab atribuindo o terceiro elemento de b utilizando o campo entries b3entriespoly13s atribuição de subcells Xcell32 X1b extraindo um subcell o resultado é um cell b1 b12 extraindo o valor de um subcell o resultado é um array b1entries dimensões de b bdims Ver Também eye ones zeros 1097 Name definedfields retorna o índice dos campos definidos de uma lista kdefinedfieldsl Parâmetros l uma lista tlist ou mlist k um vetor de índices Descrição Se l é do tipo list tlist mlist kdefinedfieldsl retorna em k os índices dos campos definidos da lista Esta função é útil porque a indexação de campos indefinidos acarreta erros Exemplos llist1l35 kdefinedfieldsl ttlistxt54 definedfieldst mmlistmabmbsdfgfgd definedfieldsm Ver Também list tlist mlist insertion extraction 1098 Name getfield extração de campos de listas xgetfieldil Parâmetros x matriz de qualquer tipo possível l lista tlist ou mlist i índice de campo ver extraction para mais detalhes Descrição Esta função é equivalente à sintaxe xli para extração de campos com a única diferença de que também se aplica a objetos mlist Exemplos llist1qwerws abgetfield3 2l ahypermat222rand123 hipermatrizes são codificadas usandose mlists a1 a entrada a111 getfield1a o primeiro campo do mlist Ver Também extraction 1099 Name hypermat inicializa matrizes ndimensionais Mhypermatdims v Parâmetros dims vetor de dimensões da hipermatriz v vetor de entradas da hipermatriz valor padrão zerosproddims1 Descrição Incializa uma hipermatriz cujas dimensões são dadas pelo vetor dims e as entradas são dadas pelo argumento opcional v A estrutura de dados de M contém o vetor de dimensões da matriz Mdims e o vetor de entradas Mentries tais que os índices subescritos mais à esquerda variam primeiro M11Mn11M1n2Mn1n2 Exemplos Mhypermat2 3 2 2124 See Also hypermatrices zeros ones grand matrix 1100 Name hypermatrices objeto do Scilab matrizes ndimensionais Descrição O tipo hipermatriz hypermatrix permite manipular arrays multidimensionais Hipermatrizes podem ser definidas por uma extensão das matrizes 2D como segue a1 23 4a2rand22 ou usando a função hypermat diretamente As entradas podem ser números reais ou complexos polinômios razões de polinômios strings ou valores booleanos Hipermatrizes são mlists mlisthmdimsentriesszv onde sz é o vetor linha de dimensões e v é o vetor coluna de entradas as primeiras dimensões são armazenadas primeiro NOTAS O número de dimensões de hipermatrizes com tamanhos mais à direita iguais a 1 é auto maticamente reduzido Uma hipermatriz com apenas duas dimensões é automaticamente trocada por uma matriz regular tipo 1 Exemplos a111121 2 a1 23 4a2rand22 a11 sizea a1 redução de dimensionalidade typea1 a a Ver Também hypermat zeros ones grand matrix 1101 Name iscell verifica se um array é um cell célula bool iscellx Parâmetros x variável Scilab bool um booleano Descrição iscellx retorna t verdadeiro se x é um cell e f falso em caso contrário Exemplos iscell1 iscellcell c cell12 c1entriesScilab c2entriesdatenum iscellc Ver Também cell isstruct Autor VC 1102 Name iscellstr verifica se uma variável é um cell array de strings bool iscellstrx Parâmetros x variável Scilab bool um booleano Descrição iscellstrx retorna verdadeiro se x é um cell array de strings ou um cell array vazio e falso em caso contrário Exemplos iscellstr1 iscellstrcell iscellstrcell3 strcell cell31 strcell1entriesScilab strcell2entriesiscellstr strcell3entrieshelp iscellstrstrcell Ver Também cell iscell isstruct Autor VC 1103 Name isstruct checa se uma variável é um struct array estrutura bool isstructx Parâmetros x variável Scilab bool um booleano Descrição isstructx retorna t verdadeiro se x é um struct array e f em caso contrário Exemplos isstruct1 isstructcell isstructstructnameScilab version getversion infonameScilab infofunctionisstruct infomodulehelp isstructinfo Ver Também struct iscell Autor VC 1104 Name list objeto do Scilab e definição de lists listas lista1an Descrição Cria um list com elementos ais que são elementos Scilab arbitrários matrix list O tipo de objetos list é 15 list cria o list vazio 0 elementos Operações em Listas extração xyzLv onde v é um vetor de índices xyzL extrai todos os elementos inserção no índice i Lia note que não é errado usar Lia com i 1 sizeL mas algumas entradas de lista estão então indefinidas e sua extração levanta um erro anexar elemento no fim da lista L1e anexar elementos no início da lista L0e note que após esta operação e está no índice 1 os elementos iniciais foram movidos para a direita deleção Linull remove o iésimo elemento da lista L concatenação de duas listas L3 lstcatL1L2 número de elementos de uma lista você pode usar tanto nbelm sizeL ou nbelm lengthL iterações com uma lista é possível usar uma lista L com um laço loop for for eLend é um laço com lengthL iterações a variável de laço e sendo igual a Li na iésima iteração Observações O Scilab também possui outros tipos de listas o tipo tlist lista com tipo e o tipo mlist que são úteis para definir um novo tipo de dado com o operador overloading facilities hypermatrices hipermatrizes que são arrays multidimensionais no Scilab são na verdade mlist struct do Matlab também estão disponíveis Exemplos l list1a b l0 foo l1 olá l2 toto l3 rand12 l3 null lbis listgewurtz caipirina debug list 1105 lter lstcatllbis sizelter sizelbis sizel deve ser zero Ver Também null lstcat tlist insertion extraction size length 1106 Name lsslist definição de função linear de espaço de estados do Scilab lsslist lsslista1an Descrição lsslista1an é um atalho para tlistlssABCX0dt a1an Cria um tlist com lssABCX0dt como primeiras entradas e os ais como próximas entradas se tiver algum Não é feita verificação de tipo ou tamanho nos ais Ver Também tlist syslin 1107 Name lstcat concatenação de listas lclstcatl1ln Parâmetros li lista ou qualquer outro tipo de variável lc uma lista Descrição lclstcatl1ln concatena os componentes das li listas em uma única lista Se os li são outros tipos de variáveis eles simplesmente são adicionados à lista resultante Exemplos lstcatlist12333listfoos lstcat123 Ver Também list 1108 Name mlist objeto Scilab definição de listas com tipos orientadas matricialmente mlisttypa1an Parâmetros typ vector of character strings ai any Scilab object matrix liststring Descrição Objetos mlist são bastante semelhantes a objetos tlist objects A única diferença concerne às sintaxes de extração e inserção extraction e insertion se M é uma mlist para qualquer índice i que não é um campo de nome Mi não é mais o iésimo campo da lista A semântica da sintaxe de extração e inserção deve ser dada por uma função de sobrecarga over loading A função de overloading para sintaxe de extração bai1in tem a seguinte seqüência de chamamento btipodeaei1ina e a sintaxe x1xmai1in tem a seguinte seqüência de chamamento x1xmtypedeaei1ina A função de overloading associada à sintaxe de inserção ai1inb tem a seguinte seqüência de chamamento atypedebitypedeai1inba Os campos de um mlist devem então ser designados por seus nomes Eles também podem ser ma nipulados usandose as funções getfield e setfield Exemplos MmlistVnamevalueabc d1 2 3 4 Definindo exibição function VpMdispMnamestringMvalueendfunction Definindo operação de extração function rVevarargin Mvarargin rmlistVnamevalueMnamevarargin11Mvaluevarargin11 endfunction M2 a segunda entrada do vetor M Mvalue Definindo operações de inserção function MViVvarargin Mvarargin Nvarargin1 Mvaluevarargin12Nvalue Mnamevarargin12Nname mlist 1109 endfunction M11M22 function MsiVvarargin inserção de uma matriz regular em uma matriz V Mvarargin Nvarargin1 Mvaluevarargin12N Mnamevarargin12emptystrN endfunction M1144 caso de tlists MtlistVnamevalueabc d1 2 3 4 M2 M2astring1 23 4 Mname Ver Também tlist list overloading getfield setfield 1110 Name rlist definição de função racional do Scilab rlist rlista1an Descrição rlista1an é um atalho para tlistrnumdendt a1an Cria um tlist com rnumdendt como primeira entrada e os ais como próximas entradas se tiver algum Nenhuma verificação de tipo ou tamanho é feita nos ais Ver Também tlist syslin 1111 Name setfield inserção de campos de listas setfieldixl Parâmetros x matriz de qualquer tipo l lista tlist ou mlist i índice de campo ver insertion para mais detalhes Descrição Esta função é equivalente à sintaxe lix spara inserção de campos com a única diferença de que também se aplica a objetos mlist Exemplos llist1qwerws l1Modificado l0Adicionado l6mais umadicionado ahypermat222rand123 hipermatrizes são codificadas usandose mlists setfield318aa ajusta o valor de campo para 18 Ver Também insertion 1112 Name struct criando um struct estrutura ststructfield1value1field2value2 Parâmetros field1 field2 strings representam os nomes dos campos value1 value2 todos os tipos de dados double char int representam os valores dos campos Descrição Esta função retorna uma estrutura com campos de nomes fields1 field2 e valores corre spondentes value1 value2 Exemplos criando um dado struct datestructdia25mes DEZano2006 mudando o mes datemesAGO mudando o ano dateano1973 mudando o dia datedia19 adicionando um novo campo datesemana32 Ver Também cell 1113 Name tlist objeto do Scilab e definição de listas com tipos typed lists tlisttypa1an Parâmetros typ string ou vetor de strings ai qualquer objeto Scilab matrix liststring Descrição Cria um typedlist com elementos ais O argumento typ especifica o tipo da lista Tais typedlist permitem ao usuário definir novas operações trabalhando nestes objetos através de funções do Scilab A única diferença entre um typedlist e um list lista é o valor do tipo 16 ao invés de 15 typ1 espeifica o tipo de lista string usado para definir operações softcoded Se especificado typi pode fornecer o nome formal do i1 ésimo elemento Operações padrões em list operam de modo semelhante para typedlist Extração xyzlv onde v é o vetor de índices xyzl extrai todos os ele mentos Inserção lia Deleção linull remove o iésimo elemento do tlist l Exibição Além disso se typ2n1 forem especificados o usuário pode apontar elementos por seus nomes Abaixo fornecemos exemplos de onde tlists são usados Sistemas lineares são representados por typedlist específicos ex um sistema linear ABCD é representado pelo tlist SystlistlssABCDX0dtABCDx0c e esta lista específica pode ser criada pela função syslin Sys2 SysA ou SysA é a estadomatriz e Sysdt ou Sysdt é o domínio de tempo Uma matriz de razões de polinômios H é representada por um typedlist HtlistrnumdendtNumDen onde Num e Den são duas matrizes de polinômios e um sistema linear ex de tempo contínuo com matriz de transferência H possivelmente criada por syslincH H2 Hnum ou Hnum é o numerador da matriz de transferência Ver Também null percent syslin list 1114 Name fieldnames returns the tlist mlist or struct field names ffieldnamesx Parameters x a tlist or an mlist or a struct f column vector of strings Description This function returns the tlist mlist cell or struct field names Examples clear t ta1 tb2 fieldnamest fieldnames1s fieldnamestf2ss1s See Also extraction getfield tlist mlist struct 1115 Name isfield Checks if the given fieldname exists in the structure bool isfieldsfieldname Parameters s A struct array fieldname A matrix of strings bool A matrix of boolean Description This function returns true if the specified structure s includes the field field regardless of the corresponding value Examples s structfield1123field2456field4789 Single Fieldname Syntax isfield s field1 Multiple Fieldname Syntax isfield s field1 field2 field3 field4 See Also struct getfield definedfields Parte XI Shell 1117 Name clc Clear Command Window clcnblines Parameters nblines a double value Description clc clears all input and output from the Command Window After using clc you cannot use the scroll bar to see the history of functions but still can use the up arrow to recall statements from the command history clcnblines clears nblines above cursor current line and move cursor up to this line Note that clcnblines cannot be used under UnixLinux platforms when Scilab used in no window mode See Also tohome Authors VC 1118 Name lines rows and columns used for display linesnl nc ncllines Parameters nl an integer the number of lines for vertical paging control If 0 no vertical paging control is done nc an integer the number of column of output Used for formatting output ncl a 1x2 vector ncnl Description lines handles Scilab display paging lines returns the vector columns rows currently used by Scilab for displaying the results linesnl sets the number of displayed lines before user is asked for more to nl lines0 disables vertical paging linesnlnc changes also the size of the output to nc columns When Scilab is launched without nw option the lines parameters are automatically set according to the output window size these parameters are also automatically modified when the window is resized See Also disp print 1119 Name prompt GetSet current prompt currentprompt prompt currentpromptpauselevel prompt promptuserprompt Parameters currentprompt String current prompt returned as a character string pauselevel integer current pause level userprompt String prompt to display for next user input Then current prompt will be used again Description currentprompt prompt gets the current prompt promptuserprompt sets the prompt See Also pause input Authors AC 1120 Name tohome Move the cursor to the upper left corner of the Command Window tohome Description tohome moves the cursor to the upperleft corner of the Command Window and clears the screen You can use the scroll bar to see the history of previous functions Note that tohome cannot be used under Windows platforms when Scilab used in no window mode See Also clc Authors VC Parte XII Console 1122 Name console Keyboard Shortcuts in the Console Window Description UP or CtrlP recall previous line DOWN or CtrlN recall next line F1 call help F2 clear console F12 open console box only on Windows Ctrlspace or TAB completion scilab displays a list of all names that start with somes characters Ctrl A or HOME move to beginning of current line Ctrl B or LEFT moves the cursor one character to the left Ctrl C interrupts Scilab if nothing selected in the console else text selected is sent to clipboard Ctrl D or DELETE deletes the current character Ctrl E or END moves the cursor to the end of command line Ctrl F or RIGHT moves the cursor one character to the right Ctrl H or BACKSPACE deletes the previous character Ctrl K kills command line from cursor to the end Ctrl S select all Ctrl U delete the whole command line Ctrl V do a paste from clipboard Ctrl W delete the last word of the command line Ctrl X Interrupt Scilab Ctrl LEFT move left one word Ctrl RIGHT move right one word Shift HOME select from cursor to beginning of statement Shift END select from cursor to end of statement Doubleclick select current word Parte XIII Complementação 1124 Name completion returns words that start with the text you pass as parameter r completionbeginningofaword r completionbeginningofaworddictionary functions commands variables macros graphicproperties files completionbeginningofaword functions commands variables macros graphicproperties completionbeginningofaword functions commands variables macros completionbeginningofaword functions commands variables completionbeginningofaword functions commands completionbeginningofaword Parameters r a string matrix beginningofaword a string dictionary a string functions commands variables macros graphicproperties files functions commands variables macros graphicproperties files a string matrix Description returns words that start with the text you pass as parameter functions a string matrix of functions name C gateways see what commands a string matrix of command words reserved see what variables a string matrix of variables names see who macros a string matrix of macros names see who graphicproperties a string matrix files a string matrix Examples r completionw r completionwfunctions r completionwcommands r completionwvariables r completionwmacros r completionwgraphicproperties r completionwfiles functionscommandsvariablesmacrosgraphicpropertiesfiles completionw functionscommandsvariablesmacrosgraphicproperties completionw functionscommandsvariablesmacros completionw functionscommandsvariables completionw functionscommands completionw completion 1125 See Also getscilabkeywords who what libraryinfo librarieslist Parte XIV Gerenciador de histórico 1127 Name addhistory add lines to current history addhistorystring addhistorystringmatrix Parameters string a string stringmatrix a string matrix Description add lines to current history Examples addhistoryhello addhistoryhelloScilab Authors AC 1128 Name displayhistory displays current scilab history displayhistory Description displays current scilab history See Also gethistory Authors AC 1129 Name gethistory returns current scilab history in a string matrix matstrgethistory linegethistoryN Parameters matstr a string matrix N Nth line in scilabs history line a string Description returns current scilab history in a string matrix See Also savehistory loadhistory resethistory Authors AC 1130 Name gethistoryfile get filename used for scilabs history filename gethistoryfile Parameters filename file name used for history Description get filename for scilabs history Examples gethistoryfile Authors AC 1131 Name historymanager enable or disable history manager state1historymanagerstate2 state1historymanager Parameters state1 returns history manager state on or off state2 on or off set history managers state Description enable or disable history manager Examples displayhistory backupstatehistorymanager historymanageroff displayhistory historymanageron loadhistory displayhistory historymanagerbackupstate Authors AC 1132 Name historysize get number of lines in history nbhistorysize Parameters nb number of lines in history Description get number of lines in history Examples historysize Authors AC 1133 Name loadhistory load a history file loadhistory loadhistoryf Parameters f file pathname Description load a history file by default history filename is SCIHOMEhistoryscilab Examples loadhistorySCIsessionscilab See Also savehistory resethistory gethistory Authors AC 1134 Name removelinehistory remove the Nth line in history removelinehistoryN Parameters N a line number Description remove the Nth line in history Examples displayhistory removelinehistoryhistorysize2 displayhistory Authors AC 1135 Name resethistory Deletes all entries in the scilab history resethistory Description Deletes all entries in the current scilab history See Also savehistory loadhistory Authors AC 1136 Name saveafterncommands Save the history file after n statements are added to the file saveafterncommandsn v saveafterncommands Parameters n a integer n statements v current value Description Save the history file after n statements are added to the file For example when you select the option and set n to 5 after every 5 statements are added the history file is automatically saved Use this option if you dont want to risk losing entries to the saved history because of an abnormal termination such as a power failure saveafterncommands returns current value 0 is default value Examples saveafterncommands3 Authors AC 1137 Name saveconsecutivecommands Save consecutive duplicate commands saveconsecutivecommandsbooleanin booleanout saveconsecutivecommands Parameters booleanin a boolean t or f booleanout current value Description Save consecutive duplicate commands saveconsecutivecommandst if you want consecutive executions of the same statement to be saved to the history file Examples saveconsecutivecommands saveconsecutivecommandst 1 1 2 saveconsecutivecommandsf 1 1 2 Authors AC 1138 Name savehistory save the current history in a file savehistory savehistoryf Parameters f file pathname Description save the current history in a file by default history filename is SCIHOMEhistoryscilab Examples savehistorySCIsessionscilab See Also loadhistory resethistory gethistory Authors AC 1139 Name sethistoryfile set filename for scilab history sethistoryfilefilename sethistoryfile Parameters filename filename for history Description set filename for scilab history sethistoryfile without parameters will use the default filename SCIHOMEhistoryscilab Examples gethistoryfile sethistoryfilegethistoryfile Authors AC Parte XV IGU 1141 Índice 1 Tree 1142 uiConcatTree 1143 uiCreateNode 1144 uiCreateTree 1145 uiDeleteNode 1146 uiDisplayTree 1148 uiDumpTree 1149 uiEqualsTree 1150 uiFindNode 1151 uiGetChildrenNode 1153 uiGetNodePosition 1154 uiGetParentNode 1155 uiInsertNode 1156 Capítulo 1 Tree Tree 1143 Name uiConcatTree Concatenation of Trees concatenatedTree uiConcatTreetree1 tree2 Input parameters tree1 tree2 are of type Tree Output parameters concatenatedTree a Tree which is the concatenation of tree1 and tree2 Description Concatenation will return a tree which is the concatenation of the first tree with the second one The concatenation will took place at the parent level of the first tree Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf21 uiCreateNodeleaf 21 iconLeaf21 callbackLeaf21 leaf22 uiCreateNodeleaf 22 iconLeaf22 callbackLeaf22 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 root uiCreateNodeRoot iconRoot callbackRoot myTree1 uiCreateTreenode1 leaf11 leaf12 myTree2 uiCreateTreenode2 leaf21 leaf22 concatTree uiConcatTreemyTree1 myTree2 uiDisplayTreeconcatTree See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiEquals Tree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1144 Name uiCreateNode Creation of node for Scilab Tree myNode uiCreateNodelabel icon callback Input parameters label a string matrix which gives the label of the nodes icon optional a string matrix which gives the icon image of the nodes callback optional a string matrix which gives the callback instruction of the nodes Output parameters myNode a node of type Tree Description Creates a nodea node or a leaf of type Tree Examples leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot See Also uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiConcatTree uiEquals Tree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1145 Name uiCreateTree Creation of a Tree myTree uiCreateTreemyParentTree mySubTree1 mySubTree2mySubTreeN Input parameters myParentTree a Tree mySubTrees one or many trees Output parameters myTree a Tree Description Creates a Tree in which myParentTree will have childrenmySubTree1 mySubTree2mySubTreeN Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 uiDisplayTreetreeRoot See Also uiCreateNode uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiConcatTree uiE qualsTree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1146 Name uiDeleteNode Deletion in a Tree delTree uiDeleteNodetree node delTree uiDeleteNodetree position Input parameters tree Tree were we do the deletion node node we want to delete position a string which is the position of the node we want to delete Output parameters delTree a Tree without the deleted node Description Deletion of a node subTree from a tree If we have 3 nodes called Node1 Node2 and Node3 each one at position 11 12 and 13 Deletion of node at position 12 Node2 will pull up the Node 3 to position 12 Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Deletion of node2 treeDel uiDeleteNodetreeRoot node2 uiDisplayTreetreeDel Deletion of node at position 32 treeDel uiDeleteNodetreeRoot 32 uiDisplayTreetreeDel Tree 1147 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiConcatTree uiEquals Tree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1148 Name uiDisplayTree Printing a Tree in GUI mode uiDisplayTreetree Input parameters tree a Tree Description Display a tree into the a graphic window Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 leaf12 uiCreateNodeleaf 12 leaf31 uiCreateNodeleaf 31 leaf32 uiCreateNodeleaf 32 node1 uiCreateNodeNode 1 node2 uiCreateNodeNode 2 node3 uiCreateNodeNode 3 root uiCreateNodeRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTree root treeNode1 node2 treeNode3 uiDisplayTreetreeRoot See Also uiCreateNode uiCreateTree uiDumpTree uiInsertNode uiDeleteNode uiConcatTree uiEquals Tree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1149 Name uiDumpTree Printing a Tree in the console text mode uiDumpTreetreeb Input parameters tree a Tree boptional display features of each node of the tree By default b is F Description Display a tree into the consoletext mode Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11leaf12 treeNode3 uiCreateTreenode3 leaf31leaf32 treeRoot uiCreateTreeroot node1node2node3 uiDumpTreetreeRoot See Also uiCreateNode uiCreateTree uiDisplayTree uiInsertNode uiDeleteNode uiConcatTree uiE qualsTree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1150 Name uiEqualsTree Comparing two trees isEqual uiEqualsTreetree1 tree2 Input parameters tree1 tree2 are of type Tree Output parameters isEqual a Boolean which indicate if those trees are equal or not Description Compare two trees structures Examples Creation of trees root uiCreateNodeRoot pathrootImagejpg rootCallback node1 uiCreateNodeNode 1 default node1Callback node2 uiCreateNodeNode 2 default node2Callback myTree1 uiCreateTreeroot node1 node2 myTree2 uiCreateTreeroot node1 node2 Compare myTree1 with myTree2 isEqual uiEqualsTreemyTree1 myTree2 will return isEqual T See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1151 Name uiFindNode Find node in Tree nodeList uiFindNodetree node nodeList uiFindNodetree position nodeList uiFindNodetree property value Input parameters tree Tree in which we find the node node the node we find position a string which is the position of the node we find in the tree property a string which finds nodes by properties label icon or callback value a string which is the value of the property Output parameters nodeList a list of matching nodes Description Finds nodes in a tree Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Creation of a node myNode uiCreateNodeNode 2 iconNode2 callbackNode2 Tree 1152 Find if treeRoot contains myNode result uiFindNodetreeRoot myNode will return result listnode1 Find node at position 11 result uiFindNodetreeRoot 31 will return result listleaf31 Find node where text equals Node 2 result uiFindNodetreeRoot label Node 2 will return result listnode2 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiEqualsTree uiGetParentNode uiGetChildrenNode uiGetNodePosition Tree 1153 Name uiGetChildrenNode Get Children of a node children uiGetChildrenNodetree node children uiGetChildrenNodetree position Input parameters tree Tree in which we look for children nodes node the node we look for children position a string which is the position of the node we look for children Output parameters children a list of children nodes Description Finds the children of a specific node Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Search children nodes of node node1 children uiGetChildrenNodetreeRoot node1 will return children listleaf11 leaf12 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiEqualsTree uiFindNode uiGetParentNode uiGetNodePosition Tree 1154 Name uiGetNodePosition Get the positions of a node position uiGetNodePositiontree node Input parameters tree Tree in which we look for positions of a node node the node we look for positions Output parameters position a matrix of string which contains node positions Description Get the position of a given node Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Get the position of node node1 position uiGetNodePositiontreeRoot node1 will return position 1 Get the position of leaf leaf31 position uiGetNodePositiontreeRoot leaf31 will return position 31 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiEqualsTree uiFindNode uiGetParentNode uiGetChildrenNode Tree 1155 Name uiGetParentNode Get Parent of a node parent uiGetParentNodetree node parent uiGetParentNodetree position Input parameters tree Tree in which we look for parent of a node node the node we look for parent position a string which is the position of the node we look for parent Output parameters parent the parent node Description Finds the parent of a specific node Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Search parent node of node1 parentNode uiGetParentNodetreeRoot node1 will return parentNode root Search parent node of leaf31 parentNode uiGetParentNodetreeRoot leaf31 will return parentNode node3 See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiInsertNode uiDeleteNode uiCon catTree uiEqualsTree uiFindNode uiGetChildrenNode uiGetNodePosition Tree 1156 Name uiInsertNode Insertion in a Tree insertTree uiInsertNodetree position node insertTree uiInsertNodetree parentNode node Input parameters tree Tree were we do the insertion position a string which is the position where we want to insert the node parentNode which is the parent node into we want to insert the node node node we want to insert Output parameters insertTree a Tree with the node inserted Description Insertion of a node subTree into a tree If we have 2 nodes called Node1 and Node2 each one at position 11 and 12 Insertion of a new node Node3 at position 12 will move the Node2 to position 13 Examples We should create nodessubTrees before creating trees leaf11 uiCreateNodeleaf 11 iconLeaf11 callbackLeaf11 leaf12 uiCreateNodeleaf 12 iconLeaf12 callbackLeaf12 leaf31 uiCreateNodeleaf 31 iconLeaf31 callbackLeaf31 leaf32 uiCreateNodeleaf 32 iconLeaf32 callbackLeaf32 node1 uiCreateNodeNode 1 iconNode1 callbackNode1 node2 uiCreateNodeNode 2 iconNode2 callbackNode2 node3 uiCreateNodeNode 3 iconNode3 callbackNode3 root uiCreateNodeRoot iconRoot callbackRoot treeNode1 uiCreateTreenode1 leaf11 leaf12 treeNode3 uiCreateTreenode3 leaf31 leaf32 treeRoot uiCreateTreeroot treeNode1 node2 treeNode3 Creation of a new nodes to insert leaf13 uiCreateNodeleaf 13 iconLeaf13 callbackLeaf13 testNode uiCreateNodetest icontest callbacktest Insertion of leaf13 in node2 treeInsert uiInsertNodetreeRoot node2 leaf13 uiDisplayTreetreeInsert Tree 1157 Insertion of testNode at position 11 treeInsert uiInsertNodetreeRoot 11 testNode uiDisplayTreetreeInsert See Also uiCreateNode uiCreateTree uiDisplayTree uiDumpTree uiDeleteNode uiConcatTree uiE qualsTree uiFindNode uiGetParentNode uiGetChildrenNode uiGetNodePosition 1158 Name about show about scilab dialog box about Description show about scilab dialog box Examples about Authors Allan CORNET 1159 Name addmenu interactive button or menu definition addmenubutton submenus action addmenugwinbutton submenus action Parameters button a character string The button name An can be placed before the character in the name to be used for keyboard shortcut this character will be underlined on the GUI Under MacOSX a sub menu with the same name is automatically added no button can be added to the menu bar submenus a vector of character string The submenus items names action a list with 2 elements actionlistflagprocname flag an integer default value is 0 flag0 the action is defined by a scilab instruction flag1 the action is defined by a C or Fortran procedure flag2 the action is defined by a scilab function procname a character string which gives the name of scilab variable containing the instruction or the name of procedure to call gwin integer The number of graphic window where the button is required to be installed Description The function allows the user to add new buttons or menus in the main window or graphics windows command panels If action argument is not given the action associated with a button must be defined by a scilab instruction given by the character string variable which name is button for a main window command buttongwin for a graphic window command If action argument is set to 0 procname should be the name of a Scilab string vector Actions associated with the kth submenu must be defined by scilab instructions stored in the kth element of the character string variable If action argument is set to 1 procname designes a C or Fortran procedure this procedure may be interfaced in Fortran subroutine defaultfbutnf or dynamically linked with scilab using the link function The C calling sequence is char buttonname int gwinint k addmenu 1160 If action argument is set to 2 procname designes a Scilab function This function calling se quence should be procnamekfor a main window command procnamekgwinfor a graphic window command or a main window command Examples if getscilabmode STD then addmenufoo foo disphello addmenuHelloFranckPeter Hello disphello Franckdisphello Peter addmenuByelist0FrenchBye FrenchBye dispAu revoir else mprintfThis example requires to use scilab with GUI mode end addmenu0HelloFranckPeter Hello0 disphello Franckdisphello Peter C defined Callback creating Callback code code include machineh include sciprinth void foochar name int win int entry if win1 sciprintmenu si in Scilab window selected name entry1 else sciprintmenu si in window i selected name entry1 win creating fooc file currentdir pwd chdirTMPDIR mputlcode TMPDIRfooc creating Makefile ilibforlinkfoofoocc execloadersce chdircurrentdir add menu addmenu0fooabclist1foo See Also setmenu unsetmenu delmenu 1161 Name clipboard Copy and paste strings to and from the system clipboard clipboardcopydata strclipboardpaste clipboarddopaste clipboarddocopy clipboarddoempty clipboardwinnumEMF clipboardwinnumDIB Parameters data Scilab variable or data to set as the clipboard contents str The clipboard contents returned as a Scilab character string winnum Number of the graphic window to set as the clipboard contents Description clipboardcopydata sets the clipboard contents to data If data is not a character array the clipboard uses sci2exp to convert it to a string str clipboardpaste returns the current contents of the clipboard as a string or as an empty string if the current clipboard contents cannot be converted to a string clipboarddopaste clipboarddocopy clipboarddoempty performs a paste copy or empty clipboard clipboardwinnumEMF copy a graphic window identified by his windows number in the clipboard to EMF format clipboardwinnumDIB copy a graphic window identified by his windows number in the clipboard to DIB format Note that clipboard function works only when Scilab used in window mode Authors AC 1162 Name close close a figure Parameters h integer Handle of the window to close Description This routine close a tksci figure toplevel window If a handle is given the figure corresponding to this handle is closed Otherwise the current active figure is closed Examples hfigure creates figure number 1 uicontrol h styletext stringscilab is great position50 70 100 100 fontsize15 put a clever text in figure 1 figure create figure 2 uicontrol styletext stringReally great position50 70 100 100 fontsize15 put a text in figure 2 close close the current graphic window ie fig 2 closeh close figure 1 See Also figure gcf Authors Bertrand Guiheneuf 1163 Name delmenu interactive button or menu deletion delmenubutton delmenugwinbutton Parameters button a character string The button name On Windows operating systems not Xwindow an should be placed before the character in the name used for keyboard shortcut this character is underlined on the GUI gwin integer The number of graphic window where the button is required to be installed Description The function allows the user to delete buttons or menus create by addmenu in the main or graphics windows command panels Predefined buttons on Scilab graphic windows can also be deleted If possible it is better to delete first the latest created button for a given window to avoid gaps in command panels Examples addmenufoo delmenufoo See Also setmenu unsetmenu addmenu 1164 Name exportUI Call the file export graphical interface exportUIfigId exportUIfig Parameters figId integer Id of the figure to export fig Figure handle handle of the figure to export Description exportUI routine call the graphical interface dedicated in exporting a graphic window into an image file See Also xs2jpg xs2eps xs2png xs2svg xs2pdf Authors JeanBaptiste Silvy 1165 Name figure create a figure f figurenum f figurePropertyName1 Propertyvalue1 PropertyNameN PropertyvalueN Description This routine creates a figure If an ID is given the figure corresponding to this ID is created Otherwise the window is created with the first free ID that is the lowest integer not already used by a window Parameters num ID of the window to create If not specified the first free ID is used PropertyName1 N character string name of a property to set One of the property names listed below PropertyValue1 N scilab object value to give to the corresponding property f handle of the newly created window Properties BackgroundColor 13 real vector or string Background color of the figure A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB Figurename character string allows to set the title of the figure ForegroundColor 13 real vector or string Foreground color of the figure A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB Position allows to control the geometrical aspect of the figure It is a 14 real vector x y width height where the letters stand for the x location of the top left corner the y location of the top left corner the width and the height of the virtual graphics window the part of the figure which contains uicontrols and graphics See the axessize property description in figure properties help page One can also set this property by giving a string where the fields are separated by a ie xy widthheight Tag string this property is generally used to identify the figure It allows to give it a name Mainly used in conjontion with findobj Userdata this can be used to associate some Scilab objects to a fugure figure 1166 Examples Create figure having figureid3 hfigure3 Add a text uicontrol in figure 3 uicontrolh style text string This is a figure position 50 70 100 100 fontsize15 Create figure having figureid1 figure Add a text uicontrol in figure 1 uicontrolstyle text string Another figure position 50 70 100 100 fontsize 15 Close current figure ie figure 1 close close figure 3 closeh See Also close gcf Authors Bertrand Guiheneuf VC 1167 Name findobj find an object with specified property h findobjpropertyName propertyValue Parameters propertyName string character Name of the property to test case unsensitive propertyValue string character specify the value the tested propoerty should be equal to case sensitive h handle of the found object Description This routine is currently used to find objects knowing their tag property It returns handle of the first found object which property propertyName is equal to propertyValue If such an object does not exist the function returns an empty matrix Examples Create a figure hfigure Put a text in the figure uicontrolh styletext stringThis is a figure position50 70 100 100 fontsize15 tagAlabel Find the object which tag value is Alabel labfindobjtagAlabel dispThe text of the label is labstring Close the figure close See Also uicontrol uimenu set get Authors Bertrand Guiheneuf VC 1168 Name gcbo Handle of the object whose callback is executing gcbo Description gcbo is a Scilab variable automatically created each time a callback in executed This variable is initialised using getcallbackobject gcbo does not exists in Scilab environment if no callback is currently executed You can use gcbo in callback functions particularly if you write a single callback function for multiple objects it helps you to know which object received a user action See Also getcallbackobject Authors Vincent COUVERT 1169 Name getcallbackobject Return the handle of the object whose callback is executing h getcallbackobject Parameters h Handle the handle of the object whose callback is executing Description getcallbackobject is used to automatically create Scilab variable called gcbo each time a call back in executed getcallbackobject returns if no callback is currently executed See Also gcbo Authors Vincent COUVERT 1170 Name getinstalledlookandfeels returns a string matrix with all Look and Feels lnfgetinstalledlookandfeels Parameters lnf a string matrix Description returns a string matrix with all Look and Feels that you can use Examples getinstalledlookandfeels See Also setlookandfeel getlookandfeel Authors Allan CORNET 1171 Name getlookandfeel gets the current default look and feel lnfgetlookandfeel Parameters lnf a string with current look and feel bok a boolean Description Gets the current default look and feel Examples currentlnf getlookandfeel Look and feel CDEMotif setlookandfeelcomsunjavaswingplafmotifMotifLookAndFeel sleep3000 Look and feel métal setlookandfeeljavaxswingplafmetalMetalLookAndFeel sleep3000 setlookandfeelcurrentlnf See Also getinstalledlookandfeels setlookandfeel Authors Allan CORNET 1172 Name getvalue xwindow dialog for data acquisition okx1x14getvaluedesclabelstypini Parameters desc column vector of strings dialog general comment labels n column vector of strings labelsi is the label of the ith required value typ listtyp1dim1typndimn typi defines the type of the ith value may have the following values mat for constant matrix col for constant column vector row for constant row vector vec for constant vector str for string lis for list dimi defines the size of the ith value it must be a integer or a 2vector of integer 1 stands for undefined dimension ini n column vector of strings inii gives the suggested response for the ith required value ok boolean t if ok button pressed f if cancel button pressed xi contains the ith value if okt If left hand side has one more xi than required values the last xi contains the vector of answered strings Description This function encapsulate xmdialog function with error checking evaluation of numerical re sponse Remarks All valid expressions can be used as answers for matrices and vectors getvalues automatically adds around the given answer before numeric evaluation getvalue 1173 Examples labelsmagnitudefrequencyphase okmagfreqphgetvaluedefine sine signallabels listvec1vec1vec1085102pi3 See Also xmdialog xmatrix xdialog Authors S Steer 1174 Name messagebox Open a message box btn messageboxmsg btn messageboxmsg msgboxtitle btn messageboxmsg msgboxtitle msgboxicon btn messageboxmsg msgboxtitle msgboxicon btn messageboxmsg msgboxtitle msgboxicon buttons btn messageboxmsg msgboxtitle msgboxicon buttons ismodal Parameters msg Matrix of strings the message box displays each entry of this matrix one entry per line msgboxtitle String the title of the message box default value is Scilab Message msgboxicon String the name of the icon to be displayed in the message box its possible values are error hourglass info passwd question warning scilab default icon buttons 1xn vector of strings the names of the buttons to be displayed in the message box By default only one button is displayed with label OK modal String modal to create a modal dialog any other string to create a nonmodal dialog Please note that modal can replace any of the other input arguments except msg See examples btn Scalar number of the button that the user pressed 1 is the leftmost button for a modal dialog 0 else Description Creates a dialog window to display a message waiting or not for a user action Examples Simple example messageboxSingle line message messagebox 1175 Multi line message with title messageboxMultiline message User defined title Icon specified by th euser messageboxAn error message Error error Buttons labels modal replaces title messageboxHave you seen this beautiful message modal info Yes No modal given as fifth input argument messageboxAn error message Error error Continue Stop modal Authors Vincent COUVERT 1176 Name printfigure Opens a printing dialog and prints a figure printfigurefigid status printfigurefigid Parameters figid Real the id of the figure to be printed status Boolean T if the printing succeeds F otherwise Description This function opens a dialog to select a printer printing options and then prints the figure Examples plot2d printfiguregetgcf figureid See Also toprint printsetupbox Authors VC 1177 Name printsetupbox Display print dialog box printsetupbox statusprintsetupbox Parameters status Boolean T if the user clicked on the OK button F otherwise Description Displays the builtin printing dialogbox and configure the printer See Also toprint printfigure Authors AC 1178 Name progressionbar Draw a progression bar winIdprogressionbarmes progressionbarwinIdmes Parameters mes string message to display winId integer greater than 0 window identificator Description progressionbarmes create a new progression bar return window identificator progressionbarwinIdmes update the progression bar identificated as winId Examples winIdprogressionbarDo something realtimeinit03 for j0011 realtime3j progressionbarwinId end winclosewinId Authors Jaime Urzua 1179 Name rootproperties description of the root object properties Description The root object is a virtual object used to get the computer screen properties Use get function with 0 as first argument to access its properties Root properties screensizepx The screen size in pixels screensizept The screen size in points screensizemm The screen size in millimeters screensizecm The screen size in centimeters screensizein The screen size in inches screensizenorm The normalized screen size screendepth The number of bits used to encode colors Examples get0 screensizepx get0 screendepth See Also get Author Vincent COUVERT 1180 Name setlookandfeel sets the current default look and feel boksetlookandfeel boksetlookandfeellnf Parameters lnf a string with a look and feel bok a boolean Description Sets the current default Look and Feel setlookandfeel without parameter set system default look and feel Examples currentlnf getlookandfeel Look and feel Windows Classic setlookandfeelcomsunjavaswingplafwindowsWindowsClassicLookAndFeel Look and feel Windows setlookandfeelcomsunjavaswingplafwindowsWindowsLookAndFeel sleep3000 Look and feel CDEMotif setlookandfeelcomsunjavaswingplafmotifMotifLookAndFeel sleep3000 Look and feel GTK setlookandfeelcomsunjavaswingplafgtkGTKLookAndFeel sleep3000 Look and feel métal setlookandfeeljavaxswingplafmetalMetalLookAndFeel sleep3000 Look and feel Macintosh setlookandfeelitunitningswingplafmacosMacOSLookAndFeel System default look and feel setlookandfeel sleep3000 setlookandfeel 1181 restore previous look and feel setlookandfeelcurrentlnf See Also getinstalledlookandfeels getlookandfeel Authors Allan CORNET 1182 Name setmenu interactive button or menu activation setmenubutton nsub setmenugwinbutton nsub Parameters button a character string The button name gwin integer The number of graphic window where the button is installed nsub integer The number of submenu to deactivate if any If button has no submenu nsub is ignored Description The function allows the user to make active buttons or menus created by addmenu in the main or graphics windows command panels Examples addmenufoo New button made in main scilab window unsetmenufoo button foo cannot be activated grey string setmenufoo button foo can be activated black string See Also delmenu unsetmenu addmenu 1183 Name toolbar show or hide a toolbar state1toolbarwinnumstate2 state1toolbarwinnum Parameters state1 returns toolbars state on or off winum windows number 1 Scilab console window state2 on or off set toolbars state Description show or hide a toolbar Examples toolbar1off statetoolbar1on plot3d hgcf toolbarhfigureidoff Authors Allan CORNET Vincent COUVERT 1184 Name toprint Send text or figure to the printer toprintfilename toprintlinestoprintpageheader toprintfigid toprintfigidoutput status toprintfilename status toprintlinestoprintpageheader status toprintfigid status toprintfigidoutput Parameters filename String path of the text file to be printed linestoprint String matrix text to be printed each entry is a line in printed pages pageheader String header of printed pages figid Real the id of the figure to be printed output String printing output type must be pos for PostScript or gdi for Bitmap format gdi by default status Boolean T if the printing succeeds F otherwise Description Prints a text file Scilab character strings or figure Examples toprintSCIetcscilabstart toprintTesttoprint primitiveScilab page header scf4 plot toprint4 toprint4pos See Also printfigure printsetupbox Authors AC VC 1186 Name uicontrol create a Graphic User Interface object h uicontrolPropertyNamePropertyValue h uicontrolparentPropertyNamePropertyValue h uicontroluich Description This routine creates an object in a figure If the handle of the figure is given as the first parameter the uicontrol is created in this figure If no handle is given the uicontrol is created in the current figure which may be obtained with a call to gcf If there is no current figure then one is created before the creation of the uicontrol Then when the control is created the properties given as parameters are set with the corresponding values It is equivalent to create the uicontrol and then set its properties with the set command Nevertheless it generally more efficient to set the properties in the call to uicontrol This is particularly true concerning the Style property Indeed the default value for this property is Push button So if you do not set it at creation time a button will be created and will be transformed to another uicontrol when you call the seth Style instruction Scilab and all the graphic objects communicate through the property mechanism Thus to create adapted uicontrol one has to know the use of the property fields h uicontrolPropertyName PropertyValue creates an uicontrol and assigns the specified properties and values to it It assigns the default values to any properties you do not specify The default uicontrol style is a Pushbutton The default parent is the current figure See the Properties section for information about these and other properties h uicontrolparent PropertyName PropertyValue creates a uicontrol in the object specified by the handle parent If you also specify a different value for the Parent property the value of the Parent property takes precedence parent is the handle of a figure h uicontroluich gives focus to the uicontrol specified by uich Properties BackgroundColor 13 real vector or string Background color of the uicontrol A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB Callback String Instruction evaluated by the Scilab interpreter when an uicontrol is activated for example when you click on a button Enable on off Enable or disable the uicontrol If this property is set to on default the uicontrol is opera tional but if this property is set to off the uicontrol will not respond to the mouse actions and will be grayed out uicontrol 1187 FontAngle normal italic oblique For a control containing some text this property sets the slant of the font FontSize Scalar For a control containing some text this property sets the size of the font in FontUnits FontUnits points pixels normalized For a control containing some text this property sets the units with which the FontSize is specified FontWeight light normal demi bold For a control containing some text this property sets the weight of the used font FontName String Used to choose the name of the font selected to display the text of the control ForegroundColor 13 real vector or string Foreground color of the uicontrol A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB HorizontAlalignment left center right Set text horizontal alignment in the uicontrol This property has only effect with Text Edit and Check Boxes ListboxTop Scalar For a ListBox this property tells which item of the list appears on the first line of the visible area of the list Max Scalar Specifies the largest value the Value property can be set to It has however different meaning on each uicontrol CheckBoxes Max is the value the Value property take when control is checked Sliders Maximum value of the slider ListBoxes if MaxMin1 the list allows multiple selection Otherwise not Min Scalar Specifies the lowest value the Value property can be set to It has however different meaning on each uicontrol uicontrol 1188 CheckBoxes Min is the value the Value property take when control is unchecked Sliders Minimum value of the slider ListBoxes if MaxMin1 the list allows multiple selection Otherwise not Parent Handle Handle of the uicontrol parent Changing this property allows to move a control from a figure to another Path This property is no more supported Position 14 real vector or string This property is used to set or get the geometrical configuration of a control It is a vector x y w h where the letters stand for the x location of the left bottom corner the y location of the left bottom corner the width and the height of the uicontrol or a character string where each value is separated by a ie xywh The units are determined by the Units property The width and height values determine the orientation of sliders If width is greater than height then the slider is oriented horizontally otherwise the slider is oriented vertically Relief flat groove raised ridge solid sunken Appearance of the border of the uicontrol PushButtons the default value for Relief property is raised Edits the default value for Relief property is sunken Other styles the default value for Relief property is flat SliderStep 12 real vector small big the small step represents the movement achieved when clicking on the slider trough or tapping on the keyboard arrows when the slider has focus the big step is the amount moved when using Ctrlkeyboardarrows If the big step is omitted it is defaulted to 110 of the scale String String This property represents the text appearing in a uicontrol Except for Frame and Slider styles For ListBoxes and PopupMenus the value can be a vector of string or a string where the items are separated by a For Text uicontrols this string can contain HTML code to format the text Style pushbutton radiobutton checkbox edit text slider frame listbox popupmenu Style of the uicontrol Here is a short description of each one Pushbutton a rectangular button generally used to run a callback Radiobutton a button with to states RadioButtons are intended to be mutually exclusive Your code must implement mutually exclusive behavior Checkbox a button with to states Used for multiple independent choices uicontrol 1189 Edit an editable string zone Text a text control generally static Slider a scale control that is a scrollbar use to set values between in range with the mouse Frame a control representing a zone used to group related controls Listbox a control representing a list of items that can be scrolled The items can be selected with the mouse Popupmenu a button which make a menu appear when clicked Tag String This property is generally used to identify the control It allows to give it a name Mainly used in conjunction with findobj Units points pixels normalized Set the units used to specify the Position property Userdata Scilab data This can be used to associate some Scilab objects stringstring matrix matrix mxn to an uicon trol Value Scalar or vector Value of the uicontrol The exact meaning depends on the style of the uicontrol CheckBoxes Radio buttons value is set to Max see above when on and Min when off ListBoxes PopupMenus value is a vector of indexes corresponding to the indexes of the se lected entries in the list 1 is the first item of the list Sliders value indicated by the slider bar Verticalalignment top middle bottom Set text vertical alignment in the uicontrol This property has only effect with Text and Check Boxes styles Visible on off Set the visibility of the uicontrol If this property is set to on default the uicontrol is visible but if this property is set to off the uicontrol will not appear in its parent figure Examples ffigure create a figure huicontrolfstylelistbox position 10 10 150 160 uicontrol 1190 create a listbox seth string item 1item 2item3 fill the list seth value 1 3 select item 1 and 3 in the list closef close the figure See Also figure set get uimenu Authors Bertrand Guiheneuf Vincent Couvert 1191 Name uigetcolor Opens a dialog for selecting a color uigetcolor RGB uigetcolortitle RGB uigetcolortitle defaultRGB RGB uigetcolortitle defaultRed defaultGreen defaultBlue R G B uigetcolortitle R G B uigetcolortitle defaultRGB R G B uigetcolortitle defaultRed defaultGreen defaultBlue Parameters title String Optional argument the title to display in the dialog Default value is Color Chooser defaultRGB 1x3 vector the default values for Red Green and Blue values given as a vector red green blue defaultRed Scalar the default value for red defaultGreen Scalar the default value for green defaultBlue Scalar the default value for blue RGB 1x3 vector the values for Red Green and Blue values given as a vector red green blue or if the user cancels R Scalar the value for red or if the user cancels G Scalar the value for green or if the user cancels B Scalar the value for blue or if the user cancels Description Creates a dialog window for selecting a color All default and returned values must be in the interval 0 255 Examples uigetcolor R G B uigetcolor255 128 0 RBG uigetcolor0 128 255 RBG uigetcolorMy color chooser 0 128 255 uigetcolor 1192 See Also getcolor Authors Vincent COUVERT 1193 Name uigetdir dialog for selecting a directory directory uigetdir directory uigetdirstartpath title Parameters startpath a character string which gives the initial directory used for search By default uigetdir uses current working directory title the title for the uigetdir window directory is the user selected directory if user answers Ok or the string if user cancels Description Creates a dialog window for selecting a directory Examples uigetdir uigetdirSCImodules uigetdirSCImodules Choose a directory See Also uigetfile uiputfile 1194 Name uigetfile dialog window to get a files names path and filter index FileNamePathNameFilterIndexuigetfilefilemaskdirboxTitlemultipleSelection PathFileNameuigetfilefilemaskdirboxTitlemultiple Input parameters filemask a string matrix which gives the file masks to use for file selection filemask is written with Unix convention The default value is we can also add descriptions for masks for example xX filesbinBIN files dir a character string which gives the initial directory used for file search By default uigetfile uses the previously selected directory boxTitle a character string which gives the title of the uigetfile window By default uigetfiles title is uiget file multipleSelection a boolean which allows to load only one file if it is at f false or multiple files if it is at t true By default uigetfiles multiple file selection is not enable Output parameters FileName matrix of string which give the user selected files path files names if user answers Ok or the string if user answers Cancel PathName is the user selected files path if user answers Ok or the string if user answers Cancel FilterIndex is the user selected filter index on the list box if user answers Ok or 0 string if user answers Cancel Description Creates a dialog window for files selection Comments On Windows java component used by uigetfile browse also zip archive then it is very slow with big zip files To disable this feature if MSDOS then unixREGSVR32 u WINDIRSystem32zipfldrdll end To reenable if MSDOS then unixREGSVR32 WINDIRSystem32zipfldrdll end uigetfile 1195 Examples uigetfilebinscecos uigetfilescibinSCImodulesguimacros uigetfilescbinSCImodulesguimacros uigetfilexX filesbinBIN filesSCImodulesguimacros uigetfilescebinSCImodulesguimacros Choose a file name t uigetfilescebinSCImodulesguimacros Choose a file name f See Also uiputfile uigetdir xdialog file read write exec 1196 Name uigetfont Opens a dialog for selecting a font uigetfont fontname fontsize bold italic uigetfontdefaultfontname defaultfontsize defaultbold defaultitalic fontname fontsize bold italic uigetfontdefaultfontname defaultfontsize defaultbold defaultitalic Parameters defaultfontname String the default font name to select in the dialog defaultfontsize Scalar the default font size to select in the dialog defaultbold Boolean the default bold attribute in the dialog T for bold font F otherwise defaultitalic Boolean the default italic attribute in the dialog T for bold font F otherwise fontname The selected font name if the user cancels fontsize The selected font size if the user cancels bold T if bold attribute has been selected F otherwise if the user cancels italic T if italic attribute has been selected F otherwise if the user cancels Description Creates a dialog window for selecting a font Examples uigetfont uigetfontarial uigetfontarial 24 uigetfontarial 24 T uigetfontarial 24 T F See Also getfont Authors Vincent COUVERT 1197 Name uimenu Create a menu or a submenu in a figure huimenuprop1val1 prop2 val2 huimenuparentprop1 val1 prop2 val2 Parameters parent integer Handle of menus parent prop1 2 string character name of a property to set up val1 2 scilab object value to affect to the corresponding property h integer handle of the corresponding menu Description This allows to create menus in a figure If parent is a figure then the menu item will be added to the menu bar of the figure If parent is a menu item then the new item will be added to the parent item allowing to create cascaded submenu To create a customized menu you can use the properties listed below Properties Callback String Instruction evaluated by the Scilab interpreter when the menu is activated Under MacOSX the callback will not be executed for a button menu a menu without children you must specify at least a child Enable on off Enable or disable the menu If this property is set to on default the menu is operational but if this property is set to off the menu will not respond to the mouse actions and will be grayed out Checked on off Menu check indicator Setting this property to on respectively off places respectively re moves a check mark next to the corresponding menu item This option can be used to create menus that indicate the state of a particular option Please note that a standard menu without the option Checked set has no mechanism to become a menu which will be checked by a user action and conversely This property is ignored for parent menus ForegroundColor 13 real vector or string uimenu 1198 Foreground color of the uimenu font color A color is specified as Red Green and Blue values Those values are real in 01 The color can be given as a real vector ie RGB or a string where each value is separated by a ie RGB Label String This property represents the text appearing in the menu Tag String This property is generally used to identify the menu It allows to give it a name Mainly used in conjunction with findobj Visible on off Set the visibility of the uimenu If this property is set to on default the uimenu is visible but if this property is set to off the uimenu will not appear in its parent figure Examples ffigureposition 10 10 300 200 create a figure muimenuflabel windows create an item on the menu bar m1uimenumlabel operations m2uimenumlabel quit scilab callback exit create two items in the menu windows m11uimenum1label new window callbackxselect m12uimenum1label clear window callbackclf create a submenu to the item operations closef close the figure See Also figure uicontrol set get Authors Bertrand Guiheneuf 1199 Name uiputfile Open standard dialog box for selecting and saving file FileNamePathNameFilterIndexuiputfilefilemaskdirboxTitle PathFileNameuiputfilefilemaskdirboxTitle Input parameters filemask a string matrix which gives the file masks to use for file selection filemask is written with Unix convention The default value is we can also add descriptions for masks for example xX filesbinBIN files dir a character string which gives the initial directory used for file search By default uiputfile uses the previously selected directory boxTitle a character string which gives the title of the uiputfile window By default uiputfiles title is uiput file Output parameters FileName string which give the user selected file path file name if user answers Ok or the string if user answers Cancel PathName is the user selected file path if user answers Ok or the string if user answers Cancel FilterIndex is the user selected filter index on the list box if user answers Ok or 0 string if user answers Cancel Description Creates a dialog window for file saving Examples uiputfilebinscecos uiputfilescibinSCImodulesguimacros uiputfilescbinSCImodulesguimacros uiputfilexX filesbinBIN filesSCImodulesguimacros uiputfilescebinSCImodulesguimacros Choose a file name See Also uigetfile uigetdir 1200 Name unsetmenu interactive button or menu or submenu deactivation unsetmenubuttonnsub unsetmenugwinbuttonnsub Parameters button a character string The button name gwin integer The number of graphic window where the button is installed nsub integer The number of submenu to deactivate if any If button has no submenu nsub is ignored Description The function allows the user to desactivate buttons or menus created by addmenu in the main or graphics windows command panels Examples addmenufoo unsetmenufoo unsetmenuFile2 See Also delmenu setmenu addmenu 1201 Name usecanvas GetSet the main component used for Scilab graphics canvasused usecanvasusecanvasfordisplay Parameters canvasused Boolean T if a GLCanvas is used for graphics display Mixing uicontrols and graphics not avail able F if a GLJPanel is used for graphics display Mixing uicontrols and graphics available usecanvasfordisplay Boolean T to use a GLCanvas for graphics display Mixing uicontrols and graphics not available F to use a GLJPanel for graphics display Mixing uicontrols and graphics available Description Scilab uses a GLJPanel a Swing OpenGL component to display graphics plot3d plot This component uses some high level OpenGL primitives which are not correctly supported on some plat forms depending on the operating system video cards drivers GLCanvas AWT OpenGL is an alternative component provided by the Java Framework Scilab can use it to render graphics However using this component disables some capabilities such as mixing plots and uicontrols see demo GUIUIcontrol2 That is why it is not the default behavior In some particular cases the use of the GLCanvas component is forced when Scilab starts a warning message is displayed when a graphics function is used for the first time here is a list of these cases Operating System Video Card Details 64bits Windows All When Scilab is used in a remote session Linux NVIDIA Card With free drivers ATI Card With free drivers or ATIdrivers with version 8523 Installer version 88 OpenGL version 217873 INTEL Card With Direct Rendering activat ed You can also dynamically activate this component through Scilab using usecanvas usecanvasT will use GLCanvas for plot rendering usecanvasF will use GLJPanel for plot rendering If your configuration is known as a one having problems with GLJPanel See table above a warning message will be displayed If you believe your configuration is able to use the GLJPanel and Scilab automatically forces the use of GLCanvas you can test your configuration by swithing to GLJPanel usecanvasF and usecanvas 1202 try to plot something plot3d for example If Scilab graphics work please inform us about it by sending an email to scilabsupportscilaborg and giving us your Operating SystemVideo CardVideo Card driver version this will help use to improve future versions of Scilab Technical Aspects Since version 50 Scilab is doing an advanced use of JOGL the Java Binding for the OpenGL which is using the Java2D OpenGL Pipeline For performance reasons we use the Java2D OpenGL Pipeline From a more technical aspect it uses the internal buffer of the graphic cards called pbuffer Problems may occur when the driver of the graphic card does not support properly this approach As far as we know there is no free driver under Linux handling this feature In the proprietary world the situation is as follows NVIDIA Nvidia provides the appropriate proprietary drivers Scilabs graphics work without any problem with most NVIDIA drivers ATI From the driver version 88 most ATI graphics supports the pbuffer under Linux Intel This is the big drawback of using the pbuffer There is currently no support of pbuffer by any official Intel drivers under Linux There is a workaround for Linux to tackle this issue but a solution is to use a software accelerated driver To do it in etcX11xorgconf look for the Section Device and change the option Driver to vesa Section Device Identifier Your Graphic card Driver vesa EndSection Unfortunately this solution makes Scilab pretty slow Under Windows video cards manufacturers update regularly and pbuffers are managed Please download recent drivers at For ATI cards httpatiamdcomsupportdriverhtml For Intel cards httpwwwintelcomsupportgraphics For Matrox cards httpwwwmatroxcomgraphicsensupportdrivers For NVIDIA cards httpwwwnvidiacomcontentdriversdriversasp For S3 cards httpwwws3graphicscomenresourcesdriversindexjsp For SiS cards httpwwwsiscomdownload For VIA cards httpwwwviaarenacomdefaultaspxPageID2 Some troubles can also occur when using Windows 2000 video drivers are no more updated and no more supported In the cases where pBuffer create a problem waiting for a working pbuffer is not a solution indeed The OpenGL community is moving away from pbuffers and toward the frame buffer object extension which is a more portable and higherperformance solution for offscreen rendering than pbuffers httpsjogldevjavanetissuesshowbugcgiid163 The JOGL team is working to fix this issue usecanvas 1203 For more information about this problem please refer to JoGL bug database Bug 366 httpsjogldevjavanetissuesshowbugcgiid366 Scilab bug database Bug 3525 httpbugzillascilaborgshowbugcgiid3525 Debian bug database Bug 501799 httpbugsdebianorgcgibinbugreportcgibug501799 Freedesktop bug database Bug 17603 httpsbugsfreedesktoporgshowbugcgiid17603 Examples Example using GLJPanel Mixing uicontrols and graphics is available usecanvasF plot2d uicontrolString Close the window Position 10 10 100 25 Callback deletegcf messageboxYou can see the button on the figure Usecanvas example info Example using GLCanvas Mixing uicontrols and graphics is not available uicontrols are not visible usecanvasT plot2d uicontrolString Close the window Position 10 10 100 25 Callback deletegcf messageboxYou cant see any button on the figure Usecanvas example info Authors Vincent COUVERT 1204 Name waitbar Draw a waitbar winIdwaitbarx winIdwaitbarxmes winIdwaitbarmes waitbarxwinId waitbarmeswinId waitbarxmeswinId Parameters x real fraction to display mes string message to display winId integer greater than 0 window identificator Description waitbarx create a new waitbar displaying a fraction x return window identificator waitbarxmes create a new waitbar displaying a fraction x and message mes return window identificator waitbarmes create a new waitbar displaying a fraction 0 and message mes return window iden tificator waitbarxmes create a new waitbar displaying a fraction 0 and message mes return window identificator waitbarxwinId waitbarmeswinId and waitbarxmeswinId update wait bar with window identificator winId Examples winIdwaitbarThis is an example realtimeinit03 for j0011 realtime3j waitbarjwinId end winclosewinId Authors Jaime Urzua 1205 Name xchoices interactive Xwindow choices through toggle buttons repxchoicestitleitems Parameters title vector of strings title for the popup window items a list of items itemslistitem1itemn where each item is also a list of the following type itemlistlabeldefaultchoicechoices defaultchoice is an integer which gives the default toggle on entry and choices is a row vector of strings which gives the possible choices rep an integer vector which gives for each item the number of the selected toggle If user exits dialog with cancel button rep is set to Description Select items through toggle lists and return in rep the selected items Type xchoices to see an example Examples l1 listchoice 11toggle c1toggle c2toggle c3 l2 listchoice 22toggle d1toggle d2toggle d3 l3 listchoice 33toggle e1toggle e2 rep xchoicesToggle Menulistl1l2l3 1206 Name xchoose interactive window choice modal dialog numxchooseitemstitle button Parameters items column vector of string items to choose title column vector of string comment for the dialog button string text to appear in the button Default value is Cancel num integer choosen item number or 0 if dialog resumed with Cancel button Description Returns in num the number of the chosen item WARNING this dialog was not modal before Scilab 50 please use xchoosemodeless for ascendant compatibility Examples n xchooseitem1item2item3that is a commentfor the dialog n xchooseitem1item2item3that is a commentReturn See Also xchoosemodeless xchoices xmdialog getvalue unixg 1207 Name xchoosemodeless interactive window choice not modal dialog numxchoosemodelessitemstitle button Parameters items column vector of string items to choose title column vector of string comment for the dialog button string text to appear in the button Default value is Cancel num integer choosen item number or 0 if dialog resumed with Cancel button Description Returns in num the number of the chosen item Examples n xchoosemodelessitem1item2item3that is a commentfor the dialog n xchoosemodelessitem1item2item3that is a commentReturn See Also xchoose xchoices xmdialog getvalue unixg 1208 Name xdialog Dialog for interactive multilines input resultxdialoglabelsvalueini Parameters labels column vector of strings comment for dialog valueini n column vector of strings initial value suggested result User answer n column vector of strings if returned with Ok button or if returned with Cancel button Description Opens a dialog for interactive multilines input Examples gainevstrxdialogvalue of gain 0235 xdialogMethodenter sampling period1 mevstrxdialogenter a 3x3 matrix 0 0 00 0 00 0 0 See Also xmdialog xmatrix evstr execstr 1209 Name xmatrix Xwindow editing of matrix resultxmatrixlabelmatrixinit Parameters label character string name of matrix matrixinit real matrix Description For reading or editing a matrix Examples mevstrxmatrixenter a 3x3 matrix rand33 See Also xmdialog xdialog 1210 Name xmdialog Dialog for interactive vectormatrix input resultxmdialogtitlelabelsdefaultinputsvector resultxmdialogtitlelabelsvlabelshdefaultinputmatrix Parameters title column vector of strings dialog general comment labels n column vector of strings labelsi is the label of the ith required value defaultinputvector n column vector of strings defaultinputvectori is the initial value of the ith re quired value labelsv n vector of strings labelsvi is the label of the ith line of the required matrix labelsh m vector of strings labelshj is the label of the jth column of the required matrix defaultinputmatrix n x m matrix of strings defaultinputmatrixij is the initial value of the ij ele ment of then required matrix result n x m matrix of string if returned with Ok button or if returned with Cancel button Description Opens a dialog for interactive vectormatrix input Examples txt magnitudefrequencyphase sig xmdialogenter sine signaltxt1100 mag evstrsig1 frq evstrsig2 ph evstrsig3 rep xmdialogSystem Simulationwith PI regulator P gainI gain See Also editvar xdialog xchoose messagebox getvalue evstr execstr editvar 1211 Name xmessagemodeless X window modeless message xmessagemodelessstrings Parameters strings vector of characters strings to be displayed Description for displaying a message information userguide The function returns immediately The message window is killed when Ok button is clicked Examples xmessagemodelessThis is a modeless message Scilab may continue computation Click on Ok to close the message xmessagemodelessNow two message windows are opened See Also xdialog xmdialog messagebox Parte XVI Link Dinâmicoincremental 1213 Name call chamada a rotinas de usuário FORTRAN ou C forma longa out está presente y1ykcallidentx1px1tx1xnpxntxn outny1my1py1ty1nylmylpyltyl forma curta nenhum parâmetro out y1ykcallidentx1xn Parâmetros ident string xi real matrix or string pxi pyi inteiro txi tyi string d r i ou c Descrição Chamada interativa ao programa do usuário FORTRAN ou C do Scilab A rotina deve estar previa mente linkada ligada ao Scilab Este link pode ser feito Com o comando link do Scilab linkagem suave soft incremental durante a sessão Scilab ver link Há duas formas de sintaxe de chamamento uma curta e uma longa A curta fornece um código mais rápido e uma sintaxe de chamamento mais fácil mas devese escrever uma pequena interface C ou FORTRAN para que esta forma seja possível A forma longa torna possível uma chamada a uma rotina FORTRAN ou C sem modificação do código mas a sintaxe é mais complexa e o código interpretado mais devagar O significado de cada parâmetro é descrito abaixo ident é o nome da subrotina chamada x1xn são as variáveis de entrada strings ou matrizes de reais enviados à rotina px1pxn são as respectivas posições destas variáveis na seqüência de chamamento da rotina ident e tx1txn são seus tipos r i d e c para ponto flutuante real inteiro dupla precisão e strings out é a palavrachave usada para separar variáveis de entrada das variáveis de saída Quando esta palavrachave está presente ela indica que a forma longa será usada e quando não está presente indica que a forma curta será usada ny1 my1 são os tamanhos número de linhas e colunas Para argumentos c m1n1 é o número de carac teres das variáveis de saída e call 1214 py1 são as posições das variáveis de saída possivelmente iguais a pxi na seqüência de chamamento da rotina Os inteiros pyis devem estar em ordem crescente ty1 são os tipos FORTRAN das variáveis de saída As k primeiras variáveis de saída são postas em y1 yk Se uma variável de saída coincide com uma variável de entrada ie pyipxj podese apenas passar sua posição pyi O tamanho e tipo de yi são então os mesmos que os dexi Se uma variável de saída coincide com uma variável de entrada e são especificadas as dimensões da variável de saída mylnyl deve satisfazer a condição de compatibilidade mxknxk mylnyl Exemplos Exemplo 1 com um código C simples f1include mathh void fooccabmn double abc int mn int i for i 0 i mn i ci sinai b mputlf1foocc criando a biblioteca compartilhada um gateway ligação um Makefile e um loader carregador são gerados ilibforlinkfoocfooccc carregando a biblioteca compartilhada exec loadersce usando a nova primitiva a123456b pi mnsizea Entradas a está na posição 2 e double b 3 double n 4 integer m 5 integer Saídas c está na posição 1 e double com tamanho mn ccallfooca2db3dm4in5ioutmn1d Exemplo 2 com um código FORTRAN simples f1 subroutine foofcabnm integer nm double precision abc do 10 i1mn ci sinaib 10 continue call 1215 end mputlf1fooff criando a biblioteca compartilhada um gateway um Makefile e um loader são gerados ilibforlinkfooffoofff carrega a biblioteca compartilhada exec loadersce usando a nova primitiva a123456b pi mnsizea ccallfoofa2db3dm4in5ioutmn1d Ver Também link clink intersci addinter 1216 Name Gmake call make or nmake RfilesGmakefilesdllname Parameters files a character string or a vector of character string dllname a character string Rfiles vector of character string Rfiles can be used as a first argument when calling addinter function Description On Unix like systems Gmake calls the make utility for building target files and returns the val ue of files in the variable Rfiles On windows platforms Gmake calls the nmake utility for building target dllname and it returns the value of dllname in the variable Rfiles Of course Gmake will work if apropriate Makefiles are provided in the current Scilab directory Gmake can be used to provide OS independant call to addinter Examples if MSDOS then txt ex1cdll echo echo From Makefilemak echo mputltxtTMPDIRmakefilemak currentdir pwd cd TMPDIR filesGmakeTMPDIRex1cIoTMPDIRex1coex1cdll compilation addinterfilesfoobarfoubare link cdcurrentdir end See Also addinter 1217 Name VCtoLCCLib converts Ms VC libs to LCCWin32 libs VCtoLCCLib Description converts Ms VC libs to LCCWin32 libs Examples bOKchooselcccompiler VCtoLCCLib Authors Allan CORNET 1218 Name addinter new functions interface dynamic link at run time addinterfilesspnamefcts Parameters files a character string or a vector of character string contain object files used to define the new Scilab interface routine interface code user routines or libraries system libraries spname a character string Name of interface routine entry point fcts vector of character strings The name of new Scilab function implemented in the new interface in fin the order Description addinter performs dynamic link of a compiled C or Fortran new Scilab interface routine and define corresponding scilab functions You can use the command linkshow to get the number of the shared libraries And to reload a new version of an interface a call to ulink is necessary to get rid of the old version See link for more precision on use Number of addinter in a scilab session can be limited by the operating system On Windows you cannot load more than 80 dynamic libraries at the same time Number of functions implemented in a interface is limited to 1000 Examples if haveacompiler then chdirTMPDIR mkdirexampleaddinter chdirexampleaddinter src include mathh include stackch include apiscilabh include Scierrorh include localizationh static double fun2double x void fun1double xdouble y yfun2xx static double fun2double x return sinx1 addinter 1219 int scifun1char fname int iType1 0 SciErr sciErr int m1 0 n1 0 double pdVarOne NULL int piAddressVarOne NULL CheckRhs11 CheckLhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddressVarOne ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddressVarOne iType1 ifsciErriErr printErrorsciErr 0 return 0 if iType1 scimatrix Scierror999s Wrong type for input argument d A string expected fname 1 return 0 sciErr getMatrixOfDoublepvApiCtx piAddressVarOne m1 n1 pdVarOne ifsciErriErr printErrorsciErr 0 return 0 fun1pdVarOne pdVarOne LhsVar1 1 return 0 mputlsrcTMPDIR exampleaddinterexampleaddinterc filesexampleaddinterc ilibbuildaddinterfun1inscilabscifun1files dispmgetlloadersce exec loadersce fun1inscilabpi end if haveacompiler addinter 1220 See Also link intersci newfun clearfun Authors Allan CORNET 1221 Name clink check incrementaldynamic link clinkroutinename testilibclinkroutinename testclinkroutinenamenum Parameters routinename a character string num test boolean indicates if there is a shared library which contains routinename ilib a scalar the number of the shared library which contains routinename Description clink is a boolean function which checks if the routine routinename is currently linked This function returns a boolean value true or false When used with two return values the function clink returns a boolean value in test and the number of the shared library which contains routinename in ilib when test is true See Also link fort 1222 Name chooselcccompiler choose LCCWin32 as the default C Compiler bOKchooselcccompiler Parameters bOK returns T if LCCWin32 is the default C Compiler Description choose LCCWin32 as the default C Compiler Examples bOKchooselcccompiler Authors Allan CORNET 1223 Name configurelcc set environments variables for LCCWin32 C Compiler bOKconfigurelcc Parameters bOK returns T if environments variables for LCCWin32 C Compiler are OK Description set environments variables for LCCWin32 C Compiler Examples bOKconfigurelcc Authors Allan CORNET 1224 Name configureifort set environments variables for Intel Fortran Compiler Windows bOKconfiguremsifort Parameters bOK returns T if environments variables for Intel fortran 9 or 10 Compiler are OK Description set environments variables for Intel fortran 9 or 10 Compiler Examples bOK configuremsifort Authors Allan CORNET 1225 Name configuremsvc set environments variables for Microsoft C Compiler bOKconfiguremsvc Parameters bOK returns T if environments variables for Ms C Compiler are OK Description set environments variables for Microsoft C Compiler Examples bOKconfiguremsvc Authors Allan CORNET 1226 Name dllinfo provides information about the format and symbols provided in executable and DLL files Windows infolist dllinfofilenameoption Parameters filename a string a filename dll or exe file option a string machine exports imports infolist a list infolist1 a string name of dll or executable infolist2 a string matrix symbols imported or exported or machine type x86 or x64 Description This tool provides information about the format and symbols imported or exported provided in ex ecutable and DLL files This tool is based on dumpbinexe A tool provided with Visual studio SDK Examples if MSDOS then filename SCIbinlibscilabdll dllinfolist dllinfofilenamemachine printfMachine destination of s s dllinfolist1dllinfolist2 dllinfolist dllinfofilenameimports printfDlls dependencies of s filename for i1sizedllinfolist printfs dllinfolisti1 end dllinfolist dllinfofilenameexports printfDll exports of s filename dispdllinfolist end See Also addinter link ilibcompile ilibgenMake ilibgengateway ilibgenloader ilibforlink Authors Allan CORNET 1227 Name findlcccompiler detects LCCWin32 C Compiler retfindlcccompiler Parameters ret returns T or F Description detects LCCWin32 C Compiler Examples retfindlcccompiler Authors Allan CORNET 1228 Name findmsifortcompiler detects Intel fortran Compiler ifortvfindmsifortcompiler Parameters ifortv returns ifort90ifort10ifort11unknown Description detects Intel fortran Compiler Windows Examples ifortv findmsifortcompiler Authors Allan CORNET 1229 Name findmsvccompiler detects Microsoft C Compiler msvcfindmsvccompiler Parameters msvc returns msvc70msvc71msvc80expressmsvc80stdmsvc80promsvc90expressmsvc90stdmsvc90prounknown Description detects Microsoft C Compiler Examples msvcfindmsvccompiler Authors Allan CORNET 1230 Name fort Fortran or C user routines call long form out is present y1ykfortidentx1px1tx1xnpxntxn outny1my1py1ty1nylmylpyltyl short form no out parameter y1ykfortidentx1xn Parameters ident string xi real matrix or string pxi pyi integers txi tyi character string d r i or c Description Interactive call of Fortran or C user program from Scilab The routine must be previously linked with Scilab This link may be done with Scilab link command dynamic link during the Scilab sessionsee link There are two forms of calling syntax a short one and a long one The short one will give faster code and an easier calling syntax but one has to write a small C or Fortran interface in order to make the short form possible The long one make it possible to call a Fortran routine or a C one whitout modification of the code but the syntax is more complex and the interpreted code slower The meaning of each parameter is described now ident is the name of the called subroutine x1xn are input variables real matrices or strings sent to the routine px1pxn are the respective positions of these variables in the calling sequence of the routine ident and tx1txn are their types r i d and c for real float integer double precision and strings out is a keyword used to separate input variables from output variables when this key word is present it is assumes that the long form will be used and when it is not prsent the short form is used ny1 my1 are the size number of rows and columns For c argumentsm1n1 is the number of charaters of output variables and py1 are the positions of output variables possibly equal to pxi in the calling sequence of the routine The pyis integers must be in increasing order fort 1231 ty1 are the Fortran types of output variables The k first output variables are put in y1 yk If an output variable coincides with an input variable ie pyipxj one can pass only its position pyi The size and type of yi are then the same as those of xi If an output variable coincides with an input variable and one specify the dimensions of the output variable mylnyl must follow the compatibility condition mxknxk mylnyl For example the following program subroutine foofcabnm integer nm double precision abc do 10 i1mn ci sinaib 10 continue end linkfoofgetdynlibextfoof a123456b pi mnsizea Inputs a is in position 2 and double b 3 double n 4 integer m 5 integer Outputs c is in position 1 and double with size mn cfortfoofa2db3dn4im5ioutmn1d returns the matrix c2ab The same example coded in C void fooccabmn double abc int mn double sin int i for i 0 i lt mn i ci sinai b linkfoocgetdynlibextfoocC note the third argument a123456b pi mnsizea cfortfooca2db3dm4in5ioutmn1d See Also call link clink intersci addinter 1232 Name getdynlibext get the extension of dynamic libraries on your operating system retgetdynlibext Description get the extension of dynamic libraries on your operating system retgetdynlibext returns so on linuxsl HPUXdll on Windows Examples getdynlibext Authors Allan CORNET 1233 Name haveacompiler detect if you have a C compiler bOKhaveacompiler Parameters bOK returns T if you have a C compiler Description detect if you have a C compiler Examples bOK haveacompiler See Also findlcccompiler findmsvccompiler 1234 Name ilibbuild utility for shared library management ilibbuildlibnametablefileslibs makenameldflagscflagsfflagsismex cc Parameters libname a character string the generic name of the library without path and extension table 2 column string matrix giving the table of pairs scilabname interface name files string matrix giving source from Scilab 50 or object files needed for shared library creation libs string matrix giving extra libraries needed for shared library creation makename character string The path of the Makefile file without extension ldflagscflagsfflags character strings to provide options for the loader the C compiler and the Fortran compiler ismex Internal variable to specify if we are working with mex or not cc Provide the name of the C compiler Description This tool is used to create shared libraries and to generate a loader file which can be used to dynamically load the shared library into Scilab with addinter Many examples are provided in SCImodulesdynamiclinkexamples directory They are all released into the public domain Note that a compiler must be available on the system to use this function Languages handle by this function are C C Fortran and Fortran 90 Examples C code Here with give a complete example on adding new primitive to Scilab create the procedure files cd TMPDIR mkdirexampleilibbuildc cdexampleilibbuildc f1extern double fun2 void fun1double x double y yfun2xx mputlf1TMPDIR exampleilibbuildcfun1c f2include mathh ilibbuild 1235 double fun2double x return sinx1 mputlf2TMPDIR exampleilibbuildcfun2c creating the interface file iinclude stdlibh include stackch include apiscilabh include Scierrorh include localizationh extern int fun1 double x double y int scifun1char fname int iType1 0 SciErr sciErr int m1 0 n1 0 double pdVarOne NULL int piAddressVarOne NULL CheckRhs11 CheckLhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddressVarOne ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddressVarOne iType1 ifsciErriErr printErrorsciErr 0 return 0 if iType1 scimatrix Scierror999s Wrong type for input argument d A string expected fname 1 return 0 sciErr getMatrixOfDoublepvApiCtx piAddressVarOne m1 n1 pdVarOne ifsciErriErr printErrorsciErr 0 return 0 fun1pdVarOne pdVarOne LhsVar1 1 return 0 mputliTMPDIR exampleilibbuildcscifun1c creating the shared library a gateway a Makefile and a loader are ilibbuild 1236 generated filesfun1cfun2cscifun1c ilibbuildbuildcfun1scifun1files load the shared library exec loadersce using the new primitive fun133 Examples C code previous Scilab API 52 cd TMPDIR mkdirexampleilibbuildcold cdexampleilibbuildcold Here with give a complete example on adding new primitive to Scilab create the procedure files f1extern double fun2 void fun1double x double y yfun2xx mputlf1fun1c f2include mathh double fun2double x return sinx1 mputlf2fun2c creating the interface file iinclude stackch include stackTypeVariableh include versionh if SCIVERSIONMAJOR 5 if SCIVERSIONMINOR 2 error This example is obsolete see help ilibbuid endif endif extern int fun1 double x double y int intfun1char fname int m1n1l1 CheckRhs11 CheckLhs11 GetRhsVar1 MATRIXOFDOUBLEDATATYPE m1 n1 l1 fun1stkl1stkl1 LhsVar1 1 return 0 mputliintfun1c creating the shared library a gateway a Makefile and a loader are generated ilibbuild 1237 filesfun1cfun2cintfun1c ilibbuildilibcoldscifun1intfun1files load the shared library exec loadersce using the new primitive scifun133 Examples C code cd TMPDIR mkdirexampleilibbuildcpp cdexampleilibbuildcpp iinclude string extern C include stdlibh include stackch include apiscilabh include localizationh include Scierrorh int scicppfindchar fname SciErr sciErr int piAddressVarOne NULL char pStVarOne NULL int iType1 0 int lenStVarOne 0 int m1 0 n1 0 int piAddressVarTwo NULL char pStVarTwo NULL int iType2 0 int lenStVarTwo 0 int m2 0 n2 0 int mout 0 int nout 0 sciErr getVarAddressFromPositionpvApiCtx 1 piAddressVarOne ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddressVarOne iType1 ifsciErriErr printErrorsciErr 0 return 0 ilibbuild 1238 if iType1 scistrings Scierror999s Wrong type for input argument d A string expected fname 1 return 0 sciErr getVarAddressFromPositionpvApiCtx 2 piAddressVarTwo ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddressVarTwo iType2 ifsciErriErr printErrorsciErr 0 return 0 if iType2 scistrings Scierror999s Wrong type for input argument d A string expected fname 2 return 0 sciErr getMatrixOfStringpvApiCtx piAddressVarOne m1 n1 lenStVarOne pStVarOne ifsciErriErr printErrorsciErr 0 return 0 pStVarOne new charlenStVarOne 1 if pStVarOne NULL Scierror999s Memory allocation error fname return 0 sciErr getMatrixOfStringpvApiCtx piAddressVarTwo m2 n2 lenStVarTwo pStVarTwo ifsciErriErr printErrorsciErr 0 return 0 pStVarTwo new charlenStVarTwo 1 if pStVarTwo NULL Scierror999s Memory allocation error fname return 0 sciErr getMatrixOfStringpvApiCtx piAddressVarOne m1 n1 lenStVarOne pStVarOne ifsciErriErr ilibbuild 1239 printErrorsciErr 0 return 0 sciErr getMatrixOfStringpvApiCtx piAddressVarTwo m2 n2 lenStVarTwo pStVarTwo ifsciErriErr printErrorsciErr 0 return 0 stdstring myMessagepStVarOne stdstring searchpStVarTwo delete pStVarTwo delete pStVarOne double dOut 00 if myMessagefindsearch stdstringnpos dOut myMessagefindsearch The actual operation else dOut 1 Substring not found mout 1 nout 1 sciErr createMatrixOfDoublepvApiCtx Rhs 1 mout nout dOut ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 extern C mputliTMPDIR exampleilibbuildcppscicppfindcxx creating the shared library a gateway a Makefile and a loader are generated files scicppfindcxx ilibbuildilibbuildcppcppfindscicppfindfiles load the shared library exec loadersce Small test to see if the function is actually working if cppfindmy very long stringlong 8 pause end if cppfindmy very long stringvery 3 pause end if cppfindmy very long stringshort 1 pause end ilibbuild 1240 Examples C code previous Scilab API 52 cd TMPDIR mkdirexampleilibbuildcppold cdexampleilibbuildcppold iinclude string extern C include stackch include versionh if SCIVERSIONMAJOR 5 if SCIVERSIONMINOR 2 error This example is obsolete see help ilibbuid endif endif int scicppfindchar fname int m1 0 n1 0 l1 char inputString1 inputString2 int m2 0 n2 0 l2 int m3 0 n3 0 double position NULL Where we will store the position CheckRhs22 Check the number of input argument CheckLhs11 Check the number of output argument GetRhsVar1 c m1 n1 l1 Retrieve the first input argument inputString1cstkl1 GetRhsVar2 c m2 n2 l2 Retrieve the second input argument inputString2cstkl2 stdstring myMessage inputString1 stdstring search inputString2 m31n31 position new double1 if myMessagefindsearch stdstringnpos position0 myMessagefindsearch The actual operation else position0 1 Substring not found CreateVarFromPtrRhs1dm3n3position Create the output argument LhsVar1 Rhs1 delete position return 0 mputliscicppfindcxx creating the shared library a gateway a Makefile and a loader are generated filesscicppfindcxx ilibbuildfoooldcppfindscicppfindfiles load the shared library exec loadersce ilibbuild 1241 Small test to see if the function is actually working if cppfindmy very long stringlong 8 pause end if cppfindmy very long stringvery 3 pause end if cppfindmy very long stringshort 1 pause end Examples Fortran 90 code cd TMPDIR mkdirexampleilibbuildf90 cdexampleilibbuildf90 sourcecodesubroutine incrdoublef90xy implicit none double precision intentin x double precision intentout y yx1 end subroutine incrdoublef90 mputlsourcecodeincrdoublef90f90 libpathilibforlinkincrdoublef90incrdoublef90f90f exec loadersce n1 mcallincrdoublef90n1dout112d if absm2eps then pauseend n2 mcallincrdoublef90n1dout112d if absm3eps then pauseend See Also addinter link ilibcompile ilibgenMake ilibgengateway ilibgenloader ilibforlink Author Allan CORNET 1242 Name ilibcompile ilibbuild utility executes the Makefile produced by ilibgenMake libnilibcompilelibnamemakename filesldflagscflagsfflagscc Parameters libname a character string the generic name of the library without path and extension makename character string The path of the Makefile file without extension files optionnal vector of character strings If files is given the make is performed on each target con tained in files then a whole make is performed libn character string The path of the actual generated shared library file ldflagscflagsfflagscc character strings to provide optionsflags for the loader the C compiler the Fortran compiler cc provides the name of the compiler Description Utility function used by ilibbuild This executes the Makefile produced by ilibgenMake compiles the C and fortran files and generates the shared library Shared libraries can then be used with the link and addinter Scilab function for incrementaldy namic link Note that a compiler must be available on the system to use this function See Also addinter link ilibbuild ilibgenMake ilibgengateway ilibgenloader ilibforlink 1243 Name ilibforlink utility for shared library management with link libnilibforlinknamesfileslibsflag makename loadername libname ldflags cflags fflags cc Parameters names a string matrix giving the entry names which are to be linked files string matrix giving source from Scilab 50 or object files needed for shared library creation libs string matrix giving extra libraries needed for shared library creation flag a string flag c or f for C or Fortran entry points makename character string The pathname of the Makefile file without extension default value Makelib loadername character string The pathname of the loader file default value is loadersce libname optional character string The name of the generated shared library default value is and in this case the name is derived from names1 ldflags optional character string It can be used to add specific linker options in the generated Makefile Default value is cflags optional character string It can be used to add specific C compiler options in the generated Make file Default value is fflags optional character string It can be used to add specific Fortran compiler options in the generated Makefile Default value is cc optional character string It can be used to specify a C compiler Default value is libn character string The path of the really generated shared library file Description This tool is used to create shared libraries and to generate a loader file which can be used to dynamically load the shared library into Scilab with the link function New entry points given by names are then accessible through the call function or with non linear tools ode optim The file to compile are supposed to be located given by makename If makename sets a path different to the current directory loader script must be located in the same directory using the loadername variable Many examples are provided in SCImodulesdynamiclinkexamples directory They are all released into the public domain ilibforlink 1244 Note that a compiler must be available on the system to use this function Languages handle by this function are C C Fortran and Fortran 90 Examples C code if haveacompiler then chdirTMPDIR f1int ext1cint n double a double b double c int k for k 0 k n k ck ak bk return0 mputlf1fun1c creating the shared library a gateway a Makefile and a loader are generated ilibforlinkext1cfun1cc load the shared library exec loadersce using the new primitive a123b456n3 ccallext1cn1ia2db3dout134d if normcab eps then pauseend end See Also addinter link ilibcompile ilibgenMake ilibgengateway ilibgenloader ilibforlink 1245 Name ilibgenMake utility for ilibbuild produces a Makefile for building shared libraries MakenameilibgenMakenamefileslibsmakename withgatewayldflagscflagsfflagscc Parameters libname a character string the generic name of the library without path and extension files a vector of character string The names of the C or Fortran files without the extension and the path part libs a vector of character string additionnal libraries paths or makename character string The path of the Makefile file withgateway a boolean If true a file with name libnamegateway is added Default value is t ldflags a string It can be used to add specific linker options in the generated Makefile Default value is cflags a string It can be used to add specific C compiler options in the generated Makefile Default value is fflags a string It can be used to add specific Fortran compiler options in the generated Makefile Default value is cc a string The name of the C compiler Default value is the C compiler detected on the host Makename character string The path of the really generated Makefile file Description Utility function used by ilibbuild This function generates a Makefile adapted to the Operating System for building shared libraries to be loaded in Scilab Proper options and paths are set Shared libraries can then be used with the link and addinter scilab function for incrementaldy namic linking The shared library is build from a set of C or Fortran routines stored in a directory and if required from a set of external libraries Files are not required to exist when Makefile is generated but of course are required for executing the Makefile Only use this function is you know what you are doing it is a semiprivate function ilibgenMake 1246 See Also addinter link ilibbuild ilibcompile ilibgengateway ilibgenloader ilibforlink 1247 Name ilibgencleaner utility for ilibbuild generates a cleaner file ilibgencleanermakenameloadernamefiles Parameters makename character string The pathname of the Makefile file without extension default value Makelib loadername character string The pathname of the loader file default value is loadersce files matrix of character string files to delete Description Utility function used by ilibbuild and ilibforlink This function generates a cleaner file See Also ilibgenloader ilibbuild ilibforlink 1248 Name ilibgengateway utility for ilibbuild generates a gateway file ilibgengatewaynametable Parameters name a character string the generic name of the library without path and extension table 2 column string matrix giving the table of pairs scilabname interface name Description Utility function used by ilibbuild This function generates a gateway file used by addinter if WITHOUTAUTOPUTLHSVAR variable is defined and equals to t PutLhsVar will need to manage PutLhsVar in each interface as internal scilab functions In another case default for compatibility with previous version PutLhsVar is added in each interface You can also see SCIcontribtoolboxskeletonscigatewaycbuildergatewaycsce as example about WITHOUTAUTOPUTLHSVAR Example about WITHOUTAUTOPUTLHSVAR t cd TMPDIR WITHOUTAUTOPUTLHSVAR t name gwexample1 table scifunc1 func1 ilibgengatewaynametable generated gateway mgetlTMPDIRgwexample1c int scifunc1char fname your C code you need to add a explicit PutLhsVar as internal all gateways of scilab PutLhsVar return 0 Example about WITHOUTAUTOPUTLHSVAR f default cd TMPDIR WITHOUTAUTOPUTLHSVAR f ilibgengateway 1249 name gwexample2 table scifunc2 func2 ilibgengatewaynametable generated gateway mgetlTMPDIRgwexample2c int scifunc2char fname your code you do NOT need to add a explicit PutLhsVar added by scilab after call to scifunc2 default mode in scilab 4 return 0 See Also addinter link ilibbuild ilibcompile ilibgenMake ilibgenloader ilibforlink 1250 Name ilibgenloader utility for ilibbuild generates a loader file ilibgenloadernametablelibs Parameters name a character string the generic name of the library without path and extension table 2 column string matrix giving the table of pairs scilabname interface name libs a string matrix externals dynamic libraries filenames to load by loader file optional Description Utility function used by ilibbuild This function generates a loader file See Also addinter link ilibbuild ilibcompile ilibgenMake ilibgenloader ilibforlink 1251 Name ilibmexbuild utility for mex library management ilibmexbuildlibnametablefileslibs makenameldflagscflagsfflagscc Parameters libname a character string the generic name of the library without path and extension table 3 column string matrix giving the table of scilabname interface name cmex or fmex files string matrix giving objects files needed for shared library creation libs string matrix giving extra libraries needed for shared library creation makename character string The path of the Makefile file without extension ldflagscflagsfflagscc character strings to provide optionsflags for the loader the C compiler the Fortran compiler cc provides the name of the compiler Description This function is used to create mex libraries and to generate a loader file which can be used to dynam ically load the mex shared library Note that the file name containing the mex code can be set in the third input argument files or the second value of the table input argument Note that a compiler must be available on the system to use this function Examples cdTMPDIR mputlinclude mexh void mexFunctionint nlhs mxArray plhs int nrhs mxArray prhs int dims mxGetDimensionsprhs0 sciprintd d d dims0dims1dims2 mexfunction16c ilibmexbuildlibmexmexf16mexfunction16cmexMakelib execTMPDIRloadersce mexf16rand232 See Also addinter link ilibcompile ilibgenMake ilibgengateway ilibgenloader ilibforlink 1252 Name ilibverbose set level of display used by dynamic link functions level ilibverbose ilibverboselevel Parameters level level of verbose for dynamic link functions 0 no message 1 default level as previous version of scilab 2 maximum verbose level configure makefile debug information Description ilibverbose set level of display used by dynamic link functions All dynamic functions in dynamic link module check this value and display or not some informations Examples if haveacompiler then curverbose ilibverbose ilibverbose0 chdirTMPDIR f1int ext1cint n double a double b double c int k for k 0 k n k ck ak bk return0 mputlf1fun1c ilibforlinkext1cfun1cc exec loadersce using the new primitive a123b456n3 c callext1cn1ia2db3dout134d if normcab eps then pauseend ilibverbose1 f2int ext2cint n double a double b double c int k for k 0 k n k ck ak bk return0 ilibverbose 1253 mputlf2fun2c ilibforlinkext2cfun2cc exec loadersce using the new primitive a 123 b 456n 3 c callext2cn1ia2db3dout134d if normcab eps then pauseend ilibverbosecurverbose end See Also mode link ilibcompile ilibbuild ilibforlink Authors Allan CORNET 1254 Name link dynamic linker xlinkfiles subnamesflag linkx subnames flag ulinkx lstlinkshow lstlink Parameters files a character string or a vector of character strings the files names used to define the new entry point compiled routines user libraries system libraries subnames a character string or a vector of character strings Name of the entry points in files to be linked x an integer which gives the id of a shared library linked into Scilab with a previous call to link flag character string f or c for Fortran default or C code Description link is a incrementaldynamic link facility this command allows to add new compiled Fortran or C routines to Scilab executable code Linked routines can be called interactively by the function call Linked routines can also be used as external for eg non linear problem solvers ode optim intg dassl link returns a string matrix with linked functions a call to link returns an integer which gives the id of the shared library which is loaded into Scilab This number can then be used as the first argument of the link function in order to link additional function from the linked shared library The shared library is removed with the ulink command A routine can be unlinked with ulink If the linked function has been modified between two links it is required to ulink the previous instance before the new link linkshow returns the current linked routines To be able to link routines in a system independent way it is convenient to use the ilibforlink utility function instead of link Experienced users may also link a new Scilab interface routine to add a set of new functions See ilibbuild and addinter functions Number of link in a scilab session can be limited by the operating system On Windows you cannot load more than 80 dynamic libraries at the same time Examples Example of the use of ilibforlink with a simple C code cd TMPDIR f1include mathh link 1255 void foocdouble cdouble adouble bint mint n int i for i 0 i mn i ci sinai b mputlf1foocc creating the shared library a Makefile and a loader are generated the code is compiled and a shared library built ilibforlinkfoocfooccc display the loadersce file which calls link mprintfs mgetlloadersce load the shared library exec loadersce linkshow call the new linked entry point alinspace0pi10b5 y1callfooca2db3dsizea14isizea25ioutsizea1d check y1sinab exec cleanersce See Also call external clink addinter ilibforlink ilibbuild 1256 Name ulink unlink a dynamically linked shared object ulinkx ulink Description see link If you plan to use valgrind to profile your toolbox you must first set the environment variable PROFILESCILABDYNAMICLINK before starting scilab under bash shell export PROFILESCILABDYNAMICLINK1 export SCILABVALGRINDOPTdbattachno showbelowmainyes logfd2 logfilescilabtxt numcallers50 v tracerediryes readvarinfoyes tracechildrenyes showreachableyes smccheckall childsilentafterforkno leakcheckfull trackoriginsyes scilab nwni profile This environment variable force Scilab not to release the loaded dynamic libraries This will allow valgrind to perform its sumup analysis See Also link 1257 Name withlcc returns if LCCWin32 is the default C Compiler bOKwithlcc Parameters bOK returns T if LCCWin32 is the default C Compiler Description checks if LCCWin32 is the default C Compiler Examples bOKwithlcc Authors Allan CORNET Parte XVII Inteiros 1259 Name iconvert conversão para representação inteira de 1 a 4 bytes yiconvertXitype Parâmetros X matriz de floats ou inteiros y matriz de inteiros codificados em 1 2 ou 4 bytes Descrição Converte e armazena dados para inteiros de 1 2 ou 4 bytes itype0 retorna números em ponto flutuante itype1 retorna números int8 no intervalo 128127 itype11 retorna números uint8 no intervalo 0255 itype2 retorna números int16 no intervalo 3276832767 itype12 retorna números uint16 no intervalo 0 65535 itype4 retorna números int32 no intervalo 21474836482147483647 itype14 retorna números uint32 no intervalo 0 4294967295 Exemplos bint321 120 127 312 yiconvertb1 Ver Também double inttype 1260 Name int8 conversão para representação de inteiro de 1 byte int16 conversão para representação de inteiro de 2 bytes int32 conversão para representação de inteiro de 1 byte sem sinal uint8 conversão para representação de inteiro de 2 byte sem sinal uint16 conversão para representação de inteiro de 4 byte sem sinal uint32 conversão para representação de inteiro de 4 byte sem sinal yint8X yint16X yint32X yuint8X yuint16X yuint32X Parâmetros X matriz de números em ponto flutuante ou inteiros y matriz de inteiros codificados em 1 2 ou 4 bytes Descrição Converte e armazena dados em interos de 1 2 ou 4 bytes Estes tipos de dados são especialmente úteis para armazenar objetos grandes como imagens sinais longos yint8X retorna números no intervalo 128127 yuint8X retorna números no intervalo 0255 yint16X retorna números no intervalo 3276832767 yuint16X retorna números no intervalo 0 65535 yint32X retorna números no intervalo 21474836482147483647 yuint32X retorna números no intervalo 0 4294967295 Exemplos int81 120 127 312 uint81 120 127 312 xint32200100400 int8x Ver Também double inttype iconvert 1261 Name inttype tipos de dados inteiros iinttypex Parâmetros x uma matriz de inteiros ver int8 i inteiro Descrição inttypex retorna um inteiro que indica o tipo das entradas de x como segue 1 representação de inteiros de um byte 2 representação de inteiros de dois bytes 4 representação de inteiros de quatro bytes 11 representação de inteiros de um byte sem sinal 12 representação de inteiros de dois bytes sem sinal 14 representação de inteiros de quatro bytes sem sinal Exemplos xuint16110 inttypex Ver Também int8 Parte XVIII Interpolação 1263 Name bsplin3val função de avaliação de derivada arbitrária de spline 3d dfpbsplin3valxpypzptlder Parâmetros xp yp zp vetores ou matrizes de reais de tamanhos iguais tl tlist de tipo splin3d definindo um tensor spline 3d chamado de s a seguir der vetor com três componentes oxoyoz definindo qual derivada de s computar dfp vetor ou matriz de mesmo formato que xp yp e zp avaliação elemento a elemento da derivada especificada de s nesses pontos Descrição Enquanto a função interp3d pode computar apenas o spline s e suas primeiras derivadas bsplin3val pode computar qualquer derivada de s A derivada a ser computada é especificada pelo argumento deroxoyoz ox oy oz d d d dfpi s xpiypizpi ox oy oz dx dy dz Então der0 0 0 corresponde a s der1 0 0 to dsdx der0 1 0 to dsdy der1 1 0 to d2sdxdy etc Para um ponto com coordenadas xpiypizpi fora do grid a função retorna 0 Exemplos deffvfxyzvcosxsinycosz deffvfxxyzvsinxsinycosz deffvfxyxyzvsinxcosycosz deffvfxyzxyzvsinxcosysinz deffvfxxyzxyzvcosxcosysinz n 20 n x n x n pontos de interpolação x linspace02pin yx zx grid de interpolação XYZ ndgridxyz V fXYZ tl splin3dxyzV5 5 5 computando f e algumas derivadas em um ponto e comparando com o spline interpolante xp grand11unf02pi yp grand11unf02pi zp grand11unf02pi bsplin3val 1264 fe fxpypzp fi bsplin3valxpypzptl0 0 0 fxe fxxpypzp fxi bsplin3valxpypzptl1 0 0 fxye fxyxpypzp fxyi bsplin3valxpypzptl1 1 0 fxyze fxyzxpypzp fxyzi bsplin3valxpypzptl1 1 1 fxxyze fxxyzxpypzp fxxyzi bsplin3valxpypzptl2 1 1 Ver Também splin3d interp3d Autores RF Boisvert C De Boor código da biblioteca FORTRAN CMLIB B Pincon interface Scilab 1265 Name cshep2d bidimensional cubic shepard scattered interpolation tlcoef cshep2dxyz Parâmetros xyz uma matriz n x 3 dos pontos de interpolação interpolação sem grid a iésima linha dadas as coordenadas xy e então a altitude z do iésimo ponto de interpolação tlcoef uma estrutura tlist do Scilab do tipo cshep2d Descrição Esta função é útil para definir uma função de interpolação 2d quando os pontos não estão em um grid você pode usála para este caso mas splin2d é melhor para este propósito O interpolante é do tipo cúbico de Shepard e é uma função de duas variáveis de classe C2 duas vezes continuamente diferenciável sxy tal que sxiyizi para todo i1n xiyizi sendo a iésima linha de xyz A avaliação de s em alguns pontos deve ser feita pela função evalcshep2d Observação A função operea se n 10 se os nós não são todos colineares ie as coordenadas xy dos pontos de interpolação não estão na mesma reta e se não há nós duplicados ie dois ou mais pontos de interpolação com as mesmas coordenadas xy Há erro se essas condições não são respeitadas Exemplos interpolação de cosxcosy com pontos de interpolação escolhidos aleatoriamente n 150 número de pontos de interpolação xy grandn2unf02pi z cosxy1cosxy2 xyz xy z tlcoef cshep2dxyz avaliação em um grid m 30 xx linspace02pim XY ndgridxxxx Z evalcshep2dXY tlcoef xbasc plot3dxxxxZflag2 6 4 param3d1xy1xy2listz9 flag0 0 xtitleInterpolação cúbica de Shepard de cosxcosy com pontos de interpolação escolhidos aleatoriamente legendspontos de interpolação91 xselect Ver Também splin2d evalcshep2d cshep2d 1266 Autores Robert J Renka B Pincon interface do Scilab 1267 Name evalcshep2d avaliação por interpolação cúbica bidimensional de Shepard zp dzpdx dzpdy d2zpdxxd2zpdxyd2zpdyy evalcshep2dxp yp tlcoef Parâmetros xp yp dois vetores ou matrizes de mesmo tamanho tlcoef uma estrutura Scilab tlist de tipo cshep2d definindo uma função de interpolação cúbica de Shep ard chamada S a partir daqui zp vetor ou matrizes de mesmo tamanho que xp e yp avaliação do interpolante S nesses pontos dzpdxdzpdy vetores ou matrizes de mesmo tamanho que xp e yp avaliação das derivadas primeiras de S nestes pontos d2zpdxxd2zpdxyd2zpdyy vetores ou matrizes de mesmo tamanho que xp e yp avaliação das derivadas segundas de S nestes pontos Descrição Esta é a rotina de avaliação para a função de interpolação cúbica de Shepard obtida com cshep2d isto é zpi Sxpiypi dzpdxi dSdxxpiypi dzpdyi dSdyxpiypi d2zpdxxi d2Sdx2xpiypi d2zpdxyi d2Sdxdyxpiypi d2zpdyyi d2Sdy2xpiypi Observação O interpolante S é C2 duas vezes continuamente diferenciável mas também é estendido por zero para xy suficientemente longe dos pontos de interpolação Isto leva a uma descontinuidade em regiões exteriores muito longe dos pontos de interpolação e assim a avaliação não se torna incoveniente na prática de um modo geral avaliação fora dos pontos de interpolação ie extrapolação leva a resultados muito inacurados Exemplos ver seção de exemplos em cshep2d este exemplo mostra o comportamento longe dos pontos de interpolação deffzfxyz 1 50x1xy1y2 x linspace0110 XY ndgridxx evalcshep2d 1268 X X Y Y Z fXY S cshep2dX Y Z avaliação dentro e fora do quadrado 01x01 m 40 xx linspace1505m xpyp ndgridxxxx zp evalcshep2dxpypS computando faceta para definir uma cor para a região de extrapolação e outra para a região de interpolação xfyfzf genfac3dxxxxzp color 2ones1sizezf2 índices correspondentes à faceta na região de interpolação indfind meanxfr0 meanxfr1 meanyfr0 meanyfr1 colorind3 xbasc plot3dxfyflistzfcolor flag2 6 4 legendsregião de extrapolaçãoregião de interpolação2 31 xselect Ver Também cshep2d Autores Robert J Renka B Pincon interface Scilab 1269 Name interp função de avaliação de spline cúbico yp yp1 yp2 yp3interpxp x y d outmode Parâmetros xp vetor ou matriz de reais xyd vetores de reais de mesmo tamanho definindo uma função de spline cúbico ou subspline chama do s a partir daqui outmode opcional string definido a avaliação de s fora do intervalo x1xn yp vetor ou matriz de mesmo tamanho que xp avaliação elemento a elemento de s em xp ypisxpi ou ypijsxpij yp1 yp2 yp3 vetores ou matrizes de mesmo tamanho que xp avaliação elemento a elemento das derivadas sucessivas de s em xp Descrição Dados três vetores xyd ddefinindo uma função de spline cúbico ou supspline ver splin com yisxi di sxi esta função avalia s e s s s se necessário em xpi ypi sxpi ou ypij sxpij yp1i sxpi ou yp1ij sxpij yp2i sxpi ou yp2ij sxpij yp3i sxpi ou yp3ij sxpij O parâmetro outmode ajusta a regra de avaliação para extrapolação ie para xpi fora de x1xn byzero uma extrapolação por zero é feita bynan extrapolação por NaN C0 a extrapolação é definida como segue sx y1 para x x1 sx yn para x xn natural a extrapolação é definida como segue pi sendo o polinômio que define s em xixi1 interp 1270 sx p1x para x x1 sx pn1x para x xn linear a extrapolação é definida como segue sx y1 sx1xx1 para x x1 sx yn sxnxxn para x xn periodic s é estendido por periodicidade Exemplos veja os exemplos de splin e lsqsplin um exemplo exibindo as continuidades C2 e C1 de um spline e um subspline a 8 b 8 x linspaceab20 y sincx dk splinxy notaknot df splinxy fast xx linspaceab800 yyk yy1k yy2k interpxx x y dk yyf yy1f yy2f interpxx x y df xbasc subplot311 plot2dxx yyk yyf plot2dx y style9 legendsspline não é um nósubspline rápidopontos de interpolação 1 2 9 urf xtitleinterpolação por spline subplot312 plot2dxx yy1k yy1f legendsspline não é um nósubspline rápido 1 2 urf xtitleinterpolação por spline derivadas subplot313 plot2dxx yy2k yy2f legendsspline não é um nósubspline rápido 1 2 lrf xtitleinterpolação por splines segundas derivadas aqui está um exemplo mostrando as diferentes possibilidades de extrapolação x linspace0111 y coshx05 d splinxy xx linspace0515401 yy0 interpxxxydC0 yy1 interpxxxydlinear yy2 interpxxxydnatural yy3 interpxxxydperiodic xbasc plot2dxxyy0 yy1 yy2 yy3style25frameflag2legC0linearnaturalperiodic xtitle Modos diferentes de avaliar um spline fora de seu domínio interp 1271 Ver Também splin lsqsplin Autor B Pincon 1272 Name interp1 função de interpolação 1d ypinterp1x yxp methodextrapolation Parâmetros xp escalar real vetor ou matriz ou hipermatriz de reais x vetor de reais method opcional string definindo o método de interpolação extrapolation opcional string ou valor real defindo os componentes ypj para os valores xpj fora do intervalo x1xn yp vetor ou matriz ou hipermatriz Descrição Dados xyxp esta função faz corresponder os yp componentes aos xp por interpolação linear por padrão definida por x e y Se yp é um vetor então o comprimento de xp é igual ao comprimento de yp Se yp é uma matriz então xp tem o mesmo comprimento que cada uma das colunas de yp Se yp é uma hipermatriz então o comprimento de xp é o mesmo da primeira dimensão de yp Se sizeyCM1M2M3Mj e sizexp N1N2N3Nk então sizeyp N1N2NkM1M2Mj e o comprimento de x deve ser igual a sizey1 O parâmetro method ajusta a regra avaliação para interpolação linear a interpolação é definida pelo método linear ver interpln spline definição de interpolação por spline cúbico ver splin interp nearest para cada valor xpj ypj toma o valor ou yi correspondente ao xi o vízinho mais próximo de xpj O parâmetro extrapolation ajusta a regra de avaliação para extrapolação ie para xpi fora do intervalo x1xn extrap a extrapolação é realizada pelo método definido ypinterp1xyxpmethodextrap valor real você pode escolher um valor real para extrapolação Deste modo ypi toma este valor para xpi fora do intervalo x1xn por exemplo 0 mas também nan ou inf yiinterp1xyxpmethod 0 interp1 1273 por padrão a extrapolação é realizada pelo método definido para método spline e por nan para os métodos linear e nearest ypinterp1xyxpmethod Exemplos xlinspace0320 yx2 xxlinspace03100 yy1interp1xyxxlinear yy2interp1xyxxspline yy3interp1xyxxnearest plotxxyy1yy2yy3xy xtitleinterpolation of square function legendlinearsplinenearesta2 Ver Também interp interpln splin Autor FB 1274 Name interp2d função de avaliação spline bicúbica 2d zpdzpdxdzpdyd2zpdxxd2zpdxyd2zpdyyinterp2dxpypxyC outmode Parâmetros xp yp vetores ou matrizes de reais de mesmo tamanho xyC vetores de reais definindo uma função de spline bicúbico ou subspline chamada s daqui em diante outmode opcional string definindo a avaliação de s fora de x1xnxxy1yny zp vetor ou matriz com o mesmo formato que xp e yp avaliação elemento a elemento de s nestes pontos dzpdx dzpdy vetores ou matrizes de mesmo formato que xp e yp avaliação elemento a elemento das derivadas primeiras de s nesses pontos d2zpdxx d2zpdxy d2zpdyy vetores ou matrizes de mesmo formato que xp e yp eavaliação elemento a elemento das derivadas segundas de s nesses pontos Descrição Dados três vetores xyC definindo uma função de subspline ou spline bicúbico ver splin2d esta função avalia s e dsdx dsdy d2sdxx d2sdxy d2sdyy se necessário em xpiypi zpi sxpiypi dzpdxi dsdxxpiypi dzpdyi dsdyxpiypi d2zpdxxi d2sdx2xpiypi d2zpdxyi d2sdxdyxpiypi d2zpdyyi d2sdy2xpiypi O parâmetro outmode define a regra de avaliação para extrapolação ie para xpiypi fora de x1xnxxy1yny byzero uma extrapolação por zero é realizada bynan extrapolação por NaN C0 Extrapolação definida como segue sxy sprojxy onde projxy é o ponto mais próximo em x1xnxxy1yny de xy interp2d 1275 natural a extrapolação é realizada utilizando o elemento de área bicúbico mais próximo de xy periodic s é estendida por periodicidade Exemplos veja os exemplos de splin2d este exemplo mostra características de extrapolações diferentes interpolação de cosxcosy n 7 um grid de interpolação n x n x linspace02pin y x z cosxcosy C splin2dx y z periodic agora avaliando em um domínio maior que 02pix 02pi m 80 parâmetro de discretização do grid de avaliação xx linspace05pi25pim yy xx XXYY ndgridxxyy zz1 interp2dXXYY x y C C0 zz2 interp2dXXYY x y C byzero zz3 interp2dXXYY x y C periodic zz4 interp2dXXYY x y C natural xbasc subplot221 plot3dxx yy zz1 flag2 6 4 xtitleExtrapolação com o outmode C0 subplot222 plot3dxx yy zz2 flag2 6 4 xtitleExtrapolação com o outmode byzero subplot223 plot3dxx yy zz3 flag2 6 4 xtitleExtrapolação com o outmode periodic subplot224 plot3dxx yy zz4 flag2 6 4 xtitleExtrapolação com o outmode natural xselect Ver Também splin2d Autor B Pincon 1276 Name interp3d função de avaliação spline 3d fpdfpdxdfpdydfpdzinterp3dxpypzptloutmode Parâmetros xp yp zp vetores ou matrizes de reais de mesmo tamanho tl tlist do tipo splin3d definindo um tensor spline 3d chamado s a partir daqui outmode opcional string definindo a avaliação de s fora do grid xminxmaxxyminymaxxzminzmax fp vetor ou matriz de mesmo formato que xp yp e zp avaliação elemento a elemento de s onesses pontos dfpdx dfpdy dfpdz vetores ou matrizes de mesmo formato que xp yp e zp avaliação elemento a elemento das primeiras derivadas de s nesses pontos Descrição Dada uma tlist tl definindo uma função spline 3d ver splin3d esta função avalia s e dsdx dsdy dsdz se necessário em xpiypizpi zpi sxpiypi dzpdxi dsdxxpiypizpi dzpdyi dsdyxpiypizpi dzpdzi dsdzxpiypizpi O parâmetro outmodedefine a regra de avaliação para extrapolação ie para xpiypizpi fora de xminxmaxxyminymaxxzminzmax byzero uma extrapolação por zero é feita bynan extrapolação por NaN não é número C0 a extrapolação definida como segue sxy sprojxy onde projxy é o ponto mais próximo em x1xnxxy1yny de xy periodic s é estendido por periodicidade interp3d 1277 Exemplos veja exemplos na página da função splin3d Ver Também splin3d bsplin3val Autores RF Boisvert C De Boor código da biblioteca FORTRAN CMLIB B Pincon interface Scilab 1278 Name interpln interpolação linear yinterplnxydx Parâmetros xyd matriz de duas linhas coordenadas xy dos pontos x vetor de abscissas y vetor de ordenadas Descrição Dado xyd um conjunto de pontos no plano xy de abscissas crescentes e x aum conjunto de abscissas esta função computa y os valores correspondentes às ordenadas por interpolação linear Exemplos x1 10 20 30 40 y1 30 10 20 40 plot2dxy3011 10405050 yiinterplnxy445 plot2d445yi3000 Ver Também splin interp smooth 1279 Name intsplin integração de dados experimentais por interpolação por spline v intsplinx s Parâmetros x vetor de dados de coordenadas x crescentes O valor padrão é 1sizey s vetor de dados de coordenadas y v valor da integral Descrição Computa Onde f é uma função descrita por um conjunto de valores experimentais sifxi e x0x1 x1xn Entre os pontos da malha a função é interpolada usandose splines Exemplos t001pi intsplintsint Ver Também intg integrate inttrap splin 1280 Name linearinterpn interpolação linear ndimensional vp linearinterpnxp1xp2xpn x1 xn v outmode Parâmetros xp1 xp2 xpn vetores de reais ou matrizes de mesmo tamanho x1 x2 xn vetores linhas estritamente crescentes com pelo menos 2 elementos definindo o grid de interpolação ndimensional v vetor caso n1 matriz caso n2 ou hipermatriz caso n 2 com valores da função subjacente interpolada nos pontos do grid outmode opcional string definindo a avaliação fora do grid extrapolação vp vetor ou matriz de mesmo tamanho que xp1 xpn Descrição Dado um grid ndimensional definido pelos n vetores x1 x2 xn e os valores v de uma função aqui nomeada f nos pontos do grid vi1i2in fx1i1x2i2 xnin esta função computa o interpolante linear de f do grid chamado de s a partir daqui nos pontos nos quais as coordenadas são definidas pelos vetores ou matrizes xp1 xp2 xpn vpi sxp1ixp2i xpni or vpij sxp1ijxp2ij xpnij caso xpk sejam matrizes O parâmetro outmode ajusta a regra para extrapolação se notarmos Pixp1ixp2ixpni então outmode define a regra de avaliação quando Pi está fora de x11 x1 x x21 x2 x x xn1 xn As escolhas são byzero uma extrapolação por zero é feita bynan uma extrapolação por NaN C0 a extrapolação é definida como segue linearinterpn 1281 sP sprojP onde projP é o ponto mais próximo de P localizado na fronteira do grid natural a extrapolação é feita usando o remendo nlinear mais próximo do ponto periodic s é estendido por periodicidade Exemplos exemplo 1 interpolação linear 1d x linspace02pi11 y sinx xx linspace2pi4pi400 yy linearinterpnxx x y periodic xbasc plot2dxxyystyle2 plot2dxystyle9 strf000 xtitleInterpolação linear de sinx com 11 pontos de interpolação exemplo 2 interpolação bilinear n 8 x linspace02pin y x z 2sinxsiny xx linspace02pi 40 xpyp ndgridxxxx zp linearinterpnxpyp x y z xbasc plot3dxx xx zp flag2 6 4 xgyg ndgridxx param3d1xgyg listz9ones1n flag0 0 xtitleInterpolação bilinear de 2sinxsiny legendspontos de interpolação91 xselect exemplo 3 interpolação bilinear e experimentação com todos os tipos de outmode nx 20 ny 30 x linspace01nx y linspace02 ny XY ndgridxy z 04cos2piXcospiY nxp 60 nyp 120 xp linspace0515 nxp yp linspace0525 nyp XPYP ndgridxpyp zp1 linearinterpnXP YP x y z natural zp2 linearinterpnXP YP x y z periodic zp3 linearinterpnXP YP x y z C0 zp4 linearinterpnXP YP x y z byzero zp5 linearinterpnXP YP x y z bynan xbasc subplot231 plot3dx y z legxyz flag 2 4 4 xtitlefunção inicial 04 cos2 pi x cospi y linearinterpn 1282 subplot232 plot3dxp yp zp1 legxyz flag 2 4 4 xtitleNatural subplot233 plot3dxp yp zp2 legxyz flag 2 4 4 xtitlePeriodic subplot234 plot3dxp yp zp3 legxyz flag 2 4 4 xtitleC0 subplot235 plot3dxp yp zp4 legxyz flag 2 4 4 xtitlebyzero subplot236 plot3dxp yp zp5 legxyz flag 2 4 4 xtitlebynan xselect exemplo 4 interpolação trilinear ver ajuda de splin3d que tem os mesmos exemplos com interpolação por spline tricúbico execSCIdemosinterpinterpdemosci func vx052 y053 z052 deffvfxyzfunc n 5 x linspace01n yx zx XYZ ndgridxyz V fXYZ computando e exibindo o interpolante linear em algumas fatias m 41 dir z z z x y val 01 05 09 05 05 ebox 0 1 0 1 0 1 XF YF ZF VF for i 1lengthval XmXpYmYpZmZp sliceparallelepipeddiri vali ebox m m m Vm linearinterpnXmYmZm x y z V xfyfzfvf nf3dqXmYmZmVm1 XF XF xf YF YF yf ZF ZF zf VF VF vf Vp linearinterpnXpYpZp x y z V xfyfzfvf nf3dqXpYpZpVp1 XF XF xf YF YF yf ZF ZF zf VF VF vf end nbcol 128 vmin minVF vmax maxVF color dsearchVFlinspacevminvmaxnbcol1 xsetcolormapjetcolormapnbcol xbasc xsethidden3dxgetbackground colorbarvminvmax plot3dXF YF listZFcolor flag1 6 4 xtitleInterpolação trilinear defunc xselect Ver Também interpln splin splin2d splin3d Autor 1284 Name lsqsplin ajuste ponderado por spline cúbico de mínimos quadrados y d lsqsplinxd yd wd x Parâmetros xd yd vetores de mesmo tamanho dados a serem ajustados por um spline cúbico wd opcional um vetor de mesmo formato que xd e yd pesos dos ajustes de mínimos quadrados x vetor linha ou coluna estritamente crescente pontos de interrupção do spline cúbico y d vetores de mesmo formato que x a triplaxyd define o spline cúbico aproximado Descrição Esta função computa um spline cúbico aproximado s para os dados xd yd wd a partir daqui m é suposto como o comprimento desses vetores e de uma escolha dos pontos de interrupção do spline o vetor x por exemplo se você deseja n pontos de interrupção uniformemente escolhidos você pode usar xlinspaceminxdmaxxdn Se S é o espaço de todas as funções spline cúbicas com pontos de interrupção x1 x2 xn então o spline resultante s é tal que m m 2 2 wdk sxdk ydk wdk fxdk ydk k1 k1 para todo f em S ie realiza o mínimo da soma de todos os erros quadrados sobre todas as funções de S O spline s é completamente definido pela tripla xyd y e d são os vetores das ordenadas dos splines e das derivadas primeiras nos xi s yisxi e disxi e sua avaliação em alguns pontos deve ser feita pela função interp Observações Quando wd não é dado todos os pontos têm o mesmo peso 1 Um ponto xdkydk é considerado no ajuste se xdk em x1xn e wdk 0 Em particular você pode colocar um peso nulo ou mesmo negativo a todos os pontos que você deseja que sejam igno rados no ajuste Quando o número total de pontos levados em conta no procedure de ajuste é estri tamente menor que 4 ocorre um erro O vetor xd não necessita estar em ordem crescente Dependendo do número e das posições dos xdk s e da escolha dos xi s podem haver várias soluções mas apenas uma é selecionada Quando isso ocorre um aviso é exibido na janela de comando do Scilab Esta função foi feita para ser usada quando m é muito maior que n e neste caso tal tipo de problema não ocorre lsqsplin 1285 Exemplos este é um exemplo artificial onde os dados xd e yd são contruídos a partir de uma função seno perturbada a 0 b 2pi sigma 01 desvio padrão do ruído gaussiano m 200 número de pontos experimentais xd linspaceabm yd sinxd grandxdnor0sigma n 6 número de pontos de interrupção x linspaceabn computando o spline y d lsqsplinxd yd x usando pesos iguais plotando ye sinxd ys interpxd x y d xbasc plot2dxdye yd ysstyle2 2 3 legfunção exatamedidas experimentais perturbação gaussianaspline ajustado xtitleUm spline de mínimos quadrados xselect Ver Também interp splin Autores C De Boor AH Morris código da biblioteca FORTRAN NSWC B Pincon interface Scilab e ligeiras modificações 1286 Name smooth suavização por funções splines ptsmoothptd step Parâmetros ptd vetor de reais 2xn step real passo de discretização das abscissas pt vetor de reais 2xn Descrição Esta função computa a interpolação por funções splines para um dado conjunto de pontos no plano As coordenadas são ptd1iptd2i Os componentes ptd1 devem estar em ordem crescente O valor padrão para o para step é absmaxiptd1miniptd1100 Exemplos x1 10 20 30 40 y1 30 10 20 40 plot2dxy3011 10405050 yismoothxy01 plot2dyi1yi21000 Ver Também splin interp interpln 1287 Name splin interpolação por spline cúbico d splinx y splinetype der Parâmetros x um vetor linha ou coluna estritamente crescente x deve ter pelo menos dois componentes y um vetor com o mesmo formato que x splinetype opcional um string selecionando o tipo de spline a ser computado der optional um vetor com dois componentes com as derivadas nas extremidades a ser fornecido quando splinetypeclamped d vetor com o mesmo formato que x di é a derivada do spline em xi Descrição Esta função computa o spline cúbico ou subspline s que interpola os pontos xiyi ie temos sxiyi para todo i1n O spline resultante s é completamente definido pela tripla xyd onde d é o vetor com as derivadas nos xi sxidi esta forma é chamada de forma de Hermite ou hermitiana A avaliação do spline em alguns pontos deve ser feita pela função interp Vários tipos de splines podem ser computados selecionando o parâmetro splinetype apropriado notaknot este é o caso padrão o spline cúbico é computado sob as seguintes condições considerando n pontos x1xn sx2 sx2 sxn1 sxn1 clamped neste caso o spline cúbico é computado usando derivadas nas extremidades do intervalo que devem ser fornecidas como último argumento der sx1 der1 sxn der2 natural o spline cúbico é computado sob as seguintes condições sx1 0 sxn 0 periodic um spline cúbico periódico é computado y deve verificar y1yn sob as seguintes condições splin 1288 sx1 sxn sx1 sxn monotone neste caso um subspline s é apenas uma vez continuamente diferenciável é computado usando um esquema local para os di tais que s é monótono em cada intervalo if yi yi1 s é crescente em xi xi1 if yi yi1 s é decrescente em xi xi1 fast neste caso um subspline também é computado usando um esquema local simples para os di di é a derivada em xi da interpolação polinomial xi1yi1 xiyixi1yi1 exceto pelas extremidades d1 sendo computado a partir dos 3 pontos mais à esquerda e dn dos 3 pontos mais à direita fastperiodic é o mesmo que o anterior mas também usa uma fórmula centrada para d1 sx1 dn sxn através da periodicidade da função subjacente y deve verificar y1yn Observações De um ponto de vista de precisão use essencialmente o tipo clamped se você conhece as derivadas nas extremidades de outro modo use notaknot Mas se a função subjacente aproximada é periódica use o tipo periodic Sob boas suposições estes tipos de spline têm um comportamento assintótico Oh4 do erro Não use o tipo natural a não ser que a função subjacente possua zero derivadas segundas nas extremidades Os tipos monotone fast ou fastperiodic podem ser úteis e alguns caso por exemplo para limitar oscilações estes tipos de subsplines têm um comportamento assintótico Oh3 do erro Se n2 e splinetype não é clamped é usada interpolação linear Se n3 e splinetype é notaknot então um subspline tipo fast é computado na verdade Exemplos exemplo 1 deffyrungexy1 1 x2 a 5 b 5 n 11 m 400 x linspacea b n y rungex d splinx y xx linspacea b m yyi interpxx x y d yye rungexx xbasc plot2dxx yyi yye style2 5 leginterpolação porfunção exata plot2dx y 9 xtitleIntepolação da função de Runge exemplo 2 mostra comportamento de splines diferentes em dados aleatórios a 0 b 1 intervalo de interpolação n 10 número de pontos de interpolação splin 1289 m 800 discretização para avaliação x linspaceabn abscissas dos pontos de interpolação y randx ordenadas dos pontos de interpolação xx linspaceabm yk interpxx x y splinxynotaknot yf interpxx x y splinxyfast ym interpxx x y splinxymonotone xbasc plot2dxx yf ym yk style5 2 3 strf121 legfastmonotonespline not a knot plot2dxy9 strf000 para mostrar pontos de interpolação xtitleVários splines e subsplines em dados aleatórios xselect Ver Também interp lsqsplin Autores B Pincon F N Fritsch rotina pchimf Slatec é usada para interpolação monótona 1290 Name splin2d interpolação por spline bicúbico em grides 2d C splin2dx y z splinetype Parâmetros xy vetores linhas estritamente crescentes com pelo menos dois componentes definindo o grid de interpolação z nmatriz nx x ny nx sendo o comprimento de x e ny o comprimento de y splinetype opcional um string selecionando o tipo de spline bicúbico a ser computado C um vetor grande com coeficientes dos elementos de área bicúbicos veja detalhes em Observações Descrição Esta função computa um spline ou subspline bicúbico s que interpola os pontos xiyjzij ie temos sxiyjzij para todo i1nx e j1ny O spline resultante s é definido pela tripla xyC onde C é o vetor com comprimento 16nx1ny1 com os coeficientes de cada um dos nx1ny1 elementos de área bicúbicos em xi xi1xyj yj1 s é definido por 4 4 k1 l1 sxy C kl x xi y yj ij k1 l1 A avaliação de s em alguns pontos deve ser feita pela função interp2d Vários tipos de splines podem ser computados selecionando o parâmetro splinetype apropriado O método usada para com putar os splines ou subspline bicúbicos é o mesmo do antigo ie computar em cada ponto do grid xiyj uma aproximação das derivadas primeiras dsdxxiyj e dsdyxiyj e das derivadas cruzadas d2sdxdyxiyj Estas derivadas são computadas pelo modo dos esquemas do spline 1d levando a uma função de classe C2 s é duas vezes continuamente diferenciável ou através de um esquema de aproximação local levando a uma função de classe C1 apenas Este esquema é selecionado através do parâmetro splinetype ver splin para detalhes notaknot é o caso padrão periodic usado se a função subjacente é periódica devese ter z1j znxj para todo j em 1ny e zi1 ziny para i em 1nx mas isto não é verificado pela interface Observações De um ponto de vista de precisão use essencialmente o tipo notaknot ou periodic se a função interpolada subjacente é periódica splin2d 1291 Os tipos natural monotone fast ou fastperiodic podem ser úteis em alguns casos por exemplo para limitar oscilações monotone é o mais poderoso para isso Para obter coeficientes dos remendos bicúbicos de um modo mais amigável você pode usar c hypermat44nx1ny1C então o coeficiente kl do remendo ij ver equação aqui antes é armazenado em cklij Não obstante a função interp2d espera pelo vetor grande C e não pela hipermatriz c note que se pode recuperar facilmente C de c com Cc Exemplos exemplo 1 interpolação de cosxcosy n 7 um grid regular com n x n pontos de interpolação será usado x linspace02pin y x z cosxcosy C splin2dx y z periodic m 50 parâmetro de discretização do grid de avaliação xx linspace02pim yy xx XXYY ndgridxxyy zz interp2dXXYY x y C emax maxabszz cosxxcosyy xbasc plot3dxx yy zz flag2 4 4 XY ndgridxy param3d1XYlistz9ones1n flag0 0 str msprintf com d x d pontos de interpolação ermax gnnemax xtitleInterpolação por spline de cosxcosystr exemplo 2 diferentes funções de interpolação em dados aleatórios n 6 x linspace01n y x z randnn np 50 xp linspace01np yp xp XP YP ndgridxpyp ZP1 interp2dXP YP x y splin2dx y z notaknot ZP2 linearinterpnXP YP x y z ZP3 interp2dXP YP x y splin2dx y z natural ZP4 interp2dXP YP x y splin2dx y z monotone xsetcolormap jetcolormap64 xbasc subplot221 plot3d1xp yp ZP1 flag2 2 4 xtitlenotaknot subplot222 plot3d1xp yp ZP2 flag2 2 4 xtitlebilinear interpolation subplot223 plot3d1xp yp ZP3 flag2 2 4 xtitlenatural subplot224 plot3d1xp yp ZP4 flag2 2 4 xtitlemonotone xselect exemplo 3 spline notaknot e subspline monotone em uma função de degraus splin2d 1292 a 0 b 1 c 025 d 075 criando grid de interpolação n 11 x linspaceabn ind findc lt x amp x lt d z zerosnn zindind 1 um degrau dentro de um quadrado criando grid de avaliação np 220 xp linspaceab np XP YP ndgridxp xp zp1 interp2dXP YP x x splin2dxxz zp2 interp2dXP YP x x splin2dxxzmonotone plot xbasc xsetcolormapjetcolormap128 subplot121 plot3d1xp xp zp1 flag2 6 4 xtitlespline notaknot subplot122 plot3d1xp xp zp2 flag2 6 4 xtitlesubspline monotone Ver Também cshep2d linearinterpn interp2d Autor B Pincon 1293 Name splin3d interpolação spline em grides 3d tl splin3dx y z v order Parâmetros xyz vetores linhas estritamente crescentes cada um com pelo menos três componentes definindo o grid de interpolação 3d v uma hipermatriz nx x ny x nz nx ny nz sendo de comprimentos de x y e z respectivamente order opcional um vetor 1x3 kxkykz dada a ordem do tensor spline em cada direção o padrão é 444 ie spline tricúbico tl um tlist do tipo splin3d definindo o spline Descrição Esta função computa um spline tensor 3d s que interpola os pontos xiyjzkvijk ie temos sxiyjzkvijk para todo i1nx j1ny e k1nz O spline resultante s é definido por tl que consiste em uma representação Btensorspline de s A avaliação de s em alguns pontos deve ser feita pela função interp3d para computar s e suas derivadas primeiras ou pela função bsplin3val para computar uma derivada arbitrária de s Vários tipos de splines podem ser computados selecionando a ordem dos splines em cada direção orderkxkykz Observação Esta função funciona sob as condições nx ny nz 3 2 kx nx 2 ky ny 2 kz nz Há erro quando estas condições não são respeitadas Exemplos exemplo 1 func vcos2pixsin2piycos2piz deffvfxyzfunc n 10 n x n x n pontos de interpolação x linspace01n yx zx grid de interpolação XYZ ndgridxyz V fXYZ tl splin3dxyzV5 5 5 splin3d 1294 m 10000 computando um erro aproximado xp grandm1def yp grandm1def zp grandm1def vpexact fxpypzp vpinterp interp3dxpypzp tl er maxabsvpexact vpinterp tente agora com n20 e veja o erro exemplo 2 veja a página de ajuda de linearinterpn que contém o mesmo exemplo com interpolação trilinear execSCImodulesinterpolationdemosinterpdemosci func vx052 y053 z052 deffvfxyzfunc n 5 x linspace01n yx zx XYZ ndgridxyz V fXYZ tl splin3dxyzV computando e exibindo o spline interpolante 3d em algumas fatias m 41 dir z z z x y val 01 05 09 05 05 ebox 0 1 0 1 0 1 XF YF ZF VF for i 1lengthval XmXpYmYpZmZp sliceparallelepipeddiri vali ebox m m m Vm interp3dXmYmZm tl xfyfzfvf nf3dqXmYmZmVm1 XF XF xf YF YF yf ZF ZF zf VF VF vf Vp interp3dXpYpZp tl xfyfzfvf nf3dqXpYpZpVp1 XF XF xf YF YF yf ZF ZF zf VF VF vf end nbcol 128 vmin minVF vmax maxVF color dsearchVFlinspacevminvmaxnbcol1 xsetcolormapjetcolormapnbcol xbasc xsethidden3dxgetbackground colorbarvminvmax plot3dXF YF listZFcolor flag1 6 4 xtitleinterpolação por spline 3d da função func xselect Ver Também linearinterpn interp3d bsplin3val Autores RF Boisvert C De Boor código da biblioteca FORTRAN CMLIB B Pincon interface Scilab Parte XIX Funções de EntradaSaída 1296 Name file Gerenciamento de arquivos unit errfileopen filename status access recl format fileactionunit units typ nams mod swap fileunit Parâmetros filename string nome o arquivo a ser aberto status string o status do arquivo a ser aberto new o arquivo não deve existir novo arquivo padrão old o arquivo já deve existir unknown status desconhecido scratch o arquivo deve ser deletado ao fim da sessão access string o tipo de acesso ao arquivo sequential acesso seqüencial padrão direct acesso direto format string formatted para um arquivo formatado padrão unformatted registro binário recl inteiro é o tamanho de registros quando accessdirect unit inteiro descritor de unidade lógica do arquivo aberto units vetor de inteiros descritores de unidades lógicas dos arquivos abertos As unidades 5 e 6 são reservadas pelo sistema para dispositivos de entrada e saída typs vetor de strings tipo C ou Fortran dos arquivos abertos nams vetor de strings endereços dos arquivos abertos file 1297 mod modo de abertura de arquivo Formado por três dígitos abc Arquivos Fortran a 0 significa formatado e 1 não formatado binário b 0 significa acesso sequencial e 1 acesso direto c 0 significa new 1 significa old 2 significa scratch e 3 significa unknown Arquivos C a 1 significa r leitura 2 significa w escrita e 3 significa a anexação b é 1 se o arquivo foi aberto pelo modo atualização c é 1 se o arquivo foi aberto pelo modo b binário swap alavanca de troca automática swap1 se a troca automática estiver ativada swap é sempre 0 para arquivos Fortran err inteiro número de mensagem de erro ver error se a abertura falha Se err for omitido uma mensagem de erro aparece action é um dos seguintes strings close fecha os arquivos fornecidos pelos descritores de unidades lógicas fornecidos em units rewind coloca o ponteiro no início do arquivo backspace coloca o ponteiro no início do último registro last coloca o ponteiro após o último registro Descrição Seleciona uma unidade lógica unit e gerencia o arquivo filename unit errfileopen filename status access re clformat permite abrir um arquivo com propriedades especificadas e obter o número de unidade associado unit Este número de unidade pode ser utilizado para ações futuras no arquivo ou como descritor de arquivo em chamadas às funções read write readb writbsave load fileactionunit permite fechar o arquivo ou mover o ponteiro do arquivo corrente file retorna os descritores de unidades lógicas dos arquivos abertos So fileclosefile fecha todos os arquivos do usuário abertos tipo C ou Fortran file 1298 Exemplos ufileopenTMPDIRfoounknown for k14 arand14 writeua end filerewindu xreadu24 filecloseu u1fileopenTMPDIRfoounknown u2mopenTMPDIRfoo1wb unitstypsnamsfile filecloseu1 mcloseu2 Ver Também save load write read writb readb uigetfile mopen mclose 1299 Name getenv retorna o valor de uma variável de ambiente envgetenvstr rep Parâmetros str string especificando o nome da variável de ambiente rep um string opcional Quando este valor opcional é usado a função getenv retorna o valor rep quando a variável de ambiente str não é encontrada env string que contém o valor da variável de ambiente Descrição Retorna o valor de uma variável de ambiente se existir Exemplos getenvSCI getenvFOOfoo 1300 Name getio retorno de unidades lógicas de entradasaída do Scilab iosgetio Parâmetros ios um vetor rio rte wio wte rio unidade lógica corrente para leitura de instruções rte unidade lógica designada para entrada na janela do Scilab wio unidade lógica relativa ao arquivo de diário se houer wio0 significa que nenhum arquivo de diário foi aberto wte unidade lógica designada para saída na janela do Scilab Descrição getio retorna unidades lógicas designadas para entrada e saída principais no Scilab Ver Também file exec 1301 Name getpid Retorna o identificador do processo Scilab idgetpid Descrição Retorna retorna um inteiro correspondente ao identificador do processo Scilab Exemplos dSDstringgetpid 1302 Name getscilabkeywords retorna uma lista com todas as palavraschave do Scilab listkeywordsgetscilabkeywords Parâmetros listkeywords uma lista Descrição listkeywords1 primitivas listkeywords2 comandos listkeywords3 variáveis predefinidas listkeywords4 funções Scilab listkeywords5 funções Scicos Autores AC adaptado do código de Enrico Segres no Scipad 1303 Name halt para execução halt halta message Descrição Para execução até a entrada de algo no teclado Exemplos haltPress a key halt Ver Também pause return exec 1304 Name host execução de comandos do Unix ou DOS stathostcommandname Parâmetros commandname um string contendo uma instrução sh Unix stat um flag indicador inteiro Descrição Envia um string commandname para o Unix para execução pelo interpretador de comando sh em Unix ou commandcom em DOS As saídas e os erros padrões do comando do shell são escritos no shell chamado stat fornece 1 se o host significa anfitrião não pode ser chamado memória disponível do sistema insuficiente ou se o interpretador de comando retorna o código Exemplos criando uma função getdir baseda no host function wdgetdir if MSDOS then hostcdTMPDIRpath else hostpwdTMPDIRpath end wdreadTMPDIRpath11a endfunction chamandoa wdgetdir Ver Também edit manedit unixg unixs unixw unixx 1305 Name input prompt para entrada do usuário x inputmessage string Parâmetros message string string string string pode ser abreviado para s x número real ou string se string estiver na seqüência de chamamento Descrição inputmessage fornece ao usuário o prompt no string de texto e então espera por entrada no teclado A entrada pode ser a expressão avaliada por evstr Se apenas um retornodecarro for fornecido no prompt inputmessage retorna uma matriz vazia Chamado com dois argumentos a saída é um string que é a expressão fornecida pelo teclado Se apenas um retorno de carro for fornecido inputmessage retorna um único espaço em branco Exemplos xinputQuantas iterações xinputQual o seu nomestring Ver Também evstr xdialog xmdialog 1306 Name load carrega variável salva loadfilename x1xn loadfd x1xn Parâmetros filename string contendo o endereço do arquivo fd descritor de arquivo fornecido por uma chamada a mopen xi nomes de variáveis Scilab arbitrárias fornecidos como strings Descrição O comando load pode ser utilizado para recarregar no Scilab variáveis de sessão previamente gravadas com o comando save Se o arquivo contém variáveis correspondentes a manipuladores gráficos as graphicsentities entidades gráficas correspondentes são desenhados Desde o Scilab 50 todos os manipuladores uimenu ou uicontrol também são desenhados loadfilename carrega variáveis no arquivo dado pelo endereço filename loadfd carrega variáveis no arquivo fornecido pelo seu descritor fd loadfilenamexy ou loadfdxy carrega apenas as variáveis xy Mesmo que o formato de arquivo binário tenha mudado na versão 25 loadfilename é capaz de ler formatos antigos Formatos antigos podem ser acessados por enquanto utilizando as funções oldsave e oldload Exemplos aeye22bonesa savevalsdatab clear a clear b loadvalsdatab Ver Também save listvarinfile saveformat exec mopen 1307 Name oldload carrega variáveis salvas em formato 241 e anteriores oldloadfilename x1xn Parâmetros filename string xi nomes de variáveleis arbitrárias do Scilab fornecidos como strings Descrição A função oldload está obsoleta e esta sendo retida apenas para propósitos de compatibilidade O comando oldload pode ser usado para recarregar no Scilab variáveis de sessão previamente salvas em um arquivo através do comando save oldloadfilename carrega as variáveis em um arquivo salvo filename oldloadfilenamexyz carrega apenas variáveis xyz ar mazenadas no arquivo filename Exemplos aeye22bonesa oldsaveTMPDIRvalsdatab clear a clear b oldloadTMPDIRvalsdatab Ver Também save exec 1308 Name oldsave gravação de variáveis em formato 241 e anteriores oldsavefilename x1x2xn Parâmetros filename string ou unidade lógica retornada por fileopen xi variávelis Scilab arbtrárias Descrição A função oldsave está obsoleta e retida apenas por compatibilidade O comando oldsave pode ser usado para salvar variáveis Scilab correntes em forma binária num arquivo oldsavefilename salva todas as variáveis correntes no arquivo definido por filename oldsavefilenamexy salva apenas as variáveis nomeadas x e y Variáveis salvas podem ser recarregadas através dos comandos load ou oldload Exemplos aeye22bonesa oldsaveTMPDIRvaldatab clear a clear b oldloadTMPDIRvaldatab Ver Também load file 1309 Name read Leitura de matrizes xreadfiledescmnformat xreadfiledescmnkformat Parâmetros filedesc string especificando o nome do arquivo ou valor inteiro especificando uma unidade lógica ver file m n inteiros dimensões da matriz x Ajuste m1 se você desconhece o número de linhas para que todo o arquivo seja lido format string especifica um formato Fortran Este string deve começar com um parêntese direito e terminar com um parêntese esquerdo Formatos não podem misturar pontos flutuantes inteiros ou modo de edição de caractere k inteiro ou vetor de inteiros Descrição Lê linha após linha a matriz x mxn n1 para cadeia de caracteres no arquivo filedesc string ou inteiro Cada linha da matriz x começa em uma nova linha do arquivo filedesc Dependendo de format uma dada linha da matriz x pode ser lida de mais de uma linha do arquivo filedesc O tipo do resultado dependerá do formato especificado Se format contém apenas os descritores defg a função tenta ler dados numéricos o resultado é uma matriz de números reais Se format contém apenas o descritor a a função tenta ler strings o resultado é um vetor coluna de strings Neste caso n deve ser igual a 1 Aviso Os strings serão truncados se tiverem tamanho maior que 4093 Exemplos para format 1xe1035x3f30 10xa20 Quando format é o omitido os dados são lidos utilizandose o formato numérico livre espaços em branco vírgulas e barras podem ser utilizados como separadores de dados nv pode ser utilizado para representar n ocorrências do valor n Um arquivo de acesso direto pode ser utilzado na presença de um parâmetro k que é um vetor de números de gravações a serem lidas uma gravação por linha logo m deve ser mprodsizek Para ler no teclado use readio1 Observação A última linha de cada arquivo de dados devemser terminada por uma nova linha newline a ser levada em conta read 1310 Exemplos if MSDOS then unixdel foo else unixrm f foo end Arand35 writefooA Breadfoo35 Breadfoo15 readio111a espera por entrada do usuário Ver Também file readb write xdialog mscanf mfscanf msscanf fscanfMat 1311 Name read4b leitura de arquivo FORTRAN binário xread4bfilenamemn rec Parâmetros filename string ou inteiro m n inteiros dimensões da matriz x Ajuste m1 se você não sabe o número de linhas então todo o arquivo será lido rec vetor de inteiros positivos os registros selecionados para acesso direto O tamanho desejado deve ter o mesmo tamanho de x desejado Descrição Leitura binária da matriz x no arquivo filename Supõese que as entradas da matriz foram ar mazenadas em palavras de quatro bytes Para acesso a registros direto o arquivo deve ter sido previamente aberto com a função file para se ajustar o comprimento do registro filename deve ser o resultado da função file Ver Também file write writb mget write4b 1312 Name readb leitura de arquivo FORTRAN binário xreadbfilenamemn rec Parâmetros filename string ou inteiro m n inteiros dimensões da matriz x Ajuste m1 se o número de linhas não for conhecido então todo arquivo será lido rec vetor de inteiros positivos os registros selecionados para acesso direto O tamanho deste vetor deve ser igual ao número de linhas de x desejado Descrição Leitura binária da matriz x no arquivo filename Supõese que as entradas da matriz tenham sido armazenadas em palavras de 8 bytes Para acesso direto a registros o arquivo deve ter sido aberto previamente com a função file para ajustar o comprimento de registro filename deve ser o resultado da função file Ver Também file write writb mget read4b 1313 Name readc lê um string creadcunit creadc Descrição readc lê um string Esta função permite interromper um arquivo exec sem pause o arquivo exec pára até que seja dado um retorno de carro Ver Também read 1314 Name save salvando variáveis em arquivos binários savefilename x1x2xn savefd x1x2xn Parâmetros filename string contendo o endereço do arquivo fd descritor do arquivo fornecido por uma chamada a mopen xi variávelis Scilab arbitrárias Descrição O comando save pode ser usado para salvar as variáveis Scilab correntes em um arquivo Se uma variável é um manipulador gráfico a função save salva todas as definições de graphicsentities entidades gráficas correspondentes Desde o Scilab 50 todos os manipuladores de uimenu ou uicontrol também são gravados por esta função O arquivo pode ser fornecido tanto pelo seu endereço quanto por seu descritor dado previamente por mopen savefilename salva todas as variáveis correntes definidas por filename savefd salva todas as variáveis correntes definidas pelo descritor fd savefilenamexy ou savefdxy salva apenas as variáveis chamadas x e y Variáveis salvas podem ser recarregadas através do comando load Exemplos aeye22bonesa savevaldatab clear a clear b loadvaldatab gravação seqüêncial em um arquivo fdmopenTMPDIRfoowb for k14 xk2savefdxkend mclosefd fdmopenTMPDIRfoorb for i14 loadfdxkxkend mclosefd anexando variáveis a um arquivo gravado antigo fdmopenTMPDIRfoor mseek0fdend save 1315 lstlist123 savefdlst mclosefd Ver Também load saveformat mopen 1316 Name setenv ajusta o valor de uma variável de ambiente repsetenvname value Parâmetros name aponta para o nome de uma variável de ambiente name é um string value aponta para o valor a ser atribuído à variável de ambiente value é um string rep Retorna T se estiver tudo correto ou F em caso contrário Descrição Ajusta o valor de uma variável de ambiente Exemplos setenvtotoexample getenvtoto Ver Também getenv Autor Allan CORNET 1317 Name unix execução de comando shell sh statunixcommandname Parâmetros commandname string contendo uma instrução Unix sh stat flag inteiro Descrição Envia um string commandname ao Unix para execução com o shell sh Saída e erros padrões do shell de comando são escritos no shell chamado stat retorna 1 se o Unix não pode ser chamado memória do sistema disponível insuficiente ou o código de retorno sh Exemplos if MSDOS then unixls SCIdemos end function wddirectory if MSDOS then unixcdgtTMPDIRpath else unixpwdgtTMPDIRpath end wdreadTMPDIRpath11a endfunction wddirectory Ver Também edit manedit unixg unixs unixw unixx host 1318 Name unixg execução de um comando shell sh saída redirecionada a uma variável repunixgcmd repstatunixgcmd repstatstderrunixgcmd Parâmetros cmd string rep vetor coluna de strings saída padrão stat inteiro o status de erro stat0 se nenhum erro tiver ocorrido err vetor coluna de strings erro padrão Descrição Envia um string cmd ao Unix para execução pelo comando shell sh A saída padrão é redirecionada para a variável Scilab rep O erro padrão é redirecionado à variável Scilab err ou é exibido se você forneceu apenas dois argumentos de saída Erros de execução Unix são detectados Note que apenas o último erro de comando shell é reportado quando uma lista de comandos separados por é enviada Isto não é recomentdado Exemplos function dDIRpath pathpathconvertpathtt if MSDOS then dunixgdir path else dunixgls path end endfunction DIRSCIetc Ver Também unixs unixw unixx unix 1319 Name unixs execução do comando shell sh sem saída unixscmd Parâmetros cmd string Descrição Envia um string cmd ao Unix para execução pelo shell sh A saída padrão é redirecionada para devnull Erros de execução Unix são detectados Note que apenas o último erro de comando shell é reportado quando uma lista de comandos separados por é enviada isto não é recomendado Exemplos if MSDOS then unixsdel foo else unixsrm f foo end Ver Também edit manedit unixg unixw unixx unix 1320 Name unixw execução de comando shell sh saída redirecionada à janela do Scilab unixwcmd Parâmetros cmd string Descrição Envia um string cmd ao Unix para execução com o comando shell sh A saída é redirecionada à janela do Scilab Erros de execução Unix são detectados Note que apenas o último erro de comando shell é reportado quando uma lista de comandos separados por é enviada isto não é recomandado Exemplos if MSDOS then unixwdir WSCImodules else unixwls SCImodules end Ver Também edit manedit unixg unixs unixx unix 1321 Name unixx execução do comando shell sh saída redirecionada a uma janela unixxcmd Parâmetros cmd string Descrição Envia um string cmd ao Unix para uma execução através do shel sh A saída padrão é redirecionada a uma janela Erros de execução Unix são detectados Note que apenas o último erro de comando de shell é reportado quando uma lista de comandos separados por é enviada Isto não é recomendado Exemplos if MSDOS then unixxdir WSCImodulesgraphicsdemos else unixxls SCImodulesgraphicsdemos end Ver Também edit manedit unixg unixs unixw unix 1322 Name writb escrita binária de arquivo FORTRAN writbfilenamea rec Parâmetros filename string ou inteiro rec vetor de inteiros positivos os registros selecionados para acesso direto O tamanho deste vetor deve ser igual ao número de linhas de a Descrição Escreve em formato binário a matriz a no arquivo filename As entradas da matriz são ar mazenadas em palavras de quatro bytes Para registro de acesso direto o arquivo deve ter sido previamente aberto através da função file para se ajustar o comprimento do registro filename deve ser o resultado da função file Ver Também file readb write mput write4b 1323 Name write Escrita em arquivo formatado writefiledescaformat writefiledescakformat Parâmetros filedesc string especificando o nome do arquivo ou valor inteiro especificando a unidade lógica ver file a matriz de reais ou vetor coluna de strings format string especifica um formato Fortran Este string deve começar com um parêntese direito e terminar com um parêntese esquerdo Formatos não podem misturar pontos flutuantes inteiros ou modo de edição de caractere k integer vector Descrição Escreve linha por linha uma matriz de reais ou um vetor coluna de strings em um arquivo formatado Cada linha do argumento a começa em uma nova linha do arquivo filedesc Dependendo de format uma dada linha do argumento a pode ser escrita em mais de uma linha do arquivo file desc Exemplos de formatos 1xe1035x3f30 10xa20 Veja um livro de Fortran para maior precisão Arquivos de acesso direto xwritefiledescakformat Aqui k é o vetor de gravações uma gravação por linha ie mprodsizek writeio2 escreve em uma janela do Scilab Note que neste caso format deve pro duzir uma linha de saída por linha da matriz Se esta restrição não for respeitada um erro imprevisível acontece Exemplos if MSDOS then unixdel asave else unixrm f asave end Arand53 writeasaveA Areadasave53 writeio2A 3f103 writeio2string110 writeio2strcatstring110 writeio211010i23x if MSDOS then unixdel foo else unixrm f foo end writefooA Ver Também file fileinfo writb read print string mfprintf mprintf msprintf fprintfMat 1324 Name write4b escrita binária de arquivo FORTRAN write4bfilenamea rec Parâmetros filename string ou inteiro rec vetor de inteiros positivos os registros selecionados para acesso direto O tamanho deste vetor deve ter o mesmo número de linhas que a Descrição Escreve em formato binário a matriz a no arquivo filename As entradas da matriz são ar mazenadas em palavras de 8 bytes Para acesso direto o arquivo deve ter sido previamente aberto através da função file para se ajustar o comprimento do registro filename deve ser o resultado da função file Ver Também file readb write mput read4b Parte XX Funções de Saída 1326 Name disp exibição de variáveis dispx1x2xn Descrição Exibe xi com o formato corrente xis são objetos arbitrários matrizes de constantes strings funções listas A exibição de objetos definidos por tlists pode ser sobrecarregada pela definição de uma função Esta função não deve ter argumento de saída um único argumento de entrada e seu nome deve ser formado como segue tlisttypep onde tlisttype é a primeira entrada do com ponente de tipo tlist A função lines pode ser usada para controlar a saída Exemplos disp1 23 defftpldispl3l2 disptlistt12 Ver Também lines write read print string tlist 1327 Name print imprime variáveis em um arquivo printfilenamex1x2xn Descrição Imprime xi no arquivo filename com o formato corrente ie o formato utilizado pelo Scilab para exibir variáveis Todos os tipos de variáveis podem ser impressos Note que xi deve ser uma variável nomeada Com expressões a exibição da parte do nome da variável é imprevisível printio2 imprime na janela do Scilab Esta sintaxe pode ser utilizada para exibir variáveis dentro de um macro Exemplos arand33ppoly123sllist1asdf1 2 3 printio2apl writeio2a Ver Também write read format printf disp 1328 Name printf emulador da função da linguagem C printf printfformatvalue1valuen Parâmetros format string Scilab especifica um string combinando caracteres literais com especificações de conversão valuei especifica os dados a serem convertidos de acordo com o parâmetro de formato str vetor coluna de strings file string Scilab especificando um arquivo ou um número de unidade lógica ver file Descrição A função printf converte formata e escreve seus parâmetros value sob controle do parâmetro format para a saída padrão O parâmetro format é um string que contém dois tipos de objetos Caracteres literais que são copiados no fluxo de saída Especificações de conversão cada um dos quais faz com que zero ou mais itens sejam buscados da lista de parâmetros value Ver printfconversion para detalhes Se algum item de values sobrar após todo o format ter sido processado ele é ignorado Exemplos printfO resultado é alphaf0535 Ver Também string print write format disp file fprintf sprintf printfconversion 1329 Name printfconversion Especificações de conversão de printf sprintf fprintf Descrição Cada especificação de conversão no parâmetro format de printf sprintf fprintf possui a seguinte sintaxe Um sinal porcento Zero ou mais options opções que modificam o significado da especificação de conversão A lista seguinte contem os caracteres option e seus significados Alinhe à esquerda dentro do campo o resultado da conversão Comece o resultado de uma conversão com sinal com um sinal ou Prefixe um caractere de espaço ao resultado se o primeiro caractere de uma conversão com sinal não for um sinal Se ambas as opções espaço e aparecerem a opção space é ignorada Converta o valor para uma forma alternativa Para as conversões c d i s e u a opção não possui efeito Para a conversão o aumenta a precisão para forçar o primeiro dígito do resultado a ser 0 zero Para as conversões x e X um valor nãonulo possui 0x ou 0X prefixado a ele Para as conversões e E f g e G o resultado sempre contém ponto decimal Mesmo que nenhum dígito o siga Para as conversões g e G zeros por último não são removidos Aumente a largura do campo utilizando zeros à esquerda seguindo qualquer indicação de sinal ou base para as conversões d i o u x X e E f g e G nenhum aumento de espaço é realizado Se ambos os indicadores 0 e barra aparecerem o indicador 0 é ignorado Para as conversões d i o u x e X se uma precisão for especificada o indicador 0 também é ignorado Um string de dígitos decimais opcional que especifica a largura mínima do campo Se o valor conver tido tiver menos caracteres que a largura do campo o campo é aumentado à esquerda até o compri mento especificado pela largura do campo Se a opção de ajuste à esquerda for especificada o campo é aumentado pela direita Uma precisão opcional A precisão é um ponto seguido por um string de dígito decimal Se nen huma precisão for fornecida o parâmetro é tratado como 0 zero A precisão especifica O número mínimo de dígitos a aparecerem nas conversões d u o x ou X O número de dígitos a aparecerem após o ponto decimal nas conversões e E e f O número máximo de dígitos significativos para as conversões g e G O número máximo de caracteres a serem impressos a partir de um string em uma convesão s O caractere que indica o tipo de conversão a ser aplicada Não realiza conversão Exibe Aceita um valor inteiro e o converte para notação decimal com sinal A precisão especifica o número mínimo de dígitos a aparecer Se o valor sendo convertido puder ser representado em menos dígitos ele é expandido com zeros à esquerda A precisão padrão é 1 O resultado de se converter um valor zero com uma precisão de zero é um string nulo A especificação de uma largura de campo com zero como caractere mais à esquerda faz com que o valor da largura do campo seja preenchido com zeros à esquerda Aceita um valor inteiro e o converte para a notação decimal sem sinal A precisão especifica o número mínimo de dígitos a aparecer Se o valor sendo convertido puder ser representado em menos printfconversion 1330 dígitos ele é expandido com zeros à esquerda A precisão padrão é 1 O resultado de se converter um valor zero com uma precisão de zero é um string nulo A especificação de uma largura de campo com zero como caractere mais à esquerda faz com que o valor da largura do campo seja preenchido com zeros à esquerda Aceita um valor inteiro e o converte para a sua notação octal sem sinal A precisão especifica o número mínimo de dígitos a aparecer Se o valor sendo convertido puder ser representado em menos dígitos ele é expandido com zeros à esquerda A precisão padrão é 1 O resultado de se converter um valor zero com uma precisão de zero é um string nulo A especificação de uma largura de campo com zero como caractere mais à esquerda faz com que o valor da largura do campo seja preenchido com zeros à esquerda Não é implicado um valor octal para a largura do campo Aceita um valor inteiro e o converte para a sua notação hexadecimal sem sinal As letras abcdef são utilizadas para a conversão x as letras ABCDEF são utilizadas para a conversão X A precisão especifica o número mínimo de dígitos a aparecer Se o valor sendo convertido puder ser represen tado em menos dígitos ele é expandido com zeros à esquerda A precisão padrão é 1 O resultado de se converter um valor zero com uma precisão de zero é um string nulo A especificação de uma largura de campo com zero como caractere mais à esquerda faz com que o valor da largura do campo seja preenchido com zeros à esquerda Aceita um valor float ou double e o converte para a sua notação decimal no formato dddddd O número de dígitos após o ponto decimal é igual à especificação de precisão Se nenhuma precisão for especificada a saída possui seis dígitos Se a precisão for zero nenhum ponto decimal aparece e o sistema imprime na saída o valor inteiro mais próximo de value Se a saída possui um ponto decimal pelo menos um dígito é posto antes dele Aceita um real e o converte para a sua forma exponencial ddddedd Há um dígito antes do ponto decimal e o número de dígitos após o ponto decimal é igual à especificação de precisão Se nenhuma precisão for especificada a saída são seis dígitos Se a precisão for zero nenhum ponto decimal aparece A caractere de conversão E produz um número com o caractere E ao invés de e antes do expoente O expoente sempre contém pelo menos dois dígitos Se o valor for zero o expoente é zero Aceita um real e o converte no estilo dos caracteres de conversão e E ou f com a precisão es pecificando o número de dígitos significativos Zeros por último são removidos Um ponto decimal aparece apenas se for seguido de um dígito O estilo depende do valor convertido O resultado é o estilo e E se G é o indicador utilizado apenas se o expoente resultante da conversão for menor do que 4 ou se for maior do que ou igual à precisão Aceita e exibe um valor inteiro convertido em um caractere Aceita um valor string e exibe caracteres do string até o fim ou até que o número de caracteres indicados pela precisão seja alcançado Se nenhuma precisão for especificada todos os caracteres até o fim são exibidos Uma largura de campo ou uma precisão podem ser indicadas por asterísco ao invés de um string de dígito Neste caso um parâmetro de valor inteiro provê a largura do campo ou a precisão O parâmetro de valor convertido para saída não é buscado até que a letra de conversão seja alcançada então os parâmetros especificando o comprimento de campo ou precisão devem aparecer antes do valor a ser convertido se houver algum Se o resultado da conversão for maior que a largura do campo o campo é expandido para conter o resultado convertido printfconversion 1331 A representação do sinal de mais depende da opção de formatação especificada se ou espaço Ver Também printf fprintf sprintf 1332 Name sprintf emulador da função da linguagem C sprintf strsprintfformatvalue1valuen Parâmetros format string Scilab especifica um string combinando caracteres literais com especificações de conversão valuei especifica os dados a serem convertidos de acordo com o parâmetro de formato str vetor coluna de strings Descrição A função sprintf converte formata e escreve seus parâmetros value sob controle do parâmetro format para a saída padrão O parâmetro format é um string que contém dois tipos de objetos Literal characters que são copiados no fluxo de saída Conversion specifications cada um dos quais faz com que zero ou mais itens sejam buscados da lista de parâmetros value parameter list Ver printfconversion para detalhes Se não há itens suficientes para format na lista de parâmetros value sprintf gera um erro Se algum valor de value sobrar após todo format ter sido processado ele é ignorado Nota sprintf é obsoleto use msprintf ao invés Exemplos fahr120 sprintf3d Fahrenheit 61f Celsiusfahr59fahr32 Ver Também string print write format disp file printf fprintf msprintf printfconversion 1333 Name ssprint embelezador de sistemas lineares ssprintsl out Parâmetros sl lista lista syslin out saída valor padrão outio2 Descrição Representação embelezada de uma sistema linear em lista syslin de forma de espaço de estados slABCD Exemplos a1 10 1b0 11 0c11d32 ssprintsyslincabcd ssprintsyslindabcd Ver Também texprint 1334 Name diary diary of session diaryfilename idfilename diaryfilename newappend ids filenames diary ids filenames diary list diary close diary0 diaryfilename close diaryid close diary pauseoff diaryfilename pauseoff diaryid pauseoff diary resumeon diaryfilename resumeon diaryid resumeon diaryfilenames exists diaryids exists diaryfilename newappend prefixYYYYMMDD hhmmss diaryfilename newappend prefixU diaryfilename newappend prefixYYYYMMDD hhmmss prefixonlycommands Parameters filename a character string give the full file name path id a scalar to identify a diary Description diaryffunction creates a log of keyboard input and the resulting text output Start a diary session id filename diaryfilename newappend returns id a positive integer 1 which is the diary session identifier filename A string the absolute path of the effective written file The first input argument is a string that contain the path of the diary file This can be a relative path or a absolute path The 2nd input argument controls if a new file is created new or if diary adds new content at the end of the file append If the 2nd input argument is not present the default value is new diary 1335 When diary is called with new mode If filename already exists and is not empty an effective filename basefilemaneextensionfilename is built used and returned by diaryfilename as a second output argument beside id The rank would be set as the smallest integer for which the resultant filename does not yet exists List diary sessions ids filenames diary ids filenames diarylist returns a column vector of integer identifiers list of opened diary sessions a column vector of strings absolute paths of the files associated with opened diary sessions Close diary sessions diaryclose diary0 diaryfilenameclose diaryidclose The first and second syntaxes close all opened diary sessions The third syntax closes diary sessions identified by filename The fourth syntax closes the diary session identified by id which is a positive integer or a vector of positive integers Remark diary0 is retained as backwards compatibility PauseResume diary sessions diary pauseoff diaryfilenamepauseoff diaryid pauseoff The first syntax suspends all opened diary sessions The second syntax suspend diary sessions identified by filename filename can be a single string or a character string array The third syntax suspend the diary session identified by id which is a positive integer or a vector of positive integers diary resumeon diaryfilenameresumeon diaryid resumeon The first syntax resume all opened diary sessions The second syntax resume diary sessions identified by filename filename can be a single string or a character string array diary 1336 The third syntax resume the diary session identified by id which is a positive integer or a vector of positive integers Does a diary session exists diaryfilenameexists diaryidexists return true if a diary session is currently opened with the file filename if not false Diary and timestamp diaryfilenamenewprefixYYYYMMDD hhmmss diaryfilenamenewprefixU diaryfilenamenew prefixYYYYMMDD hhmmss prefixon lycommands prefixYYYYMMDD hhmmss add date hour prefixU add UNIX time epoch prefixonlycommands add timestamp only as prefix for commands Filtering diary diaryfilenamenewfiltercommand Log only the input commands diaryfilenamenewfilteroutput Log only the text output Examples d1 diaryTMPDIR diary1txt d2 diaryTMPDIR diary2txt some Scilab instructions cd TMPDIR dir returns infos about opened diary ids filenames diary close diary d1 diaryd1close ids filenames diary close diary d2 diaryTMPDIR diary2txt ids filenames diary closes all diary diaryclose ids filenames diary 1337 Name mprintf converts formats and writes data to the main scilab window mprintfformata1an Parameters format a Scilab string describing the format to use to write the remaining operands The format operand follows as close as possible the C printf format operand syntax a1an Specifies the data to be converted and printed according to the format parameter Description The mprintf function is a interface for Ccoded version of printf function The mprintf function writes formatted operands to the standard Scilab output ie the Scilab win dow The argument operands are formatted under control of the format operand Examples mprintfAt iteration i Result is alphaf330535 See Also disp 1338 Name msprintf converts formats and writes data in a string strmsprintfformata1an Parameters format a Scilab string describing the format to use to write the remaining operands str a character string a1an Specifies the data to be converted and printed according to the format parameter Description The msprintf writes formatted operands in its returned value a Scilab string The argument operands are formatted under control of the format operand Note that in this case the escape sequences split string to a matrix of string see example Examples msprintf53f 53f1230732 msprintf53f 53f1230732 msprintfs dhello3 See Also mprintf printfconversion 1339 Name prettyprint From any Scilab datatype and provide a representation to the TeX LaTeX or MathML formats str prettyprinta Show the variable a with the default format LaTeX str prettyprintaexportFormat Show the variable a a with the specified format str prettyprintaexportFormat delim As above but change the delimiter str prettyprintaexportFormat delim processByElement As above but process each element independently str prettyprintaexportFormat delim processByElement isWrapped As above Add the special keyword of Tex or LaTeX export Parameters a is a Scilab variable exportFormat is the format if omitted latex is used by default it can be latex tex or mathml delimiter is a string indicating the delimiter to use for the resulting matrix its only used if isWrapped is true The delimiter can be or processByElement is a boolean to indicate if the resulting matrix must be converted into a single string isWrapped is a boolean to indicate if the result must be wrapped inside delimiters for latex and tex or nothing for mathml to be used with xstring or xtitle str the representation of the variable a Description Taking a variable the prettyprint function will provide a formated representation of it Formats can be TeX LaTeX or MathML They can be used in third party applications but also within Scilab with the most of the Scilab graphic features The following types are handled by this function Real Complex matrices Polynomial types Boolean Integer String Tlist Rationnal Cell Examples prettyprint 1340 str prettyprintrand33 Return the LaTeX representation of a 33 matrix xstring0202str Show the representation in a graphic Windows prettyprintrand34mathml Return the MathML representation of a 34 matrix prettyprintrand34mathml Return the MathML representation of a 34 matrix with as delimiter spoly0s G1s1s23s3 xstring0202prettyprintGs1 Show a polynom through a LaTeX representation See also mathrenderingfeaturesingraphic xtitle axesproperties labelproperties legendproperties textproperties xstringb xstringl xstring Authors Calixte Denizet Parte XXI Intersci 1342 Name intersci scilab tool to interface C of Fortran functions with scilab Description All scilab primitive functions are defined in a set of interface routines For each function the interfacing code checks first number of rhs and lhs arguments Then it get pointers on input arguments in the Scilab data base and checks their types After that it calls procedure associated with Scilab functions checks returned errors flags and set the results in the data base intersci is a program which permits to interface automatically FORTRAN subroutines or C func tions to Scilab With intersci a user can group all his FORTRAN or C code into a same set called an interface and use them in Scilab as Scilab functions The interfacing is made by creating a FORTRAN subroutine which has to be linked to Scilab together with the user code This complex FORTRAN subroutine is automatically generated by intersci from a description file of the interface Refer to intersci documentation for more details See Also fort external addinter Parte XXII JVM 1344 Name javaclasspath set and get dynamic Java class path resjavaclasspath javaclasspathpath Parameters res a string matrix Description set and get the dynamic Java path to one or more directory or file specifications given in path Examples resjavaclasspath javaclasspathSCI javaclasspathSCISCIjava Authors AC 1345 Name javalibrarypath set and get dynamic javalibrarypath resjavalibrarypath javalibrarypathpath Parameters res a string matrix Description set and get the dynamic Java Library path to one or more directory given in path When you use java classes with native methods you need to define path where is dynamic library Examples resjavalibrarypath javalibrarypathSCI javalibrarypathSCISCIlibs See Also javaclasspath Authors AC 1346 Name jrepath returns Java Runtime Environment used by Scilab pjrepath Parameters p a string path of JRE Description returns Java Runtime Environment used by Scilab See Also systemgetproperty Authors AC 1347 Name systemgetproperty gets the system property indicated by a specified key ressystemgetpropertykey Parameters res a string value key a string Description gets the system property indicated by a specified key javaversion Java Runtime Environment version javavendor Java Runtime Environment vendor javavendorurl Java vendor URL javahome Java installation directory javavmspecificationversion Java Virtual Machine specification version javavmspecificationvendor Java Virtual Machine specification vendor javavmspecificationname Java Virtual Machine specification name javavmversion Java Virtual Machine implementation version javavmvendor Java Virtual Machine implementation vendor javavmname Java Virtual Machine implementation name javaspecificationversion Java Runtime Environment specification version javaspecificationvendor Java Runtime Environment specification vendor javaspecificationname Java Runtime Environment specification name javaclassversion Java class format version number javaclasspath Java class path javalibrarypath List of paths to search when loading libraries javaiotmpdir Default temp file path javacompiler Name of JIT compiler to use javaextdirs Path of extension directory or directories osname Operating system name osarch Operating system architecture osversion Operating system version fileseparator File separator on UNIX pathseparator Path separator on UNIX lineseparator Line separator on UNIX username Users account name userhome Users home directory userdir Users current working directory systemgetproperty 1348 Examples systemgetpropertyawttoolkit systemgetpropertyfileencoding systemgetpropertyfileencodingpkg systemgetpropertyjavaawtgraphicsenvsunawtWin32GraphicsEnvironment systemgetpropertyjavaawtprinterjobsunawtwindowsWPrinterJob systemgetpropertyjavaclasspath systemgetpropertyjavaclassversion systemgetpropertyjavaendorseddirs systemgetpropertyjavaextdirs systemgetpropertyjavahome systemgetpropertyjavaiotmpdir systemgetpropertyjavalibrarypath systemgetpropertyjavaruntimename systemgetpropertyjavaruntimeversion systemgetpropertyjavaspecificationname systemgetpropertyjavaspecificationvendor systemgetpropertyjavaspecificationversion systemgetpropertyjavavendor systemgetpropertyjavavendorurl systemgetpropertyjavavendorurlbug systemgetpropertyjavaversion systemgetpropertyjavavminfo systemgetpropertyjavavmname systemgetpropertyjavavmspecificationname systemgetpropertyjavavmspecificationvendor systemgetpropertyjavavmspecificationversion systemgetpropertyjavavmvendor systemgetpropertyjavavmversion systemgetpropertylineseparator systemgetpropertyosarch systemgetpropertyosname systemgetpropertyosversion systemgetpropertypathseparator systemgetpropertysunarchdatamodel systemgetpropertysunbootclasspath systemgetpropertysunbootlibrarypath systemgetpropertysuncpuendian systemgetpropertysuncpuisalist systemgetpropertysundesktop systemgetpropertysuniounicodeencoding systemgetpropertysunjnuencoding systemgetpropertysunmanagementcompiler systemgetpropertysunospatchlevel systemgetpropertyusercountry systemgetpropertyuserdir systemgetpropertyuserhome systemgetpropertyuserlanguage systemgetpropertyusername systemgetpropertyusertimezone systemgetpropertyuservariant Authors AC 1350 Name systemsetproperty set a system property indicated by a specified key and value prev systemsetpropertykeyvalue Parameters prev a string previous value or key a string value a string Description Sets the system property indicated by the specified key Warning change property with precaution Examples systemgetpropertymyproperty systemsetpropertymypropertyhello systemgetpropertymyproperty Authors AC 1351 Name withembeddedjre checks if scilab uses a embedded JRE reswithembeddedjre Parameters res a boolean Description checks if scilab uses a embedded JRE Examples reswithembeddedjre Authors AC Parte XXIII Álgebra Linear 1353 Name aff2ab Conversão de uma função linear afim para forma Ab Abaff2abafunctiondimXD flag Parâmetros afunction uma função do Scilab Y fctXD onde X D Y são lists de matrizes dimX uma matriz de inteiros p x 2 p é o número de matrizes em X D uma list de matrizes de reais ou qualquer outro objeto Scilab válido flag parâmetro opcional flagf ou flagsp A uma matriz de reais b um vetor de reais tendo a mesma dimensão de linha que A Descrição aff2ab retorna a representação matricial de uma função afim na base canônica afunction é uma função com sintaxe imposta YafunctionXD onde XlistX1X2Xp é uma lista de p matrizes de reais e YlistY1Yq é uma lista de q matrizes reais que dependem linearmente das Xis A entrada opcional D contém parâmetros necessários para computar Y como uma função de X geralmente é uma lista de matrizes dimX é uma matriz p x 2 dimXinrinci é o número real de linhas e colunas da matriz Xi Estas dimensões determinam na a dimensão de coluna da matriz resultante A nanr1nc1 nrpncp Se o parâmetro opcional flagsp a matriz resultante A é retornada como uma esparsa Esta função é útil para resolver um sistema de equações lineares onde as incógnitas são matrizes Exemplos solucionador de equação de Lyapunov uma incógnita uma restrição deffYlyapunovXDAQDXmX YlistAXmXmAQ Arand33Qrand33QQQDlistAQdimX33 Alyblyaff2ablyapunovdimXD XlkerAlinsolveAlybly Xvvec2listXldimX lyapunovXvD XmXv AXmXmAQ solucionador de equação de Lyapunov com restrição redundante XX uma variável uma restrição D é variável global deffYly2XDAQDXmX YlistAXmXmAQXmXm Arand33Qrand33QQQDlistAQdimX33 Alyblyaff2ably2dimXD aff2ab 1354 XlkerAlinsolveAlybly Xvvec2listXldimX ly2XvD equações de Francis Achando matrizes X1 e X2 tais que A1X1 X1A2 BX2 A3 0 D1X1 D2 0 deffYbruceXDA1A2A3BD1D2D X1X2XYlistA1X1X1A2BX2A3D1X1D2 A141012A312B01A21D101D21 DlistA1A2A3BD1D2 n1m1sizeA1n2m2sizeA2n3m3sizeB dimXm1n2m3m2 Afbfaff2abbrucedimXD XfKerAflinsolveAfbfXsolvec2listXfdimX bruceXsolD Achando todas as X que comutam com A deffyfXDylistDXXD Arand33dimX33Afbfaff2abfdimXlistA XfKerAflinsolveAfbfpqsizeKerAf Xsolvec2listXfKerAfrandq1dimX CXsol ACCA Ver Também linsolve 1355 Name balanc balanceamento de uma matriz ou de um feixe de matrizes AbXbalancA EbAbXYbalancEA Parâmetros A matriz quadrada de reais X matriz quadrada de reais invertível E matriz quadrada de reais com mesma dimensão que A Y uma matriz quadrada de reais invertível Descrição Balanceia uma matriz quadrada para melhorar seu número de condicionamento AbX balancA acha uma transformação de similaridade X tal que Ab invXAX tem aproximadamente normas iguais de linha e de coluna Para feixes de matrizes o balancemento é feito para melhorar o problema do autovalor generalizado EbAbXY balancEA retorna transformações esquerda e direita X e Y tais que EbinvXEY AbinvXAY Observação O balanceamento é feito nas funções bdiag e spec Exemplos A12101210210210 AbXbalancA normA1normA2 normAb1normAb2 Ver Também bdiag spec schur 1356 Name bdiag diagonalização em blocos autovetores generalizados Ab X bsbdiagA rmax Parâmetros A matriz quadrada de reais ou complexos rmax número real Ab matriz quadrada de reais ou complexos X matriz de reais ou complexos nãosingular bs vetor de inteiros Descrição Ab X bsbdiagA rmax realiza a diagonalização em blocos da matriz A bs fornece a estrutura dos blocos respectivos tamanhos dos blocos X é a matriz mudança de base ie Ab invXAX é diagonal em blocos rmax controla o condicionamento de X o valor padrão é a norma L1 de A Para encontrar a forma diagonal se existir escolha um valor suficientemente grande para rmax rmax1eps por exemplo Genericamente para uma matriz A de reais aleatória os blocos são 1x1 e 2x2 e X é a matriz de autovetores Exemplos No caso de reais blocos 1x1 e 2x2 arand55abxbsbdiagaab No caso de complexos blocos 1x1 complexos abxbsbdiagai0ab Ver Também schur sylv spec 1357 Name chfact fatoração esparsa de Cholesky spchochfactA Parâmetros A uma matriz simétrica positiva e esparsa spcho lista contendo os fatores de Cholesky em forma codificada Descrição spchochfactA computa os fatores esparsos de Cholesky da matriz esparsa A assumida simétrica e positiva definida A função é baseada nos programas NgPeyton ORNL Ver os progra mas FORTRAN para uma completa descrição das variáveis em spcho Esta função deve ser usada com a função chsolve Ver Também chsolve sparse lufact luget spchol 1358 Name chol Cholesky factorization RcholX Parâmetros X uma matriz simétrica e positiva definida de reais ou complexos Descrição Se X é positiva definida então R cholX produz uma matriz triangular superior R tal que RR X cholX usa apenas a diagonal e o triângulo superior de X O triângulo inferior é assumido como sendo a transposta ou complexo conjugado da superior Referências A decomposição de Cholesky é baseada nas rotinas de Lapack DPOTRF para matrizes de reais e ZPOTRF no caso de matrizes de complexos Exemplos Wrand55irand55 XWW RcholX normRRX Ver Também spchol qr svd bdiag fullrf 1359 Name chsolve solucionador esparso de Cholesky solchsolvespchorhs Parâmetros spcho lista contendo os fatores de Cholesky na forma codificada retornados por chfact rhs sol vetores colunas cheios Descrição solchsolvespchorhs computa a solução de rhsAsol com A uma matriz simétrica e positiva definida Esta função é baseada nos programas NgPeyton ORNL Veja os programas FORTRAN para uma descrição completa das variáveis em spcho Exemplos Asprand202001 AAAeye spchochfactA sol120rhsAsol spchochfactA chsolvespchorhs Ver Também chfact sparse lufact luget spchol 1360 Name classmarkov classes transientes e recorrentes da matriz de Markov permrectrindsRecindsTclassmarkovM Parâmetros M matriz de Markov N x N de reais A soma das entradas em cada linha deve ser acrescida em uma unidade perm vetor de permutação de inteiros rec tr vetor de inteiros número número de estados em cada classe recorrente número de estados tran sientes indsRecindsT vetor de inteiros índices dos estados recorrentes e transientes Descrição Retorna um vetor de permutação perm tal que Mpermperm M11 0 0 0 0 0 0 M22 0 0 0 0 0 M33 0 0 0 Mrr 0 Q Cada Mii é uma matriz de Markov de dimensão reci i1r Q é uma submatriz de Markov de dimensão tr Estados de 1 a sumrec são recorrentes e estados de r1 a n são transientes Tem se permindsRecindsT onde indsRec é um vetor de tamanho sumrec e indsT é um vetor de tamanho tr Exemplos P tem 2 classes recorrentes com 2 e 1 estados e 2 estados transientes Pgenmarkov212perm permrectrindsRecindsTclassmarkovP Ppermperm Ver Também genmarkov eigenmarkov 1361 Name cmblin combinação linear simbólica xcmblinalfaxbetay Descrição Avalia alfaxbetay alfa beta x y são strings rotina de baixonível Ver também mulf addf 1362 Name coff resolvente método do cofator NdcoffM var Parâmetros M matriz quadrada de reais var string N matriz de polinômios com o mesmo tamanho que M d polinômio polinômio característico polyAs Descrição coff computa RseyeM1 para M uma matriz de reais R é dado por Nd N matriz de polinômios como numerador d denominador comum var string s se omitido Exemplos M1203 NdcoffM Nd invseyeM Ver Também coffg ss2tf nlev poly 1363 Name colcomp compressão de colunas núcleo WrkcolcompA flag tol Parâmetros A matriz de reais ou complexos flag string tol número real W matriz quadrada nãosingular mudança de base rk inteiro posto de A Descrição Compressão de colunas de A Ac AW é de colunas comprimidas ie Ac0Af com o postocoluna de Af cheio postoAf postoA rk flag e tol são parâmetros opcionais flag qr ou svd o padrão é svd tol parâmetro de tolerância de ordem eps como valor padrão As mark primeiras colunas de W geram o núcleo de A quando sizeAnama Exemplos Arand52rand25 XrcolcompA normAX1r1 Ver Também rowcomp fullrf fullrfk kernel Autor FD 1364 Name companion matriz companheira Acompanionp Parâmetros p polinômio ou vetor de polinômios A matriz quadrada Descrição Retorna uma matriz quadrada A com o polinômio característico igual a p se p é mônico Se p não é mônico o polinômio característico de A é igual a pc onde c é o coeficiente do termo de maior grau em p Se p é um vetor de polinômios mônicos A é diagonal em blocos e o polinômio característico do i ésimo bloco é pi Exemplos spoly0s ppoly12341sc detseyecompanionp rootsp speccompanionp Ver Também spec poly randpencil Autor FD 1365 Name cond número de condicionamento de uma matriz condX Parâmetros X rmatriz quadrada de reais ou complexos Descrição Número de condicionamento em norma2 condX é a razão entre o maior e o menor valor singular de X Exemplos Atestmatrixhilb6 condA Ver Também rcond svd 1366 Name det determinante detX emdetX Parâmetros X matriz quadrada de reais ou complexos matriz de polinômios ou de razões de polinômios m número real ou complexo a mantissa de base 10 do determinante e inteiro o expoente de base 10 do determinante Descrição detX m10e é o determinante da matriz quadrada X Para uma matriz de polinômios detX é equivalente a determX Para matrizes de razões de polinômios detX é equivalente a detrX Referências As computações da função det são baseadas nas rotinas do LAPACK DGETRF para matrizes de reais e ZGETRF para o caso de matrizes de complexos Exemplos xpoly0x detx1x2xx2 wssrand224rootsdetsystmatwtrzerosw zeros do sistema linear Arand33 detA prodspecA Ver Também detr determ 1367 Name eigenmarkov Autovetores esquerdo e direito normalizados de Markov MQeigenmarkovP Parâmetros P matriz de Markov N x N de reais A soma das entradas de cada linha deve ser acrescida de uma unidade M matriz de reais de N colunas Q matriz de reais de N linhas Descrição Retorna os autovetores esquerdo e direito normalizados associados ao autovalor 1 da matriz P de transição de Markov Se a multiplicidade deste autovalor é m e P é N x N M é uma matriz m x N e Q é uma matriz N x m Mk é o vetor de distribuição de probabilidade associado ao késimo conjunto ergódico classe recorrente Mkx é zero se x não está na késima classe recorrente Qxk é a probabilidade de se terminar na késima classe recorrente começando de x Se Pk converge para k sem autovalores no círculo unitário exceto 1 então o limite é QM autoprojeção Exemplos P tem duas classes recorrentes com 2 e 1 estados e 2 estados transientes Pgenmarkov212 MQeigenmarkovP PQQ QMP20 Ver Também genmarkov classmarkov 1368 Name ereduc computa de forma escada de colunas da matriz por transformações qz EQZ stair rkereducXtol Parâmetros X matriz m x n de entradas reais tol escalar real positivo E matriz em forma escada de colunas Q matriz unitária m x m Z matriz unitária n x n stair vetor de índices ISTAIRi j se o elemento da borda Eij é uma quina ISTAIRi j se o elemento da borda Eij não é uma quina i1M rk inteiro posto estimado da matriz Descrição Dada uma matriz X m x n não necessariamente regular a função ereduc calcula a matriz unitária transformada EQXZ que está na forma escada de colunas forma trapezoidal Ainda o posto da matriz X é determinado Exemplos X1 2 34 5 6 EQZ stair rkereducX1d15 Ver Também fstair Autores ThGJ Beelen Philips Glass Eindhoven SLICOT 1369 Name expm exponencial de matriz quadrada matriz exponencial expmX Parâmetros X square matrix with real or complex entries Descrição X é uma matriz quadrada e expmX é a matriz expmX I X X2 2 A computação é realizada primeiro diagonalizando em blocos a matriz X e em seguida aplicando uma aproximação de Pade em cada bloco Exemplos X1 23 4 expmX logmexpmX Ver Também logm bdiag coff log exp 1370 Name fstair computa a forma escada de feixe de colunas por transformações qz AEEEQEZEblcksmuknukmuk0nuk0mneifstairAEQZstairrktol Parâmetros A matriz m x n com entradas reais tol escalar real positivo E matriz de forma escada de colunas Q matriz unitária m x m Z matriz unitária n x n stair vetor de índices ver ereduc rk inteiro posto estimado da matriz AE matriz m x n com entradas reais EE matriz de forma escada de colunas QE matriz unitária m x m ZE matriz unitária n x n nblcks é o número de submatrizes com posto linha completo 0 detectado na matriz A muk array vetor ou matriz de inteiros de dimensão n Contém as dimensões de coluna muk k1nblcks das submatrizes com posto coluna cheio no feixe sEepsAeps nuk array de inteiros de dimensão m1 Contém as dimensões de linha nuk k1nblcks das submatrizes com posto linha cheio no feixe sEepsAeps muk0 array de inteiros de dimensão n Contém as dimensões de coluna muk k1nblcks das submatrizes com o postocoluna cheio no feixe sEepsinfAepsinf nuk array de inteiros de dimensão m1 Contém as dimensões de linha nuk k1nblcks das submatrizes com postolinha cheio no feixe sEepsinfAepsinf fstair 1371 mnei array de inteiros dimensão 4 mnei1 dimensão de linha de sEepsAeps Descrição Dado o feixe sEA onde a matriz E está na forma escada de colunas a função fstair computa de acordo com as necessidades do usuário um feixe unitário transformado QEsEEAEZE que é mais ou menos similar à forma generalizada de Schur do feixe sEA A função também produz parte da estrutura de Kronecker para um dado feixe QZ são as matrizes unitárias usadas para computar o feixe onde E está na forma escada de colunas ver ereduc Ver Também quaskro ereduc Autor ThGJ Beelen Philips Glass Eindhoven SLICOT 1372 Name fullrf fatoração de posto completo ou cheio QMrkfullrfAtol Parâmetros A matriz de reais ou complexos tol número real limiar para determinação do posto QM matriz de reais ou complexos rk inteiroposto de A Descrição Fatoração de posto cheio fullrf retorna Q e M tais que A QM com ImQImA e NucMNucA Q de postocoluna cheio M de postolinha cheio e rk rankA columnsQ rowsM tol é um parâmetro real opcional valor real padrão é sqrteps O posto rk de A é definido como o número de valores singulares maiores que normAtol Se A é simétrica fullrf retorna MQ Exemplos Arand52rand25 QMfullrfA normQMA1 XdrowcompAYX svdAY1dQ spanQ spanA spanY12 span gerado Ver Também svd qr fullrfk rowcomp colcomp Autor FD 1373 Name fullrfk fatoração de posto completo de Ak BkCkfullrfkAk Parâmetros A matriz de reais ou de complexos k inteiro BkCk matrizes de reais ou de complexos Descrição Esta função calcula a fatoração de posto completo ou cheio de Ak ie BkCkAk onde Bk é de postocoluna cheio e Ck de postolinha cheio Temse ImBkImAk e NucCkNucAk Para k1 fullrfk é equivalente a fullrf Exemplos Arand52rand25BkCkfullrfkA3 normBkCkA31 Ver Também fullrf range Autor FD 1990 1374 Name genmarkov gera uma matriz de Markov aleatória com classes recorrentes e transientes Mgenmarkovrectr Mgenmarkovrectrflag Parâmetros rec vetor linha de inteiros sua dimensão é o número de classes recorrentes tr inteiro número de estados transientes M matriz de Markov de reais A soma das entradas de cada linha deve ser acrecsida de uma unidade flag string perm Se fornecido uma permutação dos estados é feita Descrição Retorna em M uma matriz de probabilidade de transição de Markov aleatória com rec1rec entradas respectivamente e tr estados transientes Exemplos P tem duas classes recorrentes com 2 e 1 states e 2 estados transientes Pgenmarkov212perm permrectrindsRecindsTclassmarkovP Ppermperm Ver Também classmarkov eigenmarkov 1375 Name givens transformação de Givens Ugivensxy Ugivensxy Ucgivensxy Ucgivensxy Parâmetros xy dois números reais ou complexos xy vetor coluna de reais ou complexos de tamanho 2 U matriz 2x2 unitária c vetor coluna de reais ou complexos de tamanho 2 Descrição U givensx y ou U givensxy com xy xy retorna uma matriz unitária 2x2 U tal que Uxyr0c Note que givensxy e givensxy são equivalentes Exemplos A3456 UgivensA1 UA Ver Também qr 1376 Name glever inverso do feixe de matrizes BfsBischisgleverEA s Parâmetros E A duas matrizes de reais quadradas de igual dimensão s string o valor padrão é s BfsBis duas matrizes de polinômios chis polinômio Descrição Computação de sEA1 pelo algoritmo generalizado de Leverrier para um feixe de matrizes sEA1 Bfschis Bis chis polinômio característico até uma constante multiplicativa Bfs nmatriz de polinômios como numerador Bis matriz de polinômios expansão de sEA1 ao infinito Note o sinal antes de Bis Cuidado Esta função usa cleanp para simplificar BfsBis e chis Exemplos ssF1s00010000s20000s1 BfsBischisgleverF invFBfschis Bis Ver Também rowshuff det invr coffg pencan penlaur Autor F D 1988 1377 Name gschur forma de Schur generalizada função obsoleta AsEsgschurAE AsEsQZgschurAE AsEsZdim gschurAEflag AsEsZdim gschurAEextern Descrição Esta função é obsoleta e agora está inclusa na função schur function Na maior parte dos casos a função gschur irá ainda trabalhar como antes mas será removida em um lançamento futuro do Scilab As três sintaxes podem ser substituídas por AsEsschurAE AsEsQZschurAEQQ NOTE A TRANSPOSIÇÃO AQUI AsEsZdim schurAEflag A última sintaxe requer algumas adaptações a mais if é uma função do Scilab a nova seqüência de chamamento deve ser AsEsZdim schurAENextern com Nextern definido como segue function tNexternR if R20 then textern1R1R31 else cR1iR2R3 textern2realccrealcc1 end endfunction if é o nome de uma função externa codificada em FORTRAN ou C a nova seqüência de chamamento deve ser AsEsZdim schurAEnextern com nextern definido como segue logical function nexternaraibeta double precision araibeta integer rextern if aieq00d0 then rextern1arbeta00d000d0 else rextern200d000d020d0arararaiai endif nexternreq1 end Ver Também external schur 1378 Name gspec autovalores de feixe de matrizes função obsoleta albegspecAE albeZgspecAE Descrição Esta função está agora inclusa na função spec A seqüência de chamamento deve ser substituida por albespecAE albeZspecAE Ver Também spec 1379 Name hess forma de Hessenberg H hessA UH hessA Parâmetros A matriz quadrada de reais ou complexos H matriz quadrada de reais ou complexos U matriz quadrada ortogonal ou unitária Descrição UH hessA produz uma matriz unitária U e uma matriz de Hessenberg H tais que A UHU e UU Identidade Por si só hessA retorna H A forma de Hessenberg de uma matriz é zero abaixo da primeira subdiagonal Se a matriz é simetrica ou Hermitiana a forma é tridiagonal Referências A função hess é baseada nas rotinas Lapack DGEHRD DORGHR para matrizes de e ZGEHRD ZORGHR para matrizes de complexos Exemplos Arand33UHhessA and absUHUA1d10 Ver Também qr contr schur 1380 Name householder matriz de reflexão ortogonal de Householder uhouseholderv w Parâmetros v vetor coluna de reais ou complexos w vetor coluna de reais ou complexos com o mesmo tamanho que v Valor padrão é eyev u vetor coluna de reais ou complexos Descrição Dados dois vetores coluna v w de mesmo tamanho householdervw retorna um vetor coluna unitário u tal que eye2uuv é proporcional a w eye2uu é a matriz de reflexão ortogonal de Householder O valor padrão de w é eyev Neste caso o vetor eye2uuv é o vetor eyevnormv Ver Também qr givens 1381 Name iminv imagem inversa XdimiminvAB tol XdimYiminvAB tol Parâmetros AB duas matirzes de reais ou complexos com igual número de colunas X matriz quadrada ortogonal ou unitária de ordem igual ao número de colunas de A dim inteiro dimensão do subespaço Y matriz ortogonal de ordem igual ao número de linhas de A e B Descrição XdimiminvAB computaA1B ie vetores cujas imagens através de A estão em ImB As dim primeiras colunas de X geram A1B tol é um limiar usado para testar a inclusão de subespaço o valor padrão é tol 100eps Se Y é retornado então YAXYB é particionado como segue A11A120A22B10 onde B1 tem postolinha cheio igual a postoB e A22 tem postocoluna cheio e tem dim colunas Exemplos Arand25zeros34rand31B1111zeros32 Wrand55AWABWB XdimiminvAB svdAX1dimB vetores AX1dim pertencem a rangeB Imagem de B ImB XdimYiminvABYAXYB Ver Também rowcomp spaninter spanplus linsolve Autor F Delebecque INRIA 1382 Name inv inversa de uma matriz invX Parâmetros X matriz quadrada de reais ou complexos matriz de polinômios matriz de razões de polinômios em representação de transferência ou espaço de estados Descrição invX é a inversa da matriz quadrada X Uma aviso é impresso na tela se X possui má escala ou é quase singular Para matrizes de polinômios ou matrizes razões de polinômios em representação de transferência invX é equivalente a invrX Para sistemas lineares na representação de espaço de estados lista syslin invrX é equivalente a invsyslinX Referências A função inv para matrizes de números é baseada nas rotinas de Lapack DGETRF DGETRI para ma trizes de reais e ZGETRF ZGETRI para o caso de matrizes de complexos Para matrizes de polinômios e matrizes de funções racionais inv é baseado na função invr do Scilab Exemplos Arand33invAA xpoly0x Ax1xx221x123invAA A1x22x21x invAA Assrand223 WinvAA cleanss2tfW Ver Também slash backslash pinv qr lufact lusolve invr coff coffg 1383 Name kernel núcleo de uma matriz WkernelA tolflag Parâmetros A matriz de reais ou complexos completa ou matriz de reais esparsa flag string svd padrão ou qr tol número real W matriz de postocoluna completo Descrição WkernelA retorna o núcleo espaço nulo de A Se A tem postocoluna completo então uma matriz vazia é retornada flag e tol são parâmetros opcionais flag qr ousvd o padrão é svd tol parâmetro de tolerância de ordem eps como valor padrão Exemplos Arand31rand13 AkernelA AsparseA cleanAkernelA Ver Também colcomp fullrf fullrfk linsolve Autor FD 1384 Name kroneck forma de Kronecker de feixe de matrizes QZQdZdnumbepsnumbetakroneckF QZQdZdnumbepsnumbetakroneckEA Parâmetros F feixe de matrizes de reais FsEA EA duas matrizes de reais de mesma dimensão QZ duas matrizes quadradas ortogonais QdZd dois vetores de inteiros numbepsnumeta dois vetores de inteiros Descrição Forma de Kronecker de feixe de matrizes kroneck computa duas matrizes ortogonais Q Z que põem o feixe FsE A na forma triangular superior sEepsAeps X X X O sEinfAinf X X QsEAZ 0 0 sEfAf X 0 0 0 sEetaAeta As dimensões dos quatro blocos são dadas por epsQd1 x Zd1 infQd2 x Zd2 f Qd3 x Zd3 etaQd4xZd4 O bloco inf contém modos infinitos de feixes O bloco f contém modos finitos de feixes A estrutura dos blocos epsilon e eta é dada por numbeps1 de blocos eps de tamanho 0 x 1 numbeps2 de blocos eps de tamanho 1 x 2 numbeps3 de blocos eps de tamanho 2 x 3 etc numbeta1 de blocos eta de tamanho 1 x 0 numbeta2 de blocos eta de tamanho 2 x 1 kroneck 1385 numbeta3 de blocos eta de tamanho 3 x 2 etc O código foi retirado de T Beelen SlicotWGS group Exemplos Frandpencil1122313103 Qrand1717Zrand1818FQFZ feixe aleatório com eps11eps21eps31 2 blocos J infty infinito com dimensões 2 e 3 autovalores finitos em 131 e eta10eta23 QZQdZdnumbepsnumbetakroneckF Qd1Zd1 parte eps é sumepsi x sumepsi número de epsi sumsoma Qd2Zd2 parte infinita Qd3Zd3 parte finita Qd4Zd4 parte eta é sumetai numbereta1 x sumetai numbernúmero numbeps numbeta Ver Também gschur gspec systmat pencan randpencil trzeros 1386 Name linsolve solucionador de equações lineares x0kerAlinsolveAb x0 Parâmetros A uma matriz na x ma de reais possivelmente esparsa b um vetor na x 1 mesma dimensão de linha de A x0 um vetor de reais kerA uma matriz ma x k de reais Descrição linsolve computa todas as soluções para Axb0 x0 é uma solução particular se houver e kerA núcleo de A Qualquer xx0kerAw com w arbitrário satisfaz Axb0 Se um compatible x0 compatível é dado na entrada x0 é retornado Senão um x0 compatível é retornado se houver Exemplos Arand53rand38 bAones81xkerAlinsolveAbAxb b comatível bones51xkerAlinsolveAbAxb b incompatível Arand55xkerAlinsolveAb invAb x é único A benchmark of sparse linear solver Adescrrefmtype ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa b 0onessizeA11 tic res umfpackAb printf time needed to solve the system with umfpack 3f toc tic res linsolveAb printf time needed to solve the system with linsolve 3f toc tic res Ab printf time needed to solve the system with the backslash operator 3f toc linsolve 1387 Ver Também inv pinv colcomp iminv backslash umfpack 1388 Name lsq problemas de mínimos quadrados lineares XlsqAB tol Parâmetros A matriz de reais ou de complexos m x n B matriz de reais ou de complexos m x p tol escalar positivo usado para determinar o posto efetivo de A definido como sendo a ordem da maior submatriz triangular R11 regente na fatoração QR com pivoteamento de A cujo número de condicionamento estimado 1tol O valor padrão de tol é sqrteps X matriz de reais ou complexos n x p Descrição XlsqAB computa a solução de mínimo quadrado de menor norma da equação AXB enquanto XA B computa uma solução de mínimo quadrado com no máximo postoA componentes nãonulos por coluna Referências lsq é baseado nas funções Lapack DGELSY para matrizes de reais e ZGELSY para matrizes de complexos Exemplos Construindo os dados x110 y13x453randxnormal y218x052randxnormal plot2dxy1y223 Achando a regressão linear AxonesxBy1y2 XlsqAB y1eX11xX21 y2eX12xX22 plot2dxy1ey2e23 Diferença entre lsqAb e Ab Arand42rand23uma matriz de posto 2 brand41 X1lsqAb X2Ab AX1b AX2b os resíduos são os mesmos lsq 1389 Ver Também backslash inv pinv rank 1390 Name lu fatores LU de eliminação Gaussiana LU luA LUE luA Parâmetros A matriz de reais ou complexos m x n L matriz de reais ou complexos m x minmn U matriz de reais ou complexos minmn x n E uma matriz de permutação n x n Descrição LU luA produz duas matrizes L e U tais que A LU com U triangular superior e EL triangular infeiror para uma matriz de permutação E Se A tem posto k as linhas de k1 a n de U são zeros LUE luA produz três matrizes L U e E tais que EA LU com U triangular superior e EL l triangular inferior para uma matriz de permutação E Se A é uma matriz de reais usando as funções lufact e luget é possível obter as matrizes de permutação e também quando A não é de posto cheio a compressão de colunas da matriz L Exemplos arand44 lulua normlua hrklufactsparsea função lufact com matrizes esparsas PLUQlugeth ludelh PfullPLfullLUfullUQfullQ normPLUQa P e Q são as matrizes de permutação Ver Também lufact luget lusolve qr svd Função Usada As decomposições de lu são baseadas nas rotinas de Lapack DGETRF para matrizes reais e ZGETRF para o caso de matrizes complexas 1391 Name lyap equação de Lyapunov XlyapACc XlyapACd Parâmetros A C matrizes quadradas de reais C deve ser simétrica Descrição X lyapACflag resolve as equações matriciais de tempo contínuo ou de tempo discreto de Lyapunov AX XA C flagc AXA X C flagd Perceba que existe uma única solução se e só se um autovalor de A não é um autovalor de A flagc ou 1 sobre um autovalor de A flagd Exemplos Arand44CrandACCC XlyapACc AX XA C XlyapACd AXA X C Ver Também sylv ctrgram obsgram 1392 Name nlev algoritmo de Leverrier numdennlevAz rmax Parâmetros A matriz quadrada de reais z string rmax parâmetro opcional ver bdiag Descrição numdennlevAz rmax computa zeyeA1 por diagonalização por blocos de A seguido pelo algoritmo de Leverrier em cada bloco Este algoritmo é melhor que o algoritmo usual de Leverrier mas ainda não está perfeito Exemplos Arand33xpoly0x NUMdennlevAx cleandenpolyAx cleanNUMdeninvxeyeA Ver Também coff coffg glever ss2tf Autores F Delebecque S Steer INRIA 1393 Name orth base ortogonal QorthA Parâmetros A matriz de reais ou complexos Q matriz de reais ou complexos Descrição QorthA retorna Q uma base ortogonal para o gerado de A ImQ ImA e QQeye O número de colunas de Q é o posto de A como determinado pelo algoritmo QR Exemplos Arand53rand34 XdimrowcompAXX svdorthAX1dim Ver Também qr rowcomp colcomp range 1394 Name pbig autoprojeção QMpbigAthresflag Parâmetros A matriz quadrada de reais thres número real flag string c ou d QM matrizes de reais Descrição Projeção sobre um autosubespaço associado aos autovalores de parte real thres flagc ou com magnitude thres flagd A projeção é definida por QM Q tem postocoluna cheio M tem postolinha cheio e MQeye Se flagc os autovalores de MAQ autovalores de A com parte real thres Se flagd os autovalores de MAQ autovalores de A com magnitude thres Se flagc e se Q1M1 fatoração em posto cheio fullrf de eyeQM então os auto valores de M1AQ1 autovalores de A com parte real thres Se flagd e se Q1M1 fatoração em posto cheio fullrf de eyeQM então os auto valores de M1AQ1 autovalores de A com magnitude thres Exemplos Adiag123XrandAAinvXAX QMpbigA15d specMAQ Q1M1fullrfeyeQM specM1AQ1 Ver Também psmall projspec fullrf schur Autor F D 1988 Função Usada pbig é baseada na forma ordenada de Schur função do Scilab schur 1395 Name pencan forma canônica de feixe de matrizes QMi1pencanFs QMi1pencanEA Parâmetros Fs um feixe regular sEA EA duas matrizes quadradas de reais QM duas matrizes nãosingulares de reais i1 inteiro Descrição Dado o feixe regular FssEA pencan retorna as matrizes Q e M tais que MsEAQ está na forma canônica MEQ é uma matriz de blocos I0 0N com N nilpotente e i1 tamanho da matriz acima I MAQ é uma matriz de blocos Ar0 0I Exemplos Frandpencil12123 Frand66Frand66 QMi1pencanF WcleanMFQ rootsdetW1i11i1 detW22 Ver Também glever penlaur rowshuff Autor F D 1396 Name penlaur Laurent coefficients of matrix pencil SiPiDiorderpenlaurFs SiPiDiorderpenlaurEA Parâmetros Fs um feixe regular sEA E A duas matrizes quadradas de reais SiPiDi três matrizes quadradas de reais order inteiro Descrição penlaur computa os primeiros coeficientes de Laurent de sEA1 no infinito sEA1 Sis Pi sDi em s infinito order ordem da singularidade ordemíndice1 O feixe de matrizes FssEA deve ser invertível Para um feixe de índice 0 Pi Di são zero e SiinvE Para um feixe de índice 1 order0Di 0 Para feixes de índices maiores os termos s2 Di2 s3 Di3 são dados por Di2DiADi Di3DiADiADi até Diorder Observação Versão experimental há problemas quando se tem malcondicionamento desoEA Exemplos Frandpencil12123 Frand66Frand66EApen2eaF SiPiDipenlaurF BfsBischisgleverF normcoeffBis1Di1 Ver Também glever pencan rowshuff Autor F Delebecque INRIA19881990 1397 Name pinv pseudoinversa pinvAtol Parâmetros A matriz de reais ou complexos tol número real Descrição X pinvA produz uma matriz X de mesma dimensão que A tal que AXA A XAX X e ambas AX e XA são Hermitianas A computação é baseada em SVD e qualquer valor singular abaixo da tolerância é tratado como zero esta tolerância é acessada por XpinvAtol Exemplos Arand52rand24 normApinvAAA1 Ver Também rank svd qr Função Usada pinv é baseada na decomposição em valores singulares função do Scilab svd 1398 Name polar forma polar RoThetapolarA Parâmetros A matriz quadrada de reais ou complexos Ro matriz de reais Theta matriz de reais ou complexos Descrição RoThetapolarA retorna a forma polar de A ie ARoexpmiThetaRo simétrico 0 e Theta hermitiano 0 Exemplos Arand55 RoThetapolarA normARoexpmiTheta1 Ver Também expm svd Autor F Delebecque INRIA 1399 Name proj projeção P projX1X2 Parâmetros X1X2 duas matrizes reais com igual número de colunas P matriz de projeção de real P2P Descrição P é a projeção sobre X2 paralela a X1 Ver Também X1rand52X2rand53 PprojX1X2 normP2P1 traceP Este é dimX2 QMfullrfP svdQX2 spanQ spanX2 See Also projspec orth fullrf Autor F D 1400 Name projspec operadores espectrais SPDiprojspecA Parâmetros A matriz quadrada S P D matrizes quadradas i inteiro índice do autovalor zero de A Descrição Características espectrais de A em 0 S resolvente reduzido em 0 S InversodeDrazinA P projeção espectral em 0 D operador nilpotente em 0 index índice do autovalor 0 Temse seyeA1 Di1si Ds2 Ps S sS2 ao redor da singularidade s0 Exemplos deffjjdrnnjzerosnnfor k1n1jkk11end Asysdiagjdrn3jdrn2rand22Xrand77 AXAinvX SPDindexprojspecA index tamanho do bloco J traceP soma das dimensões dos blocos J ASeyeP normDindex1 Ver Também coff Autor F D 1401 Name psmall projeção espectral QMpsmallAthresflag Parameters A matriz quadrada de reais thres número real flag string c ou d QM matrizes de reais Description Projeção sobre autosubespaço associado com autovalores com parte real thres flagc ou com módulo thres flagd A projeção é definda por QM Q é de postocoluna cheio M é de postolinha cheio e MQeye Se flagc os autovalores de MAQ autovalores de A com parte real thres Se flagd os autovalores de MAQ autovalores de A com magnitude thres Se flagc e se Q1M1 fatoração em posto cheio fullrf de eyeQMentão os auto valores de M1AQ1 autovalores de A com parte real thres Se flagd e se Q1M1 fatoração em posto cheio fullrf de eyeQM então os auto valores de M1AQ1 autovalores de A com magnitude thres Examples Adiag123XrandAAinvXAX QMpsmallA25d specMAQ Q1M1fullrfeyeQM specM1AQ1 See Also pbig proj projspec Authors F Delebecque INRIA 1988 Used Functions Esta função é baseada na forma de Schur ordenada Função do Scilab schur 1402 Name qr QR decomposição QRqrX e QREqrX e QRrkEqrX tol Parâmetros X matriz de reais ou complexos tol número real nãonegativo Q matriz quadrada ortogonal ou unitária R matriz com as mesmas dimensões de X E matriz de permutação rk inteiro posto QR de X Descrição QR qrX pproduz uma matriz triangular superior R de mesma dimensão que X e uma matriz ortogonal unitária no caso de matriz de complexos Q tais que X QR QR qrXe produz um economia de tamanho Se X é mporn com m n então apenas as primeiras n colunas de Q são computadas assim como as primeiras n linhas de R De QR X segue que a késima coluna da matriz X é expressa como combinação linear das k primeiras colunas de Q com coeficientes R1k Rkk As k primeiras colunas de Q formam uma base ortogonal para o subespaço gerado pelas k priemiras colunas de X Se a coluna k de X ie Xk é uma combinação linear das p primeiras colunas de X então as entradas de Rp1k Rkk são zeros Neste caso R é trapezoidal superior Se X tem posto rk as linhas Rrk1 Rrk2 são zeros QRE qrX produz uma matriz de permutação de colunas E uma matriz triangular superior R com elementos na diagonal decrescentes e uma matriz ortogonal ou unitaria Q tais que XE QR Se rk é o posto de X as rk primeiras entradas ao longo da diagonal de R ie R11 R22 Rrkrk são todas diferentes de zero QRE qrXe produz uma economia de tamanho Se X ié mporn com m n então apenas as n primeiras colunas de Q são computadas tanto quanto as n priemiras linhas de R QRrkE qrX tol retorna rk estimativa do posto de X ie rk é o número elementos da diagonal de R que são maiores que um dado limiar tol QRrkE qrX retorna rk estimativa do posto de X ie rk é o número de elementos da diagonal de R que são maiores que tolR11epsmaxsizeR Veja rankqr para uma fatoração QR que revela o posto usando o número de condicionamento de R qr 1403 Exemplos fatoração QR caso genérico X é alta posto cheio Xrand52QRqrX QX R X é gorda posto cheio Xrand23QRqrX QX R coluna 4 de X é uma combinação linear das colunas 1 e 2 Xrand85X4X1X2 QRqrX R R4 X tem posto 2 linhas 3 a de R são zero Xrand82rand25QRqrX R Avaliando o posto rk pivotação por colunas gt rk primeiras As entradas diagonais de R são nãonulas Arand52rand25 QRrkE qrA1d10 normQAR svdAQ1rk spanA spanQ1rk spangerado Ver Também rankqr rank svd rowcomp colcomp Funções Usadas A decomposição qr é baseada nas rotinas de Lapack DGEQRF DGEQPF DORGQR para as matrizes de reais ZGEQRF ZGEQPF ZORGQR para as matrizes de complexos 1404 Name quaskro forma quasiKronecker QZQdZdnumbepsnumbetaquaskroF QZQdZdnumbepsnumbetaquaskroEA QZQdZdnumbepsnumbetaquaskroFtol QZQdZdnumbepsnumbetaquaskroEAtol Parâmetros F feixe de matrizes de reais FsEA spoly0s EA duas matrizes reais de iguais dimensões tol número real tolerância valor padrão1d10 QZ duas matrizes quadradas ortogonais QdZd dois vetores de inteiros numbeps vetor de inteiros Descrição Forma quasiKronecker de um feixe de matrizes quaskro computa duas matrizes ortogonais Q Z que põem o feixe FsE A na forma triangular superior sEepsAeps X X O sEinfAinf X QsEAZ O sErAr As dimensões dos blocos são dadas por epsQd1 x Zd1 infQd2 x Zd2 r Qd3 x Zd3 O bloco inf contém os modos infinitos do feixe O bloco f contém os modos finitos do feixe A estrutura dos blocos epsilon é dada por numbeps1 de blocos eps de tamanho 0 x 1 numbeps2 de blocos eps de tamanho 1 x 2 numbeps3 de blocos eps de tamanho 2 x 3 etc quaskro 1405 A forma completa de quatro blocos de Kronecker é dada pela função kroneck que chama a função quaskro sobre o feixe pertransposto sErAr O código é retirado de T Beelen Ver Também kroneck gschur gspec 1406 Name randpencil feixe aleatório Frandpencilepsinfifineta Parâmetros eps vetor de inteiros infi vetor de inteiros fin vetor de reais ou polinômio mônico ou vetor de polinômios mônicos eta vetor de inteiros F feixe de matrizes de reais FsEA spoly0s Descrição Função utilitária Frandpencilepsinfifineta retorna um feixe aleatório F com dada estrutura de Kronecker A estrutura é dada por epseps1epsk estrutura de blocos ep silon tamanho eps1xeps11 finl1ln conjunto de autovalores finitos assumidos como reais possivelmente infik1kp tamanho de blocos J no infinito ki1 in fi se não há blocos J etaeta1etap estrutura dos blocos eta size eta11xeta1 epsis devem ser 0 etais devem ser 0 infis devem ser 1 Se fin é um polinômio mônico o bloco finito admite raízes de fin como autovalores Se fin é um vetor de polinômios eles são os divisores elementares finitos de F ie as raízes de pi são autovalores finitos de F Exemplos Frandpencil0121013 QZQdZdnumbepsnumbetakroneckF Qd Zd spoly0s Frandpencil12s32 feixe regular detF Ver Também kroneck pencan penlaur 1407 Name range Imagem gerado de Ak XdimrangeAk Parâmetros A matriz de reais ou complexos que se assume quadrada se k1 k inteiro X matriz ortonormal dim inteiro dimensão de subespaço Descrição Computação da imagem de Ak as primeiras dim colunas de X geram a imagem de Ak As últimas linhas de X geram o complemento ortogonal da imagem XX é a matriz identidade Exemplos Arand42rand24 4 vetores colunas 2 independentes XdimrangeA1dim computando a imagem y1Arand41 um vetor que está na imagem de A y2rand41 um vetor que não está na imagem de A normXdim1y1 as últimas entradas são zeros y1 está na imagem de A normXdim1y2 as últimas entradas não são zeros IX1dim I é uma base para a imagem coeffsX1dimy1 componentes de y1 relativos à base I normIcoeffsy1 verificando Ver Também fullrfk rowcomp Autor F D INRIA Função Usada A função range é baseada na função rowcomp que usa decomposição svd decomposição em valores singulares 1408 Name rank posto irankX irankXtol Parâmetros X matriz de reais ou complexos tol número real nãonegativo Descrição rankX é o posto numérico de X ie o número de valores singulares de X que são maiores que normsizeXinf normX eps rankXtol é o número de valores singulares de X que são maiores que tol Note que o valor padrão de tol é proporcional a normX Como conseqüência rank1d80001d80 é 2 Exemplos rank1d80001d80 rank1001d80 Ver Também svd qr rowcomp colcomp lu 1409 Name rankqr fatoração QR com revelação do posto QRJPVTRANKSVALrankqrA RCONDJPVT Parâmetros A matriz de reais ou complexos RCOND número real usado para determinar o posto efetivo de A que é definido como sendo a ordem da maior submatriz regente triangular R11 na fatoração QR com pivoteamento de A cujo número de condicionamento estimado é 1RCOND JPVT vetor de inteiros nas entradas se JPVTi não é 0 a iésimo coluna de A é permtutada para a frente de AP senão a coluna i é uma coluna livre Na saída se JPVTi k então a i ésima coluna de AP era a késima coluna de A RANK posto efetivo de A ie a ordem da submatriz R11 É o mesmo que a ordem da submatriz T1 na fatoração ortogonal completa de A SVAL vetor de reais com 3 componentes as estimativas de alguns dos valores singulares do fator tri angular R SVAL1 é o maior valor singular de R1RANK1RANK SVAL2 é o menor valor singular de R1RANK1RANK SVAL3 é o menor valor singular de R1RANK11RANK1 se RANK MINMN ou de R1RANK1RANK caso contrário Descrição Computa opcionalmente uma fatoração QR com revelação do posto de uma matriz de reais geral MporN ou de complexos A que pode ser deficiente de posto e estima seu posto efetivo usando estimativa de condição incremental A rotina usa uma fatoração QR com pivoteamento de colunas A P Q R onde R R11 R12 0 R22 com R11 definida como a maior submatriz regente cujo número de condição estimado é menor que 1RCOND A ordem de R11 RANK é o posto efetivo deA Se a fatoração triangular revela o posto que será o caso se as colunas regentes forem bem condi cionadas então SVAL1 também será uma estimativa para o maior valor singular de A e SVAL2 e SVAL3 serão estimativas para o RANKésimo e RANK1ésimo valores singulares de A re spectivamente Examinandose estes valores podese confirmar que o posto é bem definido a respeito do valor es colhido de RCOND A razão SVAL1SVAL2 é uma estimativa do número de condicionamento de R1RANK1RANK rankqr 1410 Exemplos Arand53rand37 QRJPVTRANKSVALrankqrAeps Ver Também qr rank Funções Usadas Rotinas da biblioteca Slicot MB03OD ZB03OD 1411 Name rcond número de condicionamento inverso rcondX Parâmetros X matriz quadrada de reais ou complexos Descrição rcondX é uma estimativa para a recíproca da condição de X na norma1 Se X é bem condicionada rcondX é próximo a 1 Senão rcondX é próximo a 0 rzrcondX ajusta r a rcondX e retorna z tal que normXz1 rnormX1normz1 Portanto se rcond é pequeno z é um vetor do núcleo Exemplos Adiag110 rcondA A110000001 rcondA Ver Também svd cond inv 1412 Name rowcomp compressão de linhas imagem WrkrowcompA flag tol Parâmetros A matriz de reais ou de complexos flag string opcional com valores possíveis svd ou qr O valor padrão é svd tol número real nãonegativo opcional O valor padrão é sqrtepsnormA1 W matriz quadrada nãosingular matriz mudança de base rk inteiro posto de A Descrição Compressão de linhas de A Ac WA é uma matriz de linhas comprimidas ie AcAf0 com Af de postolinha cheio flag e tol são parâmetros opcionais flagqr ou svd o padrão é svd tol é um parâmetro de tolerância As rk primeiras colunas de W geram a imagem de A As rk primeiras linhas do topo de W geram a imagem de linha de A Um vetor não nulo x pertence à ImA see só se Wx é de linhas comprimidas de acordo com Ac ie a norma de seus últimos componentes é pequena com relação a dos seus primeiros componentes Exemplos Arand52rand24 4 vetores colunas 2 independentes XdimrowcompAXpX svdXp1dimA spanA spanXp1dim spangerado xArand41 x pertence a spanA yXx normydim1normy1dim pequeno Ver Também colcomp fullrf fullrfk Autor F D INRIA rowcomp 1413 Função Usada A função rowcomp é baseada nas decomposições svd decomposição em valores singulares ou qr 1414 Name rowshuff algoritmo de embaralhamento WsFs1rowshuffFs alfa Parâmetros Fs feixe quadrado de reais Fs sEA Ws matriz de polinômios Fs1 feixe quadrado de reais F1s sE1 A1 com E1 nãosingular alfa número real alfa 0 é o valor padrão Descrição Algoritmo de embaralhamento dado o feixe FssEA retorna WsWs matriz quadrada de polinômios tal que Fs1 sE1A1 WssEA é um feixe com matriz E1 nãosingular Isto é possível se e só se o feixe Fs sEA é regular ie invertível O grau de Ws é igual ao índice do feixe Os pólos no infinito de Fs asão colocados para alfa e os zeros de Ws estão em alfa Note que sEA1 sE1A11 Ws WssEA1 Ws Exemplos Frandpencil2123 Frand55Frand55 feixe regular 5 x 5 com três avaliações em 123 WsF1rowshuffF1 E1A1pen2eaF1 svdE1 E1 nãosingular rootsdetWs cleaninvFinvF1Ws1d7 Ver Também pencan glever penlaur Autor F D 1415 Name rref computa a matrizlinha reduzida a forma escada por transformações de LU RrrefA Parâmetros A matriz m x n com entradas escalares R matriz m x n forma escada de A Descrição rref computa a forma escada de linhas reduzidas da matriz dada pela decomposição esquerda LU Se for necessária a transformação usada basta chamar XrrefAeyemm A forma escada de linhas reduzidas R é X1n e a transformação esquerda L ié dada por Xn1nm tal como LAR Exemplos A1 23 45 6 XrrefAeye33 RX12 LX35LA Ver Também lu qr 1416 Name schur decomposição ordenada de Schur de matrizes e feixes UT schurA Udim T schurAflag Udim T schurAextern1 AsEs QZschurAE AsEs QZdim schurAEflag Zdim schurAEflag AsEs QZdim schurAEextern2 Zdim schurAEextern2 Parâmetros A matriz quadrada de reais ou complexos E matriz quadrada de reais ou complexos com as mesmas dimensões de A flag string c oud extern1 uma external função externa veja abaixo extern2 uma external veja abaixo U matriz quadrada ortogonal ou unitária Q matriz quadrada ortogonal ou unitária Z matriz quadrada ortogonal ou unitária T matriz quadrada triangular superior ou quasitriangular As matriz quadrada triangular superior ou quasitriangular Es matriz quadrada triangular superior dim inteiro Descrição Formas de Schur formas ordenadas de Schur de matrizes e feixes FORMA DE SCHUR MATRICIAL Forma de Schur usual UT schurA produz uma matriz de Schur T e uma matriz unitária U tais que A UTU e UU eyeU Por si mesmo schurA retorna T Se A é de complexos a schur 1417 Forma de Schur Complexa é retornada na matriz T A Forma de Schur Complexa é triangular superior com os autovalores de A na diagonal Se A é de reais a Forma de Schur Real é retor nada A Forma de Schur Real tem autovalores reais na diagonal e os autovalores complexos em blocos 2por2 na diagonal Formas de Schur ordenadas UdimschurAc rretorna uma matriz unitária U que transforma A em uma forma de Schur Ainda as primeiras dim colunas de U formam uma base para o autoespaço de A associado aos autovalores com partes reais negativas autoespaço de tempo contínuo estável UdimschurAd retorna uma matriz unitária U que transforma A em uma forma de Schur Ainda as primeiras dim colunas de U geram uma base do autoespaço de A associ ado aos autovalores de magnitude menor que 1 autoespaço de tempo discreto estável UdimschurAextern1 retorna uma matriz unitária U que transforma A em uma forma de Schur Ainda as dim primeiras colunas de U geram uma base para o autoespaço de A associado aos autovalores que são selecionados pela external extern1 veja exter nal para detalhes Esta external pode ser descrita por uma função do Scilab ou por um procedure de C ou FORTRAN Uma Função do Scilab Se extern1 é descrita por uma função do Scilab deve ter a seguinte seqüência de chamamento sextern1Ev onde Ev é um autovalor e s um booleano Um Procedure C ou FORTRAN Se extern1 é descrita por uma função de C ou FORTRAN deve ter a seguinte seqüência de chamamento int extern1double EvR double EvI onde EvR e EvI são partes real e complexa de autovalor Valor verdadeiro ou diferente de zero retornado significa autovalor selecionado FORMAS DE SCHUR DE FEIXES Forma de Schur de Feixe Usual AsEs schurAE produz uma matriz As quasitriangular e uma matriz triangular Es que são a forma generalizada de Schur do par A E AsEsQZ schurAE retorna ainda duas matrizes unitárias Q e Z tais que AsQAZ e EsQEZ Formas de Schur Ordenadas AsEsZdim schurAEc retorna a forma real generalizada de Schur do feixe sEA Ainda as primeiras dim colunas de Z geram uma base para o autoespaço di reito associado aos autovalores com partes reais negativas autoespaço de tempo contínuo generalizado AsEsZdim schurAEd retorna a forma real generalizada de Schur do feixe sEA Ainda as dim primeiras colunas de Z formam uma base para o autoespaço direito associado aos autovalores de magnitude menor que 1 autoespaço de tempo discreto generalizado AsEsZdim schurAEextern2 retorna a forma real generalizada de Schur do feixe sEA Ainda as dim primeiras colunas de Z formam uma base para o autoespaço direito associado aos autovalores do feixe que são selecionados de acordo com a regra que é dada pela external extern2 veja external para detalhes Esta external pode ser descrita por uma função do Scilab ou por um proce dure de C ou FORTRAN schur 1418 Função do Scilab Se extern2 é descrita por uma função do Scilab deve ter a seqüência de chamamen to sextern2AlphaBeta onde Alpha e Beta definem um autovalor gener alizado e s um booleano Um Procedure C ou FORTRAN Se a external extern2 é descrita por um procedure C ou FORTRAN deve ter a seqüência de chamamento int extern2double AlphaR double AlphaI double Beta se A e E são matrizes de reais e int extern2double AlphaR double AlphaI double BetaR double BetaI se A ou E é matriz de complexos Alpha e Beta definem o autovalor generalizado Um valor verdadeiro ou diferente de zero siginfica autovalor generalizado selecionado Referências As computações da forma de Schur matricial são baseadas nas rotinas de Lapack DGEES e ZGEES As computações da forma de Schur de feixes são baseadas nas rotinas de Lapack DGGES e ZGGES Exemplos SCHUR FORM OF A MATRIX Adiag092209XrandAAinvXAX UTschurAT UdimTschurAc T1dim1dim stable cont eigenvalues function tmytestEvtabsEv095endfunction UdimTschurAmytest T1dim1dim The same function in C a Compiler is required cd TMPDIR Cint mytestdouble EvR double EvI the C code if EvR EvR EvI EvI 09025 return 1 else return 0 mputlCTMPDIRmytestc build and link lpilibforlinkmytestmytestcc linklpmytestc run it UdimTschurAmytest SCHUR FORM OF A PENCIL F1s 0 1 015s 0 schur 1419 0 02s 0 1 0 0 2s AcoeffF0EcoeffF1 AsEsQZschurAE QFZ It is AssEs AsEsZdim schurAEc function tmytestAlphaBetatrealAlpha0endfunction AsEsZdim schurAEmytest the same function in Fortran a Compiler is required ftninteger function mytestfaraib the fortran code double precision araib mytestf0 ifarlt00d0 mytestf1 end mputl ftnTMPDIRmytestff build and link lpilibforlinkmytestfmytestffF linklpmytestff run it AsEsZdim schurAEmytestf Ver Também spec bdiag ricc pbig psmall 1420 Name spaninter interseção de subespaços XdimspaninterAB tol Parâmetros A B duas matrizes de reais ou de complexos com igual número de linhas X matriz quadrada ortogonal ou unitária dim inteiro dimensão do subesbaço ImA inter ImB Descrição Computa a intereseção de ImA e ImB As primeiras dim colunas de X geram esta interseção ie X1dim é uma base ortogonal para ImA inter ImB Na base X A e B são respectivamente representados por XA e XB tol é um limiar sqrteps é o valor padrão Exemplos Arand53rand34 A é 5 x 4 rank3 BA2rand51rand22 XdimspaninterAB X1X1dim A interseção svdAsvdX1A X1 no geradoA spanA svdBsvdBX1 X1 no geradoB spanB Ver Também spanplus spantwo Autor F D 1421 Name spanplus soma de subespaços XdimdimaspanplusABtol Parâmetros A B duas matrizes de reais ou complexos com igual número de linhas X matriz quadrada ortogonal ou unitária dim dima inteiros dimensões de subespaços tol número real nãonegativo Descrição Computa a base X tal que as primeiras dima colunas de X geram ImA e as dimdima colunas seguintes formam uma base de AB em relação a A As dim primeiras colunas de X formam uma base para AB Temse a seguinte forma canônica para AB dima rows XAB0 dimdima rows 00 tol é um argumento opcional ver código da função Exemplos Arand62rand25 rankA2 postoA2 BA1rand62rand33 dois vetores adicionais independentes XdimdimAspanplusAB dimA dim Ver Também spaninter iminv spantwo Autor F D 1422 Name spantwo soma e interseção de subespaços XpdimadimbdimspantwoAB tol Parâmetros A B duas matrizes de reais ou complexos com igual número de linhas Xp matriz quadrada nãosingular dima dimb dim inteiros dimensões dos subespaços tol número real nãonegativo Descrição Dadas duas matrizes A e B com o mesmo número de linhas retorna uma matriz quadrada Xp não singular mas não necessariamente ortogonal tal que A1 0 dimdimb linhas XpABA2B2 dimadimbdim linhas 0 B3 dimdima linha 0 0 As primeiras dima colunas de invXp geram ImA As colunas de dimdimb1 até dima de invXp geram a interseção de ImA e ImB As primeiras dim colunas de invXp geram ImAImB As colunas de dimdimb1 até dim de invXp geram ImB A matrix A1A2 tem postolinha cheio postoA a matrix B2B3 tem postolin ha cheio postoB a matriz A2B2 tem postolinha postoA inter B e a matriz A10A2B20B3 tem postolinha cheio postoAB Exemplos A1004 5678 001112 00016 B1200C4001 Slss2sssyslincABCrandA noXcontrSlASlBCOX1no Parte controlável uoYunobsSlASlCUOY1uo Parte inobservável XpdimcdimudimspantwoCOUO Decomposição de Kalman Slcanss2ssSlinvXp spantwo 1423 Ver Também spanplus spaninter Autor F D 1424 Name spec autovalores de matrizes e feixes evalsspecA RdiagevalsspecA evalsspecAB alphabetaspecAB alphabetaZspecAB alphabetaQZspecAB Parâmetros A matriz quadrada de reais ou complexos B matriz quadrada de reais ou complexos com as mesmas dimensões que A evals vetor de reais ou complexos os autovalores diagevals matriz diagonal de reais ou complexos autovalores ao longo da diagonal alpha vetor de reais ou complexos albe fornece os autovalores beta vetor de reais albe fornece os autovalores R matriz quadrada de reais ou complexos invertível autovetores direitos da matriz Q matriz quadrada de reais ou complexos invertível autovetores esquerdos do feixe Z matriz quadrada de reais ou complexos invertível autovetores direitos do feixe Descrição evalsspecA retorna no vetor evals os autovalores Rdiagevals specA retorna na matriz diagonal evals os autovalores e em R os autovetores direitos evalsspecAB retorna o espectro do feixe de matrizes A s B ie as raízes da matriz de polinômios s B A alphabeta specAB retorna o espectro do feixe de matrizes A s B ie as raízes da matriz de polinômios A s B Auto valores generalizados alpha e beta são tais que a matriz A alphabeta B é uma matriz singular Os autovalores são dados por albe e se betai 0 o iésimo autovalor está no infinito Para B eyeA alphabeta é specA É usualmente representado pelo par alphabeta já que há uma interpretação razoável para beta0 e até mesmo para os dois sendo zero spec 1425 alphabetaR specAB retorna ainda a matriz R de autovetores direitos generalizados do feixe albeQZ specAB rretorna ainda a matriz Q e Z de autovetores esquerdos e direitos generalizados do feixe Referências As computações de autovalores de matrizes são baseadas nas rotinas Lapack DGEEV e ZGEEV quando as matrizes não são simétricas DSYEV e ZHEEV quando as matrizes são simétricas Uma matriz de complexos simétrica tem termos fora da diagonal conjugados e termos diagonais reais As computações de autovalores de feixes são baseadas nas rotinas Lapack DGGEV e ZGGEV Matrizes de reais e de complexos Devese notar que o tipo das variáveis de saída tais como evals ou R por exemplo não é necessari amente o mesmo das que das matrizes de entrada A e B No parágrafo seguinte análisamos o tipo das variáveis de saída no caso onde nos casos onde se computa os autovalores e autovetores de uma única matriz A Matriz A de reais Simétrica Os autovetores e autovalores são reais Não simétrica Os autovetores e autovalores são complexos Matriz A de complexos Simétrica Os autovalores são reais mas os autovetores são complexos Não simétrica Os autovetores e autovalores são complexos Exemplos AUTOVALORES DA MATRIZ Adiag123 Xrand33 AinvXAX specA xpoly0x poldetxeyeA rootspol SXbdiagA spec 1426 cleaninvXAX AUTOVALORES DO FEIXE Arand33 albeR specAeyeA albe cleaninvRAR exibindo os autovalores matriz genérica AAirandA ErandA rootsdetAsE caso de complexos Ver Também poly det schur bdiag colcomp 1427 Name sqroot fatoração hermitiana WW sqrootX Parâmetros X matriz simétrica nãonegativa definida de reais ou complexos Descrição Retorna W tal que XWW usa SVD Exemplos Xrand52rand25XXX WsqrootX normWWX1 Xrand52irand52XXX WsqrootX normWWX1 Ver Também chol svd 1428 Name squeeze remoção de dimensões singletons hypOut squeezehypIn Parâmetros hypIn hipermatriz ou matriz do tipo constante hypOut hipermatriz ou matriz do tipo constante Descrição Remove dimensões singletons de uma hipermatriz ie qualquer dimensão para a qual o tamanho é 1 Se a entrada é uma matriz ela não é afetada Ver Também hypermat hypermatrices Autores Eric Dubois JeanBaptiste Silvy 1429 Name sva aproximação em valores singulares UsVsvaAk UsVsvaAtol Parâmetros A matriz de reais ou complexos k inteiro tol número real nãonegativo Descrição Aproximação em valores singulares USVsvaAk com k inteiro 1 retorna US e V tais que BUSV é a melhor aproximação L2 de A com postoBk USVsvaAtol com tol real retorna US e V tais que BUSV e a normaL2 de A B é no máximo tol Exemplos Arand54rand45 UsVsvaA2 BUsV svdA svdB cleansvdAB Ver Também svd 1430 Name svd decomposição em valores singulares ssvdX USVsvdX USVsvdX0 obsolete USVsvdXe USVrksvdX tol Parâmetros X matriz de reais ou complexos s vetor de reais valores singulares S matriz diagonal de reais valores singulares UV matrizes quadradas ortogonais ou unitárias vetores singulares tol número real Descrição USV svdX produz uma matriz diagonal S com dimensão igual a de X e com elementos da diagonal nãonegativos em ordem decrescente e matrizes unitárias U e V tais que X USV USV svdX0 produz a decomposição com economia de tamanho Se X é mporn com m n então apenas as primeiras n colunas de U são computadas e S é nporn s svdX por si mesmo retorna um vetor s contendo os valores singulares USVrksvdXtol fornece também rk o posto numérico de X ie ie o número de val ores singulares maiores que tol O valor default de tol é o mesmo que em rank Exemplos Xrand42rand24 svdX sqrtspecXX Ver Também rank qr colcomp rowcomp sva spec Função Usada Decomposições svd são baseadas nas rotinas Lapack DGESVD para matrizes de reais e ZGESVD no caso de matrizes de complexos 1431 Name sylv equação de Sylvester sylvABCflag Parâmetros ABC três matrizes de reais de dimensões apropriadas flag string c ou d Descrição X sylvABCc computa X solução da equação de tempo contínuo de Sylvester AXXBC XsylvABCd computa X solução da equação de tempo discreto de Sylvester AXBXC Exemplos Arand44Crand43Brand33 X sylvABCc normAXXBC XsylvABCd normAXBXC Ver Também lyap 1432 Name trace traço de uma matriz traceX Parâmetros X matriz de reais ou complexos matriz de polinômios ou de razões de polinômios Descrição traceX é o traço da matriz X É o mesmo que sumdiagX Exemplos Arand33 traceAsumspecA Ver Também det Parte XXIV Localização 1434 Name dgettext get text translated into the current locale and a specific domain domain msgdgettextdomain myString Parameters domain The name of the message domain string the message to be translated Description dgettext get the translation of a string to the current locale in a specified message domain Examples dgettextscilabStartup execution See Also gettext Authors Sylvestre Ledru 1435 Name getdefaultlanguage getdefaultlanguage returns the default language used by Scilab getdefaultlanguage Description getdefaultlanguage returns the default language used by Scilab By default this function should return enUS Examples getdefaultlanguage See Also setlanguage getlanguage Authors Sylvestre Ledru 1436 Name getlanguage getlanguage returns current language used by Scilab getlanguage Description getlanguage returns current language used by Scilab Examples setlanguageenUS getlanguage See Also setlanguage Authors AC Sylvestre Ledru 1437 Name gettext get text translated into the current locale and domain msggettextmyString Parameters string the message to be translated Description gettext get the translation of a string to the current locale in the current domain Examples gettextStartup execution See Also dgettext Authors Sylvestre Ledru 1438 Name LANGUAGE Variable defining the language OBSOLETE Description LANGUAGE is obsolete If you need LANGUAGE add LANGUAGEgetlanguage See Also getlanguage 1439 Name setdefaultlanguage sets and saves the internal LANGUAGE value setdefaultlanguagelanguage Parameters language with languagefr en ruRU zhTW Description setdefaultlanguagelanguage changes current language and save this value in scilab You need to restart scilab if you want to use menus setdefaultlanguage resets language to the system value setdefaultlanguage is used only Windows On others operating systems it returns always f Examples setdefaultlanguageenUS restart scilab getlanguage setdefaultlanguagefrFR restart scilab getlanguage setdefaultlanguage restart scilab See Also getlanguage setlanguage Authors AC 1440 Name setlanguage Sets the internal LANGUAGE value setlanguagelanguage Parameters language with languagefr or en Description setlanguagelanguage changes current language in scilab Examples setlanguageenUS getlanguage setlanguageen getlanguage setlanguagefr getlanguage setlanguagefrFR getlanguage See Also getlanguage Authors AC Parte XXV Otimização e Simulação 1442 Índice 2 Neldermead 1443 fminsearch 1444 neldermead 1453 overview 1474 nmplot 1478 optimget 1489 optimplotfunccount 1491 optimplotfval 1492 optimplotx 1493 optimset 1494 3 Optimization base 1498 optimbase 1499 4 Optimization simplex 1513 optimsimplex 1514 Capítulo 2 Neldermead Neldermead 1444 Nom fminsearch Computes the unconstrained minimimum of given function with the NelderMead al gorithm x fminsearch costf x0 x fminsearch costf x0 options xfvalexitflagoutput fminsearch costf x0 options Description This function searches for the unconstrained minimum of a given cost function The provided algorithm is a direct search algorithm ie an algorithm which does not use the derivative of the cost function It is based on the update of a simplex which is a set of kn1 vertices where each vertex is associated with one point and one function value This algorithm is the NelderMead algorithm Design This function is based on a specialized use of the more general neldermead component Users which want to have a more flexible solution based on direct search algorithms should consider using the neldermead component instead of the fminsearch function Parameters costf The cost function x0 The initial guess options A struct which contains configurable options of the algorithm see below for details x The minimum fval The minimum function value exitflag The flag associated with exist status of the algorithm The following values are available 1 The maximum number of iterations has been reached 0 The maximum number of function evaluations has been reached 1 The tolerance on the simplex size and function value delta has been reached This signifies that the algorithm has converged probably to a solution of the problem Neldermead 1445 output A struct which stores detailed information about the exit of the algorithm This struct contains the following fields outputalgorithm A string containing the definition of the algorithm used ie NelderMead simplex direct search outputfuncCount The number of function evaluations outputiterations The number of iterations outputmessage A string containing a termination message Options In this section we describe the options input argument which have an effect on the algorithm used by fminsearch The options input argument is a data structure which drives the behaviour of fminsearch It allows to handle several options in a consistent and simple interface without the problem of managing many input arguments These options must be set with the optimset function See the optimset help for details of the options managed by this function The fminsearch function is sensitive to the following options optionsMaxIter The maximum number of iterations The default is 200 n where n is the number of variables optionsMaxFunEvals The maximum number of evaluations of the cost function The default is 200 n where n is the number of variables optionsTolFun The absolute tolerance on function value The default value is 1e4 optionsTolX The absolute tolerance on simplex size The default value is 1e4 optionsDisplay The verbose level optionsOutputFcn The output function or a list of output functions The default value is empty optionsPlotFcns The plot function or a list of plotput functions The default value is empty Termination criteria In this section we describe the termination criteria used by fminsearch The criteria is based on the following variables ssize the current simplex size Neldermead 1446 shiftfv the absolute value of the difference of function value between the highest and lowest vertices If both the following conditions ssize optionsTolX and shiftfv optionsTolFun are true then the iterations stop The size of the simplex is computed using the sigmaplus method of the optimsimplex component The sigmamplus size is the maximum length of the vector from each vertex to the first vertex It requires one loop over the vertices of the simplex The initial simplex The fminsearch algorithm uses a special initial simplex which is an heuristic depending on the initial guess The strategy chosen by fminsearch corresponds to the simplex0method flag of the nelderme ad component with the pfeffer method It is associated with the simplex0deltausual 005 and simplex0deltazero 00075 parameters Pfeffers method is an heuristic which is presented in Global Optimization Of LennardJones Atomic Clusters by Ellen Fan It is due to L Pfeffer at Stanford See in the help of optimsimplex for more details The number of iterations In this section we present the default values for the number of iterations in fminsearch The options input argument is an optionnal data structure which can contain the optionsMaxIter field It stores the maximum number of iterations The default value is 200n where n is the number of variables The factor 200 has not been chosen by chance but is the result of experiments performed against quadratic functions with increasing space dimension This result is presented in Effect of dimensionality on the neldermead simplex method by Lixing Han and Michael Neumann This paper is based on Lixing Hans PhD Algorithms in Unconstrai ned Optimization The study is based on numerical experiment with a quadratic function where the number of terms depends on the dimension of the space ie the number of variables Their study shows that the number of iterations required to reach the tolerance criteria is roughly 100n Most ite rations are based on inside contractions Since each step of the NelderMead algorithm only require one or two function evaluations the number of required function evaluations in this experiment is also roughly 100n Output and plot functions The optimset function can be used to configure one or more output and plot functions The output or plot function is expected to have the following definition function myfun x optimValues state Neldermead 1447 The input arguments x optimValues and state are described in detail in the optimset help page The optimValuesprocedure field represent the type of step used during the current iteration and can be equal to one of the following strings the empty string initial simplex expand reflect contract inside contract outside Example In the following example we use the fminsearch function to compute the minimum of the Rosenbrock function We first define the function banana and then use the fminsearch function to search the minimum starting with the initial guess 12 10 In this particular case 85 iterations are performed and 159 function evaluations are function y banana x y 100x2x122 1x12 endfunction x fval exitflag output fminsearch banana 12 1 x fval exitflag output Example with customized options In the following example we configure the absolute tolerance on the size of the simplex to a larger value so that the algorithm performs less iterations Since the default value of TolX for the fminse arch function is 1e4 we decide to use 1e2 The optimset function is used to create an optimization data structure and the field associated with the string TolX is set to 1e2 The opt data structure is then passed to the fminsearch function as the third input argument In this particular case the number of iterations is 70 with 130 function evaluations function y banana x y 100x2x122 1x12 endfunction opt optimset TolX 1e2 x fval exitflag output fminsearch banana 12 1 opt x fval exitflag output Neldermead 1448 Example with a predefined plot function In the following example we want to produce a graphic of the progression of the algorithm so that we can include that graphic into a report without defining a customized plot function The fminsearch function comes with the following 3 predefined functions optimplotfval which plots the function value optimplotx which plots the current point x optimplotfunccount which plots the number of function evaluations In the following example we use the three predefined functions in order to create one graphic repre senting the function value depending on the number of iterations function y banana x y 100x2x122 1x12 endfunction opt optimset PlotFcns optimplotfval x fval fminsearch banana 12 1 opt In the previous example we could replace the optimplotfval function with optimplotx or optim plotfunccount and obtain different results In fact we can get all the figures at the same time by setting the PlotFcns to a list of functions as in the following example function y banana x y 100x2x122 1x12 endfunction myfunctions list optimplotfval optimplotx optimplotfunccount opt optimset PlotFcns myfunctions x fval fminsearch banana 12 1 opt Example with an customized output function In the following example we want to produce intermediate outputs of the algorithm We define the outfun function which takes the current point x as input argument The function plots the current point into the current graphic window with the plot function We use the OutputFcn feature of the optimset function and set it to the output function Then the option data structure is passed to the fminsearch function At each iteration the output function is called back which creates and update an interactive plot While this example creates a 2D plot the user may customized the output function so that it writes a message in the console write some data into a data file etc The user can distinguish between the output function associated with the OutputFcn option and the plot function associated with the PlotFcns option See the optimset for more details on this feature function y banana x y 100x2x122 1x12 endfunction function outfun x optimValues state Neldermead 1449 plot x1x2 endfunction opt optimset OutputFcn outfun x fval fminsearch banana 12 1 opt Example with customized Display option The Display option allows to get some input about the intermediate steps of the algorithm as well as to be warned in case of a convergence problem In the following example we present what happens in case of a convergence problem We set the number of iterations to 10 instead of the default 400 iterations We know that 85 iterations are required to reach the convergence criteria Therefore the convergence criteria is not met and the maximum number of iterations is reached function y banana x y 100x2x122 1x12 endfunction opt optimset MaxIter 10 x fval fminsearch banana 12 1 opt Since the default value of the Display option is notify a message is generated which warns the user about a possible convergence problem The previous script produces the following output Exiting Maximum number of iterations has been exceeded increase MaxIter option Current function value 41355598 Notice that if the Display option is now set to off no message is displayed at all Therefore the user should be warned that turning the Display off should be used at your own risk In the following example we present how to display intermediate steps used by the algorithm We simply set the Display option to the iter value ffunction y banana x y 100x2x122 1x12 endfunction opt optimset Display iter x fval fminsearch banana 12 1 opt The previous script produces the following output It allows to see the number of function evaluations the minimum function value and which type of simplex step is used for the iteration Iteration Funccount min fx Procedure 0 3 242 1 3 2005 initial simplex Neldermead 1450 2 5 5161796 expand 3 7 4497796 reflect 4 9 4497796 contract outside 5 11 43813601 contract inside etc Example with customized output option In this section we present an example where all the fields from the optimValues data structure are used to print a message at each iteration function outfun x optimValues state fc optimValuesfunccount fv optimValuesfval it optimValuesiteration pr optimValuesprocedure mprintf d e d s fc fv it pr endfunction opt optimset OutputFcn outfun x fval fminsearch banana 12 1 opt The previous script produces the following output 3 2420000e001 0 3 2005000e001 1 initial simplex 5 5161796e000 2 expand 7 4497796e000 3 reflect 9 4497796e000 4 contract outside 11 4381360e000 5 contract inside 13 4245273e000 6 contract inside 157 1107549e009 84 contract outside 159 8177661e010 85 contract inside 159 8177661e010 85 Some advices In this section we present some practical advices with respect to the NelderMead method A deeper analysis is provided in the bibliography at the end of this help page as well as in the NelderMead Users Manual provided on Scilabs Wiki The following is a quick list of tips to overcome problems that may happen with this algorithm We should consider the optim function before considering the fminsearch function Because optim uses the gradient of the function and uses this information to guess the local curvature of the cost function the number of iterations and function evaluations is much lower with optim when the function is sufficiently smooth If the derivatives of the function are not available it is still possible to use numerical derivatives combined with the optim function this feature is provided by the derivative and numdiff functions If the function has discontinuous derivatives the optim function provides the nd solver which is very efficient Still there are situations where the cost function is discontinuous or noisy In these situations the fminsearch function can perform well Neldermead 1451 We should not expected a fast convergence with many parameters ie more that 10 to 20 parameters It is known that the efficiency of this algorithm decreases rapidly when the number of parameters increases The default tolerances are set to pretty loose values We should not reduce the tolerances in the goal of getting very accurate results Because the convergence rate of NelderMeads algorithm is low at most linear getting a very accurate solution will require a large number of iterations Instead we can most of the time expect a good reduction of the cost function with this algorithm Although the algorithm practically converges in many situations the NelderMead algorithm is not a provably convergent algorithm There are several known counterexamples where the algorithm fails to converge on a stationnary point and instead converge to a nonstationnary point This situation is often indicated by a repeated application of the contraction step In that situation we simply restart the algorithm with the final point as the new initial guess If the algorithm converges to the same point there is a good chance that this point is a good solution Taking into account for bounds constraints or nonlinear inequality constraints can be done by pena lization methods ie setting the function value to a high value when the constraints are not satisfied While this approach works in some situations it may also fail In this case users might be interested in Boxs complex algorithm provided by Scilab in the neldermead component If the problem is really serious Boxs complex algorithm will also fail and a more powerful solver is necessary Bibliography Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation Spendley W and Hext G R and Himsworth F R American Statistical Association and American Society for Quality 1962 A Simplex Method for Function Minimization Nelder J A and Mead R The Computer Journal 1965 Iterative Methods for Optimization C T Kelley SIAM Frontiers in Applied Mathematics 1999 Algorithm AS47 Function minimization using a simplex procedure ONeill R Applied Statistics 1971 Effect of dimensionality on the neldermead simplex method Lixing Han and Michael Neumann Optimization Methods and Software 21 1 116 2006 Algorithms in Unconstrained Optimization Lixing Han PhD The University of Connecticut 2000 Global Optimization Of LennardJones Atomic Clusters Ellen Fan Thesis February 26 2002 Mc Master University TODO implement the interrupt state of the algorithm add a demo with an interactive output function which draws the plot during the optimization implement the stop of an optimization via the stop output argument of the output function Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 Neldermead 1452 Acknowledgements Michael Baudin would like to thank Lixing Han who kindly sent his PhD thesis See Also optim neldermead optimset optimget optimplotfval optimplotx optimplotfunccount Neldermead 1453 Nom neldermead Provides several direct search optimization algorithms based on the simplex method newobj neldermeadnew this neldermeaddestroy this this neldermeadconfigure thiskeyvalue value neldermeadcget thiskey neldermeaddisplay this value neldermeadget this key this neldermeadsearch this this neldermeadrestart this this result neldermeadfunction this x Description This class provides several direct search optimization algorithms based on the simplex method The optimization problem to solve is the minimization of a cost function with bounds and nonlinear constraints min fx li xi hi i 1n gix 0 i 1nbineq where n number of variables nbineq number of inequality constraints The provided algorithms are direct search algorithms ie algorithms which do not use the derivative of the cost function They are based on the update of a simplex which is a set of kn1 vertices where each vertex is associated with one point and one function value The following algorithms are available Spendley Hext and Himsworth fixed size simplex method This algorithm solves an unconstrained optimization problem with a fixed sized simplex made of kn1 vertices Nelder and Mead variable size simplex method This algorithm solves an unconstrained optimization problem with a variable sized simplex made of kn1 vertices Box complex method This algorithm solves an constrained optimization problem with a variable sized simplex made of an arbitrary k number of vertices k2n is recommended by Box Design The neldermead component is built on top of the optimbase and optimsimplex components Neldermead 1454 Functions The following functions are available newobj neldermeadnew Creates a new neldermead object newobj The new object this neldermeaddestroy this Destroy the given object this The current object this neldermeadconfigure thiskeyvalue Configure the current object with the given value for the given key this The current object key the key to configure The following keys are available verbose set to 1 to enable verbose logging default is 0 verbosetermination set to 1 to enable verbose termination logging default is 0 x0 the initial guess as a n x 1 column vector where n is the number of variables maxfunevals the maximum number of function evalutations default is 100 If this criteria is triggered the status of the optimization is set to maxfuneval maxiter the maximum number of iterations default is 100 If this criteria is triggered the status of the optimization is set to maxiter tolfunabsolute the absolute tolerance for the function value default is 00 tolfunrelative the relative tolerance for the function value default is eps tolfunmethod the method used for the tolerance on function value in the termination criteria The following values are available t f default is f If this criteria is triggered the status of the optimization is set to tolf tolxabsolute the absolute tolerance on x default is 00 tolxrelative the relative tolerance on x default is eps tolxmethod the method used for the tolerance on x in the termination criteria Neldermead 1455 The following values are available t f default is t If this criteria is triggered the status of the optimization is set to tolx function the objective function which computes the value of the cost and the non linear constra ints if any See below for the details of the communication between the optimization system and the cost function costfargument an additionnal argument passed to the cost function outputcommand a command which is called back for output See below for the details of the communication between the optimization system and the output command function outputcommandarg an additionnal argument passed to the output command numberofvariables the number of variables to optimize default is 0 storehistory set to 1 to enable the history storing default is 0 boundsmin the minimum bounds for the parameters as an array of values default is empty ie there are no bounds boundsmax the maximum bounds for the parameters as an array of values default is empty ie there are no bounds nbineqconst the number of inequality constraints default is 0 method the name of the algorithm to use The following methods are available fixed the Spendley et al fixed simplex shape algorithm This algorithm is for unconstrai ned problems ie bounds and non linear constraints are not taken into account variable the NelderMead variable simplex shape algorithm This algorithm is for uncons trained problems ie bounds and non linear constraints are not taken into account box the Box complex algorithm This algorithm takes into account bounds and nonlinear inequality constraints mine the userdefined algorithm associated with the mymethodoption See below for details simplex0method the method to use to compute the initial simplex The first vertex in the simplex is always the initial guess associated with the x0 option The following methods are available Neldermead 1456 given the coordinates associated with the coords0 option are used to compute the initial simplex with arbitrary number of vertices This allow the user to setup the initial simplex by a specific method which is not provided by the current component for example with a simplex computed from a design of experiments This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced for example the Mac Kinnon test case The given matrix is expected to have n rows and k columns where n is the dimension of the problem and k is the number of vertices axes the simplex is computed from the coordinate axes and the length associated with the simplex0length option spendley the simplex is computed so that it is regular with the length associated with the simplex0length option ie all the edges have the same length pfeffer the simplex is computed from an heuristic in the neighborhood of the initial guess This initial simplex depends on the simplex0deltausual and simplex0deltazero randbounds the simplex is computed from the bounds and a random number This option is avai lable only if bounds are available if bounds are not available an error is generated This method is usually associated with Boxs algorithm The number of vertices in the simplex is taken from the boxnbpoints option coords0 the coordinates of the vertices of the initial simplex If the simplex0method option is set to given these coordinates are used to compute the initial simplex This matrix is expected to have shape nbve x n where nbve is the number of vertices and n is the number of variables simplex0length the length to use when the initial simplex is computed with the axes or spendley methods If the initial simplex is computed from spendley method the length is expec ted to be a scalar value If the initial simplex is computed from axes method it may be either a scalar value or a vector of values with rank n where n is the number of variables simplex0deltausual the relative delta for nonzero parameters in pfeffer method The default value is 005 simplex0deltazero the absolute delta for nonzero parameters in pfeffer method The default value is 00075 rho the reflection coefficient This parameter is used when the method option is set to fixed or variable The default value is 10 chi the expansion coefficient This parameter is used when the method option is set to va riable The default value is 20 gamma the contraction coefficient This parameter is used when the method option is set to variable The default value is 05 Neldermead 1457 sigma the shrinkage coefficient This parameter is used when the method option is set to fi xed or variable The default value is 05 tolsimplexizemethod set to f to disable the tolerance on the simplex size The default value is t If this criteria is triggered the status of the optimization is set to tolsize When this criteria is enabled the values of the options tolsimplexizeabsolute and tol simplexizerelative are used in the termination criteria The method to compute the size is the sigmaplus method tolsimplexizeabsolute the absolute tolerance on the simplex size The default value is 00 tolsimplexizerelative the relative tolerance on the simplex size The default value is eps tolssizedeltafvmethod set to t to enable the termination criteria based on the size of the simplex and the difference of function value in the simplex The default value is f If this criteria is triggered the status of the optimization is set to tolsizedeltafv This termination criteria uses the values of the options tolsimplexizeabsolute and tol deltafv This criteria is identical to Matlabs fminsearch toldeltafv the absolute tolerance on the difference between the highest and the lowest function values tolvarianceflag set to t to enable the termination criteria based on the variance of the function value If this criteria is triggered the status of the optimization is set to tolvariance This criteria is suggested by Nelder and Mead tolabsolutevariance the absolute tolerance on the variance of the function values of the simplex tolrelativevariance the relative tolerance on the variance of the function values of the simplex kelleystagnationflag set to t to enable the termination criteria using Kelleys stagnation detection based on sufficient decrease condition The default value is f If this criteria is triggered the status of the optimization is set to kelleystagnation kelleynormalizationflag set to f to disable the normalization of the alpha coefficient in Kelleys stagnation detection ie use the value of the option kelleystagnationalpha0 as is Default value is t ie the simplex gradient of the initial simplex is taken into account in the stagnation detection kelleystagnationalpha0 the parameter used in Kelleys stagnation detection The default value is 1e4 restartflag set to t to enable the automatic restart of the algorithm Default value is f restartdetection the method to detect if the automatic restart must be performed The following methods are available Neldermead 1458 oneill the factorial local optimality test by ONeill is used If the test finds a local point which is better than the computed optimum a restart is performed kelley the sufficient decrease condition by ONeill is used If the test finds that the status of the optimization is kelleystagnation a restart is performed This status may be generated if the kelleystagnationflag option is set to t The default method is oneill restartmax the maximum number of restarts when automatic restart is enabled via the restartflag option Default value is 3 restarteps the absolute epsilon value used to check for optimality in the factorial ONeill restart detection The default value is eps restartstep the absolute step length used to check for optimality in the factorial ONeill restart de tection The default value is 10 restartsimplexmethod the method to compute the initial simplex after a restart The following methods are available given the coordinates associated with the coords0 option are used to compute the initial simplex with arbitrary number of vertices This allow the user to setup the initial simplex by a specific method which is not provided by the current component for example with a simplex computed from a design of experiments This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced for example the Mc Kinnon test case The given matrix is expected to have n rows and k columns where n is the dimension of the problem and k is the number of vertices axes the simplex is computed from the coordinate axes and the length associated with the simplex0length option spendley the simplex is computed so that it is regular with the length associated with the simplex0length option ie all the edges have the same length pfeffer the simplex is computed from an heuristic in the neighborhood of the initial guess This initial simplex depends on the simplex0deltausual and simplex0deltazero randbounds the simplex is computed from the bounds and a random number This option is avai lable only if bounds are available if bounds are not available an error is generated This method is usually associated with Boxs algorithm The number of vertices in the simplex is taken from the boxnbpoints option oriented the simplex is computed so that it is oriented as suggested by CT Kelley The default method is oriented Neldermead 1459 scalingsimplex0 the algorithm used to scale the initial simplex into the nonlinear constraints The follo wing two algorithms are provided tox0 scales the vertices toward the initial guess tocentroid scales the vertices toward the centroid as recommended by Box If the centroid happens to be unfeasible because the constraints are not convex the scaling of the initial simplex toward the centroid may fail Since the initial guess is always feasible scaling toward the initial guess cannot fail The default value is tox0 boxnbpoints the number of points in the initial simplex when the simplex0method is set to rand bounds The value of this option is also use to update the simplex when a restart is performed and the restartsimplexmethod option is set to randbounds The default value is so that the number of points is twice the number of variables of the problem boxineqscaling the scaling coefficient used to scale the trial point for function improvement or into the constraints of Boxs algorithm Default value is 05 guinalphamin the minimum value of alpha when scaling the vertices of the simplex into nonlinear constraints in Boxs algorithm Default value is 1e5 boxreflect the reflection factor in Boxs algorithm Default value is 13 boxtermination set to t to enable Box termination criteria Default value is f boxtolf the absolute tolerance on difference of function values in the simplex suggested by Box This tolerance is used if the boxtermination option is set to t Default value is 1e5 boxnbmatch the number of consecutive match of Box termination criteria Default value is 5 boxboundsalpha the parameter used to project the vertices into the bounds in Boxs algorithm Default value is 0000001 mymethod a userderined simplex algorithm See below for details default is empty myterminate a userdefined terminate function See below for details default is empty myterminateflag set to t to enable the userdefined terminate function default is f value the value value neldermeadcget thiskey Get the value for the given key If the key is unknown generates an error this The current object Neldermead 1460 key the name of the key to quiery The list of available keys is the same as for the neldermeadconfigure function value neldermeadget this key Get the value for the given key If the key is unknown generates an error this The current object key the key to get The following keys are available funevals the number of function evaluations iterations the number of iterations xopt the x optimum as a n x 1 column vector where n is the number of variables fopt the optimum cost function value historyxopt an array with nbiter values containing the history of x during the iterations This array is available after optimization if the history storing was enabled with the storehistory option historyfopt an array with nbiter values containing the history of the function value during the ite rations This array is available after optimization if the history storing was enabled with the storehistory option fx0 the function value for the initial guess status a string containing the status of the optimization See below for details about the opti mization status historysimplex a matrix containing the history of the simplex during the iterations This matrix has rank nbiter x nbve x n where nbiter is the number of iterations nbve is the number of vertices in the simplex and n is the number of variables simplex0 the initial simplex This is a simplex object which is suitable for processing with the optimsimplex component simplexopt the optimum simplex This is a simplex object which is suitable for processing with the optimsimplex component restartnb the number of actual restarts performed Neldermead 1461 Most fields are available only after an optimization has been performed with one call to the neldermeadsearch method neldermeaddisplay this Display the current settings in the console this The current object this neldermeadsearch this Performs the optimization associated with the method associated with the method option and find the optimum this The current object If the restartflag option is enabled automatic restarts are performed based on the restartdetection option this neldermeadrestart this Restarts the optimization by updating the simplex and performing a new search this The current object this result neldermeadfunction this x Call the cost function and return the value this The current object x the point where the function is to be evaluated index optionnal a flag to pass to the cost function default 1 See the section The cost function for available values of index The cost function The option function allows to configure the cost function The cost function is used to compute the objective function value f If the nbineqconst option is configured to a nonzero value the cost function must also compute the value of the nonlinear positive inequality constraints c The cost function can also take as inputoutput an additional argument if the costfargument option is configured Depending of these options the cost function can have one of the following headers Without additionnal data f index costf x index f c index costf x index With costfargument f index data costf x index data f c index data costf x index data where x the current point as a column vector index optional an integer representing the value to compute Neldermead 1462 f the value of the cost function c the value of the nonlinear positive inequality constraints data an userprovided inputoutput argument The index input parameter tells to the cost function what is expected in the output arguments It has the following meaning index 2 compute f index 5 compute c index 6 compute f and c In the most simplex case there is no additionnal cost function argument and no nonlinear constraints In this case the cost function is expected to have the following header function f index myfunction x index The data argument is both input and output and the following paragraph explains for what reason and how it works This feature may be used in the situation where the cost function has to update its environment from call to call Its simplest use is to count the number of calls to the cost function but this feature is already available directly Consider the more practical situation where the optimization requires the execution of an underlying Newton method a chemical solver for example This Newton method requires an initial guess x0 If the initial guess for this underlying Newton method is kept constant the Newton method may have problems to converge when the current optimization point get far away from the its initial point If the costfargument option is provided the initial guess for the Newton method can be updated so that it gets the value of the previous call This way the Newton method will have less problems to converge and the cost function evaluation may be faster We now present how the feature works Everytime the cost function is called back the costfar gument option is passed to the cost function as an input argument If the cost function modifies its content in the output argument the content of the costfargument option is updated accordingly Once the optimization is performed the user may call the neldermeadcget function and get back an updated costfargument content The output function The option outputcommand allows to configure a command which is called back at the start of the optimization at each iteration and at the end of the optimization The output function must have the following header function outputcmdstate data myobj where state a string representing the current state of the algorithm Available values are init iter done Neldermead 1463 data a tlist containing at least the following entries x the current optimum fval the current function value iteration the current iteration index funccount the number of function evaluations simplex the current simplex step the previous step in the algorithm The following values are available init done re flection expansion insidecontraction outsidecontraction reflectionnext shrink myobj a userdefined parameter This input parameter is defined with the outputcommandarg option The output function may be used when debugging the specialized optimization algorithm so that a verbose logging is produced It may also be used to write one or several report files in a specialized format ASCII LaTeX Excel Hdf5 etc The userdefined parameter may be used in that case to store file names or logging options The data tlist argument may contain more fields than the current presented ones These additionnal fields may contain values which are specific to the specialized algorithm such as the simplex in a NelderMead method the gradient of the cost function in a BFGS method etc Termination The current component takes into account for several generic termination criterias The following termination criterias are enabled by default maxiter maxfunevals tolxmethod tolsimplexizemethod The optimizationterminate function uses a set of rules to compute if the termination occurs which leads to an optimization status which is equal to one of the following continue maxiter max funevals tolf tolx tolsize tolsizedeltafv kelleystagnation tolboxf tolvariance The value of the status may also be a userdefined string in the case where a userdefined termination function has been set The following set of rules is examined in this order By default the status is continue and the terminate flag is f The number of iterations is examined and compared to the maxiter option if the following condition Neldermead 1464 iterations maxiter is true then the status is set to maxiter and terminate is set to t The number of function evaluations and compared to the maxfunevals option is examined if the following condition funevals maxfunevals is true then the status is set to maxfuneval and terminate is set to t The tolerance on function value is examined depending on the value of the tolfunmethod f then the criteria is just ignored t if the following condition abscurrentfopt tolfunrelative abspreviousfopt tolfunabsolute is true then the status is set to tolf and terminate is set to t The relative termination criteria on the function value works well if the function value at optimum is near zero In that case the function value at initial guess fx0 may be used as previousfopt This criteria is sensitive to the tolfunrelative and tolfunabsolute options The absolute termination criteria on the function value works if the user has an accurate idea of the optimum function value The tolerance on x is examined depending on the value of the tolxmethod f then the criteria is just ignored t if the following condition normcurrentxopt previousxopt tolxrelative normcurrentxopt tolxabsolute is true then the status is set to tolx and terminate is set to t This criteria is sensitive to the tolxrelative and tolxabsolute options The relative termination criteria on x works well if x at optimum is different from zero In that case the condition measures the distance between two iterates The absolute termination criteria on x works if the user has an accurate idea of the scale of the optimum x If the optimum x is near 0 the relative tolerance will not work and the absolute tolerance is more appropriate The tolerance on simplex size is examined depending on the value of the tolsimplexize method option Neldermead 1465 f then the criteria is just ignored t if the following condition ssize tolsimplexizerelative simplexsize0 tolsimplexizeabsolute is true where simplexsize0 is the size of the simplex at iteration 0 then the status is set to tolsize and terminate is set to t The size of the simplex is computed from the sigmaplus method of the optimsimplex component This criteria is sensitive to the tolsimplexizeabsolute and the tol simplexizerelative options The absolute tolerance on simplex size and absolute difference of function value is examined de pending on the value of the tolssizedeltafvmethod option f then the criteria is just ignored t if both the following conditions ssize tolsimplexizeabsolute shiftfv toldeltafv is true where ssize is the current simplex size and shiftfv is the absolute value of the difference of function value between the highest and lowest vertices then the status is set to tolsizedeltafv and terminate is set to t The stagnation condition based on Kelley sufficient decrease condition is examined depending on the value of the kelleystagnationflag option f then the criteria is just ignored t if the following condition newfvmean oldfvmean alpha sg sg is true where newfvmean resp oldfvmean is the function value average in the current iteration resp in the previous iteration then the status is set to kelleystagnation and termi nate is set to t Here alpha is a nondimensional coefficient and sg is the simplex gradient The termination condition suggested by Box is examined depending on the value of the boxtermi nation option f then the criteria is just ignored Neldermead 1466 t if both the following conditions shiftfv boxtolf boxkount boxnbmatch is true where shiftfv is the difference of function value between the best and worst vertices and boxkount is the number of consecutive iterations where this criteria is met then the status is set to tolboxf and terminate is set to t Here the boxtolf parameter is the value associated with the boxtolf option and is a userdefined absolute tolerance on the function value The boxnbmatch parameter is the value associated with the boxnbmatch option and is the userdefined number of consecutive match The termination condition based on the variance of the function values in the simplex is examined depending on the value of the tolvarianceflag option f then the criteria is just ignored t if the following condition var tolrelativevariance variancesimplex0 tolabsolutevariance is true where var is the variance of the function values in the simplex then the status is set to tolvariance and terminate is set to t Here the tolrelativevariance parameter is the value associated with the tolrelativevariance option and is a userdefined relative tolerance on the variance of the function values The tolabsolutevariance parameter is the value associated with the tolabsolutevariance option and is the userdefined absolute tolerance of the variance of the function values The userdefined termination condition is examined depending on the value of the mytermina teflag option f then the criteria is just ignored t if the term output argument boolean returned by the termination function is true then the status is set to the userdefined status and terminate is set to t Kelleys stagnation detection The stagnation detection criteria suggested by Kelley is based on a sufficient decrease condition which requires a parameter alpha 0 to be defined The kelleynormalizationflag option allows to configure the method to use to compute this alpha parameter two methods are available where each method corresponds to a different paper by Kelley constant In Detection and Remediation of Stagnation in the NelderMead Algorithm Using a Sufficient Decrease Condition Kelley uses a constant alpha with the suggested value 1e4 which is is typical choice for line search method Neldermead 1467 normalized in Iterative Methods for Optimization Kelley uses a normalized alpha computed from the fol lowing formula alpha alpha0 sigma0 nsg where sigma0 is the size of the initial simplex and nsg is the norm of the simplex gradient for the initial guess point ONeil factorial optimality test In Algorithm AS47 Function minimization using a simplex procedure R ONeil presents a fortran 77 implementation of the simplex method A factorial test is used to check if the computed optimum point is a local minimum If the restartdetection option is set to oneill that factorial test is used to see if a restart should be performed Spendley et al implementation notes The original paper may be implemented with several variations which might lead to different results This section defines what algorithmic choices have been used The paper states the following rules Rule 1 Ascertain the lowest reading y of yi yk1 Complete a new simplex Sp by excluding the point Vp corresponding to y and replacing it by V defined as above Rule 2 If a result has occurred in k 1 successive simplexes and is not then eliminated by application of Rule 1 do not move in the direction indicated by Rule 1 or at all but discard the result and replace it by a new observation at the same point Rule 3 If y is the lowest reading in So and if the next observation made y is the lowest reading in the new simplex S do not apply Rule 1 and return to So from Sp Move out of S by rejecting the second lowest reading which is also the second lowest reading in So We implement the following rules of the Spendley et al method Rule 1 is strictly applied but the reflection is done by reflection the high point since we minimize a function instead of maximizing it like Spendley Rule 2 is NOT implemented as we expect that the function evaluation is not subject to errors Rule 3 is applied ie reflection with respect to next to high point The original paper does not mention any shrink step When the original algorithm cannot improve the function value with reflection steps the basic algorithm stops In order to make the current imple mentation of practical value a shrink step is included with shrinkage factor sigma This perfectly fits into to the spirit of the original paper Notice that the shrink step make the rule 3 reflection with respect to nexttoworst vertex unnecessary Indeed the minimum required steps are the reflection and shrinkage Never the less the rule 3 has been kept in order to make the algorithm as close as it can be to the original NelderMead implementation notes The purpose of this section is to analyse the current implementation of NelderMeads algorithm Neldermead 1468 The algorithm that we use is described in Iterative Methods for Optimization by C T Kelley The original paper uses a greedy expansion in which the expansion point is accepted whatever its function value The current implementation as most implementations uses the expansion point only if it improves over the reflection point that is if fefr then the expansion point is accepted if not the reflection point is accepted The termination criteria suggested by Nelder and Mead is based on an absolute tolerance on the stan dard deviation of the function values in the simplex We provide this original termination criteria with the tolvarianceflag option which is disabled by default Boxs complex algorithm implementation notes In this section we analyse the current implementation of Boxs complex method The initial simplex can be computed as in Boxs paper but this may not be safe In his paper Box suggest that if a vertex of the initial simplex does not satisfy the non linear constraints then it should be moved halfway toward the centroid of those points already selected This behaviour is available when the scalingsimplex0 option is set to tocenter It may happen as suggested by Guin that the centroid is not feasible This may happen if the constraints are not convex In this case the initial simplex cannot be computed This is why we provide the tox0 option which allows to compute the initial simplex by scaling toward the initial guess which is always feasible In Boxs paper the scaling into the non linear constraints is performed toward the centroid that is by using a scaling factor equal to 05 This default scaling factor might be suboptimal in certain situations This is why we provide the boxineqscaling option which allows to configure the scaling factor In Boxs paper whether we are concerned with the initial simplex or with the simplex at a given iteration the scaling for the non linear constraints is performed without end This is because Boxs hypothesis is that ultimately a satisfactory point will be found As suggested by Guin if the process fails the algorithm goes into an infinite loop In order to avoid this we perform the scaling until a minimum scaling value is reached as defined by the guinalphamin option We have taken into account for the comments by Guin but it should be emphasized that the current implementation is still as close as possible to Boxs algorithm and is not Guins algorithm More pre cisely during the iterations the scaling for the non linear constraints is still performed toward the centroid be it feasible or not Userdefined algorithm The mymethod option allows to configure a userdefined simplexbased algorithm The reason for this option is that many simplexbased variants of NelderMeads algorithm have been developped over the years with specific goals While it is not possible to provide them all it is very convenient to use the current structure without being forced to make many developments The value of the mymethod option is expected to be a Scilab function with the following header function this myalgorithm this endfunction where this is the current object Neldermead 1469 In order to use the userdefined algorithm the method option must be set to mine In this case the component performs the optimization exactly as if the userdefined algorithm was provided by the component The user interested in that feature may use the internal scripts provided in the distribution as templates and tune his own algorithm from that point There is of course no warranty that the userdefined algorithm improves on the standard algorithm so that users use this feature at their own risks Userdefined termination Many termination criteria are found in the bibliography Users which aim at reproducing the results exhibited in a particular paper may find that that none of the provided termination criteria match the one which is used in the paper It may also happen that the provided termination criteria are not suitable for the specific test case In those situation the myterminate option allows to configure a user defined termination function The value of the myterminate option is expected to be a Scilab function with the following header function this terminate status mystoppingrule this simplex endfunction where this is the current object and simplex is the current simplex The terminate output argument is a boolean which is false if the algorithm must continue and true if the algorithm must stop The status output argument is a string which is associated with the current termination criteria In order to enable the use of the userdefined termination function the value of the mytermina teflag must be set to true At each iteration if the myterminateflag option has been set to true the userdefined termination is called If the terminate output argument is true then the algorithm is stopped In that case the value of the status option of the neldermeadget is the value of the status output argument of the userdefined termination function Example 1 basic use In the following example we solve a simple quadratic test case We begin by defining the cost function which takes 2 input arguments and returns the objective The classical starting point 12 10 is used The neldermeadnew creates a new neldermead object Then we use the neldermeadconfigure method to configure the parameters of the problem We use all default settings and perform the search for the optimum The neldermeaddisplay function is used to display the state of the optimization and the neldermeadget is used to retrieve the optimum parameters function f index quadratic x index f x12 x22 endfunction x0 10 10 nm neldermeadnew nm neldermeadconfigurenmnumberofvariables2 nm neldermeadconfigurenmfunctionquadratic nm neldermeadconfigurenmx0x0 nm neldermeadsearchnm neldermeaddisplaynm xopt neldermeadgetnmxopt nm neldermeaddestroynm Neldermead 1470 Example 2 customized use In the following example we solve the Rosenbrock test case We begin by defining the Rosenbrock function which takes 2 input arguments and returns the objective The classical starting point 12 10 is used The neldermeadnew creates a new neldermead object Then we use the neldermeadconfigure method to configure the parameters of the problem The initial simplex is computed from the axes and the single length 10 this is the default but is explicitely written here as an example The va riable simplex algorithm by Nelder and Mead is used which corresponds to the method variable option The neldermeadsearch function performs the search for the minimum Once the minimum is found the neldermeadcontour allows to compute the data required by the contour function This is possible since our problem involves only 2 parameters This function uses the cost function previ ously configured to compute the required data The contour plot is directly drawn from the data pro vided by neldermeadcontour Then we plot the initial guess on the contour plot as a blue dot The neldermeadget function is used to get the optimum which is associated with the xopt option The optimum is plot on the contour plot as a red dot mprintfDefining Rosenbrock function function f index rosenbrock x index y 100x2x1221x12 endfunction x0 12 10 mprintfx0s strcatstringx0 mprintfCreating object nm neldermeadnew mprintfConfiguring object nm neldermeadconfigurenmnumberofvariables2 nm neldermeadconfigurenmfunctionrosenbrock nm neldermeadconfigurenmx0x0 nm neldermeadconfigurenmmaxiter200 nm neldermeadconfigurenmmaxfunevals300 nm neldermeadconfigurenmtolfunrelative10eps nm neldermeadconfigurenmtolxrelative10eps nm neldermeadconfigurenmsimplex0methodaxes nm neldermeadconfigurenmsimplex0length10 nm neldermeadconfigurenmmethodvariable nm neldermeadconfigurenmverbose0 nm neldermeadconfigurenmverbosetermination0 mprintfSearching for minimum nm neldermeadsearchnm mprintfPlot contour xmin 20 xmax 20 ymin 20 ymax 20 nx 100 ny 100 stepx xmax xminnx xdata xminstepxxmax stepy ymax yminny ydata yminstepyymax for ix 1lengthxdata for iy 1lengthydata experiment xdataix ydataiy nm fiexp neldermeadfunction nm experiment zdata ix iy fiexp end end wnum 100001 myhandle scfwnum contour xdata ydata zdata 1 10 100 500 1000 2000 Plot starting point Neldermead 1471 mprintfx0 blue dot plotx01x02 myhandlechildrenchildren1childrenmarkmodeon myhandlechildrenchildren1childrenmarksize 5 myhandlechildrenchildren1childrenmarkforeground 2 mprintfxopt red dot xopt neldermeadgetnmxopt plotxopt1xopt2 myhandlechildrenchildren1childrenmarkmodeon myhandlechildrenchildren1childrenmarksize 5 myhandlechildrenchildren1childrenmarkforeground 5 nm neldermeaddestroynm The verbose option allows to get detailed informations about the current optimization process The following is a sample output for an optimization based on the Nelder and Mead variableshape simplex algorithm Only the output corresponding to the iteration 156 is displayed In order to display specific outputs or to create specific output files and graphics the outputcommand option should be used Iteration 156 total 156 Function Eval 297 Xopt 1 1 Fopt 6871176e027 DeltaFv 2880999e026 Center 1 1 Size 2548515e013 Vertex 13 fv0000000 x1000000 1000000 Vertex 23 fv0000000 x1000000 1000000 Vertex 33 fv0000000 x1000000 1000000 nmplotoutputcmd 1 Reflect xbar1 1 Function Evaluation 298 is 1155D25 at 1 1 xr1 1 fxr0000000 Contract inside Function Evaluation 299 is 6023D27 at 1 1 xc1 1 fxc0000000 Perform Inside Contraction Sort Example 3 use output function In the following example we show how to use the output command to create specialized outputs These outputs may be used to create specific data files or make interactive graphic outputs We define the function myoutputcmd which takes the current state as its first argument The state is a string which can contain init iter or done depending on the status of the optimization The data input argument is a tlist which contains the data associated with the current iteration In this case we use the fields to print a message in the console As another example of use we could format the message so that it uses LaTeX formatting rules which may allow the user to directly copy and paste the output into a LaTeX report Neldermead 1472 function f index rosenbrock x index f 100x2x122 1x12 endfunction myoutputcmd This command is called back by the NelderMead algorithm Arguments state the current state of the algorithm init iter done data the data at the current state This is a tlist with the following entries x the optimal vector of parameters fval the minimum function value simplex the simplex as a simplex object iteration the number of iterations performed funccount the number of function evaluations step the type of step in the previous iteration function myoutputcmd state data iter dataiteration if state init then mprintf mprintf Initialization elseif state done then mprintf mprintf End of Optimization end fc datafunccount fval datafval x datax simplex datasimplex Simplex is a data structure which can be managed by the optimsimplex class ssize optimsimplexsize simplex mprintf Iteration d Feval d Fval e x s Size e iter fc fval strcatstringx ssize endfunction nm neldermeadnew nm neldermeadconfigurenmnumberofvariables2 nm neldermeadconfigurenmfunctionrosenbrock nm neldermeadconfigurenmx012 10 nm neldermeadconfigurenmmaxiter200 nm neldermeadconfigurenmmaxfunevals300 nm neldermeadconfigurenmtolfunrelative10eps nm neldermeadconfigurenmtolxrelative10eps nm neldermeadconfigurenmsimplex0methodaxes nm neldermeadconfigurenmsimplex0length10 nm neldermeadconfigurenmmethodvariable nm neldermeadconfigurenmverbose0 nm neldermeadconfigurenmverbosetermination0 nm neldermeadconfigurenmoutputcommandmyoutputcmd nm neldermeadsearchnm nm neldermeaddestroynm Neldermead 1473 The previous script produces the following output Initialization Iteration 0 Feval 4 Fval 2420000e001 x 12 1 Size 1000000e000 Iteration 1 Feval 4 Fval 2420000e001 x 12 1 Size 1000000e000 Iteration 2 Feval 6 Fval 2420000e001 x 12 1 Size 1000000e000 Iteration 3 Feval 8 Fval 2420000e001 x 12 1 Size 1000000e000 Iteration 4 Feval 10 Fval 9999182e000 x 10125 078125 Size 5970304e001 Iteration 155 Feval 296 Fval 2024754e026 x 1 1 Size 4601219e013 Iteration 156 Feval 298 Fval 6871176e027 x 1 1 Size 2548515e013 Iteration 157 Feval 300 Fval 6023002e027 x 1 1 Size 2814328e013 End of Optimization Iteration 157 Feval 300 Fval 6023002e027 x 1 1 Size 2814328e013 Bibliography Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation Spendley W and Hext G R and Himsworth F R American Statistical Association and American Society for Quality 1962 A Simplex Method for Function Minimization Nelder J A and Mead R The Computer Journal 1965 A New Method of Constrained Optimization and a Comparison With Other Methods M J Box The Computer Journal 1965 814252 1965 by British Computer Society Discussion and correspondence modification of the complex method of constrained optimization J A Guin The Computer Journal 1968 Detection and Remediation of Stagnation in the NelderMead Algorithm Using a Sufficient Decrease Condition Kelley C T SIAM J on Optimization 1999 Iterative Methods for Optimization C T Kelley SIAM Frontiers in Applied Mathematics 1999 Algorithm AS47 Function minimization using a simplex procedure ONeill R Applied Statistics 1971 Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 See Also optimbase optimsimplex nmplot Neldermead 1474 Nom overview An overview of the NelderMead toolbox Purpose The goal of this toolbox is to provide a NelderMead direct search optimization method That Nel derMead algorithm may be used in the following optimization context there is no need to provide the derivatives of the objective function the number of parameters is small up to 1020 there are bounds andor non linear constraints Design This package provides the following components neldermead provides various NelderMead variants and manages for NelderMead specific set tings such as the method to compute the initial simplex the specific termination criteria fminsearch provides a simplified NelderMead algorithm Specific terminations criteria initial simplex and auxiliary settings are automatically configured optimset optimget provide Scilab commands to emulate their Matlab counterparts optimplotfunccount optimplotx and optimplotfval provide plotting features for the fminsearch function nmplot provides a highlevel component which provides directly output pictures for NelderMead algorithm The current component is based on the following components optimbase provides an abstract class for a general optimization component including the number of variables the minimum and maximum bounds the number of non linear inequality constraints the loggin system various termination criteria the cost function etc optimsimplex provides a class to manage a simplex made of an arbitrary number of vertices including the computation of a simplex by various methods axes regular Pfeffers randomized bounds the computation of the size by various methods diameter sigma sigma etc Features The following is a list of features the NelderMead prototype algorithm currently provides Provides 3 algorithms including Spendley et al fixed shaped algorithm NelderMead variable shape algorithm Box complex algorithm managing bounds and nonlinear inequality constraints based on arbi trary number of vertices in the simplex Manage various simplex initializations initial simplex given by user initial simplex computed with a length and along the coordinate axes Neldermead 1475 initial regular simplex computed with Spendley et al formula initial simplex computed by a small perturbation around the initial guess point Manage cost function optionnal additionnal argument direct communication of the task to perform cost function or inequality constraints Manage various termination criteria including maximum number of iterations tolerance on func tion value relative or absolute tolerance on x relative or absolute tolerance on standard deviation of function value original termination criteria in 3 maximum number of evaluations of cost function absolute or relative simplex size Manage the history of the convergence including history of function values history of optimum point history of simplices history of termination criterias Provide a plot command which allows to graphically see the history of the simplices toward the optimum Provide query features for the status of the optimization process number of iterations number of function evaluations status of execution function value at initial point function value at optimal point etc Kelley restart based on simplex gradient ONeill restart based on factorial search around optimum Example Optimizing the Rosenbrock function In the following example one searches the minimum of the 2D Rosenbrock function One begins by defining the function rosenbrock which computes the Rosenbrock function The traditionnal initial guess 12 10 is used The initial simplex is computed along the axes with a length equal to 01 The NelderMead algorithm with variable simplex size is used The verbose mode is enabled so that messages are generated during the algorithm After the optimization is performed the optimum is retrieved with quiery features function y rosenbrock x y 100x2x122 1x12 endfunction nm neldermeadnew nm neldermeadconfigurenmx012 10 nm neldermeadconfigurenmsimplex0methodaxes nm neldermeadconfigurenmsimplex0length01 Neldermead 1476 nm neldermeadconfigurenmmethodvariable nm neldermeadconfigurenmverbose1 nm neldermeadconfigurenmfunctionrosenbrock nm neldermeadsearchnm xopt neldermeadgetnmxopt fopt neldermeadgetnmfopt historyfopt neldermeadgetnmhistoryfopt iterations neldermeadgetnmiterations historyxopt neldermeadgetnmhistoryxopt historysimplex neldermeadgetnmhistorysimplex fx0 neldermeadgetnmfx0 status neldermeadgetnmstatus nm neldermeaddestroynm Authors Michael Baudin 20082009 Bibliography Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation Spendley W and Hext G R and Himsworth F R American Statistical Association and American Society for Quality 1962 A Simplex Method for Function Minimization Nelder J A and Mead R The Computer Journal 1965 A New Method of Constrained Optimization and a Comparison With Other Methods M J Box The Computer Journal 1965 814252 1965 by British Computer Society Convergence Properties of the NelderMead Simplex Method in Low Dimensions Jeffrey C La garias and James A Reeds and Margaret H Wright and Paul E Wright SIAM Journal on Optimiza tion 1998 Compact numerical methods for computers linear algebra and function minimisation Nash J C Hilger Bristol 1979 Iterative Methods for Optimization C T Kelley 1999 Iterative Methods for Optimization Matlab Codes httpwww4ncsueductkmatlabdartshtml Sequential Simplex Optimization A Technique for Improving Quality and Productivity in Research Development and Manufacturing Walters Fred H and Jr Lloyd R and Morgan Stephen L and Deming Stanley N 1991 Numerical Recipes in C Second Edition W H Press and Saul A Teukolsky and William T Vet terling and Brian P Flannery 1992 Detection and Remediation of Stagnation in the NelderMead Algorithm Using a Sufficient Decrease Condition SIAM J on Optimization Kelley C T 1999 Matlab fminsearch httpwwwmathworkscomaccesshelpdeskhelptechdocindexhtmlac cesshelpdeskhelptechdocreffminsearchhtml GAMS A19A20 description httpgamsnistgovservecgiModuleNASHLIBA19A2011238 asa047f httppeoplescfsueduburkardtf77srcasa047asa047f optim1f httpwwwstatuconnedumhchensurvbookexample51optim1f Neldermead 1477 as47f httplibstatcmueduapstat47 Algorithm AS47 Function minimization using a simplex procedure ONeill R 1971 Applied Statistics TODO include MultiDirectionnal Search algorithm in the release include parabolic interpolation in the release provide a neldermeadoutputfunction to make nice and easy outputs provide a stopping feature to the cost function and manage the stop output argument to the output functions of fminsearch provide a quadratic penalized version of neldermead for bound constrained problems Neldermead 1478 Nom nmplot Provides several direct search optimization algorithms based on the simplex method newobj nmplotnew this nmplotdestroy this this nmplotconfigure thiskeyvalue value nmplotcget thiskey this nmplotdisplay this value nmplotget this key this nmplotsearch this this nmplotrestart this this xdata ydata zdata nmplotcontour this xmin xmax ymin ymax nx ny this nmplothistoryplot this datafile mytitle myxlabel myylabel this nmplotsimplexhistory this colorforeground markforeground markstyle Description This class provides several direct search optimization algorithms based on the simplex method The goal of this class is to provide a neldermead component with plotting features It enables to make fast plots of the algorithm progress through the iterations It is a specialized neldermead class with a specific output command This output function allows to store the history of several datas through the iterations of the algorithm These datas are the history of the coordinates of the simplex the history of the function value averaged on the vertices the history of the minimum function value in the simplex the history of the size of the simplex as computed with the sigma method These data are stored into several data files during the optimization process Several methods allows to plot the data stored into these data files Design The nmplot component is built on top of the neldermead component The outputcommand option of the neldermead class is not available since the nmplot class uses its own output function Additionnal options simplexfn fbarfn foptfn and sigmafn are provided which allows to configure the file names where the data is stored The nmplot class can be considered as a sample test case of the outputcommand option of the nel dermead class It gives an example of the situation where the user wants to get specialized outputs out of the neldermead class Functions The following functions are available newobj nmplotnew Creates a new nmplot object newobj The new object this nmplotdestroy this Destroy the given object Neldermead 1479 this The current object this nmplotconfigure thiskeyvalue Configure the current object with the given value for the given key this The current object key the key to configure The following keys are available verbose set to 1 to enable verbose logging default is 0 verbosetermination set to 1 to enable verbose termination logging default is 0 x0 the initial guess as a n x 1 column vector where n is the number of variables maxfunevals the maximum number of function evalutations default is 100 If this criteria is triggered the status of the optimization is set to maxfuneval maxiter the maximum number of iterations default is 100 If this criteria is triggered the status of the optimization is set to maxiter tolfunabsolute the absolute tolerance for the function value default is 00 tolfunrelative the relative tolerance for the function value default is eps tolfunmethod the method used for the tolerance on function value in the termination criteria The following values are available absoluterelative relative absolute disa bled default is disabled If this criteria is triggered the status of the optimization is set to tolf tolxabsolute the absolute tolerance on x default is 00 tolxrelative the relative tolerance on x default is eps tolxmethod the method used for the tolerance on x in the termination criteria The following values are available relative absolute disabled default is relati ve If this criteria is triggered the status of the optimization is set to tolx function the objective function which computes the value of the cost and the non linear constra ints if any See below for the details of the communication between the optimization system and the cost function costfargument an additionnal argument passed to the cost function Neldermead 1480 outputcommand a command which is called back for output See below for the details of the communication between the optimization system and the output command function outputcommandarg an additionnal argument passed to the output command numberofvariables the number of variables to optimize default is 0 storehistory set to 1 to enable the history storing default is 0 boundsmin the minimum bounds for the parameters as an array of values default is empty ie there are no bounds boundsmax the maximum bounds for the parameters as an array of values default is empty ie there are no bounds nbineqconst the number of inequality constraints default is 0 method the name of the algorithm to use The following methods are available fixed the Spendley et al fixed simplex shape algorithm This algorithm is for unconstrai ned problems ie bounds and non linear constraints are not taken into account variable the NelderMead variable simplex shape algorithm This algorithm is for uncons trained problems ie bounds and non linear constraints are not taken into account box the Box complex algorithm This algorithm takes into account bounds and nonlinear inequality constraints simplex0method the method to use to compute the initial simplex The first vertex in the simplex is always the initial guess associated with the x0 option The following methods are available given the coordinates associated with the coords0 option are used to compute the initial simplex with arbitrary number of vertices This allow the user to setup the initial simplex by a specific method which is not provided by the current component for example with a simplex computed from a design of experiments This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced for example the Mac Kinnon test case The given matrix is expected to have n rows and k columns where n is the dimension of the problem and k is the number of vertices axes the simplex is computed from the coordinate axes and the length associated with the simplex0length option Neldermead 1481 spendley the simplex is computed so that it is regular with the length associated with the simplex0length option ie all the edges have the same length pfeffer the simplex is computed from an heuristic in the neighborhood of the initial guess This initial simplex depends on the simplex0deltausual and simplex0deltazero randbounds the simplex is computed from the bounds and a random number This option is avai lable only if bounds are available if bounds are not available an error is generated This method is usually associated with Boxs algorithm The number of vertices in the simplex is taken from the boxnbpoints option coords0 the coordinates of the vertices of the initial simplex If the simplex0method option is set to given these coordinates are used to compute the initial simplex This matrix is expected to have shape nbve x n where nbve is the number of vertices and n is the number of variables simplex0length the length to use when the initial simplex is computed with the axes or spendley methods If the initial simplex is computed from spendley method the length is expec ted to be a scalar value If the initial simplex is computed from axes method it may be either a scalar value or a vector of values with rank n where n is the number of variables simplex0deltausual the relative delta for nonzero parameters in pfeffer method The default value is 005 simplex0deltazero the absolute delta for nonzero parameters in pfeffer method The default value is 00075 rho the reflection coefficient This parameter is used when the method option is set to fixed or variable The default value is 10 chi the expansion coefficient This parameter is used when the method option is set to va riable The default value is 20 gamma the contraction coefficient This parameter is used when the method option is set to variable The default value is 05 sigma the shrinkage coefficient This parameter is used when the method option is set to fi xed or variable The default value is 05 tolfstdeviationmethod set to enabled to enable the termination criteria based on the standard deviation of the function values in the simplex The default value is disabled If this criteria is triggered the status of the optimization is set to tolfstdev This criteria is suggested by Nelder and Mead tolfstdeviation the absolute tolerance on standard deviation The default value is 00 tolsimplexizemethod set to disabled to disable the tolerance on the simplex size The default value is ena bled If this criteria is triggered the status of the optimization is set to tolsize Neldermead 1482 When this criteria is enabled the values of the options tolsimplexizeabsolute and tol simplexizerelative are used in the termination criteria The method to compute the size is the sigmaplus method tolsimplexizeabsolute the absolute tolerance on the simplex size The default value is 00 tolsimplexizerelative the relative tolerance on the simplex size The default value is eps tolssizedeltafvmethod set to enabled to enable the termination criteria based on the size of the simplex and the difference of function value in the simplex The default value is disabled If this criteria is triggered the status of the optimization is set to tolsizedeltafv This termination criteria uses the values of the options tolsimplexizeabsolute and tol deltafv This criteria is identical to Matlabs fminsearch toldeltafv the absolute tolerance on the difference between the highest and the lowest function values kelleystagnationflag set to 1 to enable the termination criteria using Kelleys stagnation detection based on sufficient decrease condition The default value is 0 If this criteria is triggered the status of the optimization is set to kelleystagnation kelleynormalizationflag set to 0 to disable the normalization of the alpha coefficient in Kelleys stagnation de tection ie use the value of the option kelleystagnationalpha0 as is Default value is 1 ie the simplex gradient of the initial simplex is taken into account in the stagnation detection kelleystagnationalpha0 the parameter used in Kelleys stagnation detection The default value is 1e4 restartflag set to 1 to enable the automatic restart of the algorithm Default value is 0 restartdetection the method to detect if the automatic restart must be performed The following methods are available oneill the factorial local optimality test by ONeill is used If the test finds a local point which is better than the computed optimum a restart is performed kelley the sufficient decrease condition by ONeill is used If the test finds that the status of the optimization is kelleystagnation a restart is performed This status may be generated if the kelleystagnationflag option is set to 1 The default method is oneill restartmax the maximum number of restarts when automatic restart is enabled via the restartflag option Default value is 3 restarteps the absolute epsilon value used to check for optimality in the factorial ONeill restart detection The default value is eps Neldermead 1483 restartstep the absolute step length used to check for optimality in the factorial ONeill restart de tection The default value is 10 restartsimplexmethod the method to compute the initial simplex after a restart The following methods are available given the coordinates associated with the coords0 option are used to compute the initial simplex with arbitrary number of vertices This allow the user to setup the initial simplex by a specific method which is not provided by the current component for example with a simplex computed from a design of experiments This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced for example the Mac Kinnon test case The given matrix is expected to have n rows and k columns where n is the dimension of the problem and k is the number of vertices axes the simplex is computed from the coordinate axes and the length associated with the simplex0length option spendley the simplex is computed so that it is regular with the length associated with the simplex0length option ie all the edges have the same length pfeffer the simplex is computed from an heuristic in the neighborhood of the initial guess This initial simplex depends on the simplex0deltausual and simplex0deltazero randbounds the simplex is computed from the bounds and a random number This option is avai lable only if bounds are available if bounds are not available an error is generated This method is usually associated with Boxs algorithm The number of vertices in the simplex is taken from the boxnbpoints option oriented the simplex is computed so that it is oriented as suggested by CT Kelley The default method is oriented boxnbpoints the number of points in the initial simplex when the restartsimplexmethod option is set to randbounds The default value is so that the number of points is twice the number of variables of the problem nbineqloops the number of loops to perform in Box and BoxGuin algorithms to scale the trial point for function improvement or into the constraints Default value is 10 ineqscaling the scaling coefficient used to scale the trial point for function improvement or into the constraints Default value is 05 simplexfn the name of the file containing the history of the simplex Default value is the empty string Neldermead 1484 fbarfn the name of the file containing the history of the function value averaged on the vertices of the simplex Default value is the empty string foptfn the name of the file containing the history of the minimum function value in the simplex Default value is the empty string sigmafn the name of the file containing the history of the size of the simplex Default value is the empty string value the value value nmplotcget thiskey Get the value for the given key If the key is unknown generates an error this The current object key the name of the key to quiery The list of available keys is the same as for the nmplotconfigure function value nmplotget this key Get the value for the given key If the key is unknown generates an error this The current object key the key to get The following keys are available funevals the number of function evaluations iterations the number of iterations xopt the x optimum as a n x 1 column vector where n is the number of variables fopt the optimum cost function value historyxopt an array with nbiter values containing the history of x during the iterations This array is available after optimization if the history storing was enabled with the storehistory option historyfopt an array with nbiter values containing the history of the function value during the ite rations This array is available after optimization if the history storing was enabled with the storehistory option fx0 the function value for the initial guess Neldermead 1485 status a string containing the status of the optimization See below for details about the opti mization status historysimplex a matrix containing the history of the simplex during the iterations This matrix has rank nbiter x nbve x n where nbiter is the number of iterations nbve is the number of vertices in the simplex and n is the number of variables simplexopt the optimum simplex This is a simplex object which is suitable for processing with the simplex interface restartnb the number of actual restarts performed Most fields are available only after an optimization has been performed with one call to the neldermeadsearch method this nmplotdisplay this Display the current settings in the console this The current object this nmplotsearch this Performs the optimization associated with the method associated with the method option and find the optimum this The current object If the restartflag option is enabled automatic restarts are performed based on the restartdetection option this nmplotrestart this Restarts the optimization by updating the simplex and performing a new search this The current object this xdata ydata zdata nmplotcontour this xmin xmax ymin ymax nx ny Plot the contours of the cost function The cost function must be a function with two parameters this The current object xmin xmax ymin ymax the bounds for the contour plot nx ny the number of points in the directions x y xdata ydata zdata vectors of data as required by the contour function nmplotsimplexhistory this colorforeground markforeground markstyle Plots the simplex history on the current graphic window The colorforeground markforeground markstyle options are provided to produce fast plots Specific settings can still be applied with the usual graphic features this The current object Neldermead 1486 colorforeground the color of the foreground for the simplices Default value is 5 markforeground the foreground mark for the simplices Default value is 3 markstyle the mark style for the simplices Default value is 9 nmplothistoryplot this datafile mytitle myxlabel myylabel Plots the history from the given data file on the current graphic window The mytitle myxlabel myylabel options are provided as a way to produce plots faster Specific settings can still be applied with the usual graphic features this The current object datafile the data file which contains the history The file is expected to be formatted in a way similar to the files associated with the fbarfn foptfn and sigmafn files The default value is the value of the foptfn option mytitle the title of the plot Default value is the empty string myxlabel the x label for the plot Default value is the empty string myylabel the y label for the plot Default value is the empty string this result nmplotfunction this x index Call the cost function and return the value this The current object x the point where the function is to be evaluated index optionnal a flag to pass to the cost function default 1 See the section The cost function of the neldermead component for available values of index Example In the following example we use the fixed shape Spendley et al simplex algorithm and find the mini mum of a quadratic function We begin by defining a quadratic function associated with 2 input varia bles We then define an nmplot object and configure the object so that the fixed shape simplex algo rithm is used with the regular initial simplex associated with the spendley key Four files are confi gured which will contain the history of the simplex the history of fbar fopt and sigma through the ite rations The search is performed by the nmplotsearch function which writes the 4 data files during the iterations The nmplotcontour function is called in order to compute the arrays xdata ydata and zdata which are required as input to the contour function The nmplotsimplexhistory then uses the history of the simplex as stored in the rosenbrockfixedhistorysimplextxt data file and plot the various simpli ces on the contour plot The nmplothistoryplot is used with the files rosenbrockfixedhistoryfbartxt rosenbrockfixedhistoryfopttxt and rosenbrockfixedhistorysigmatxt which produces 3 plots of the history of the optimization algorithm through the iterations Neldermead 1487 mprintfDefining quadratic function function y quadratic x y x12 x22 x1 x2 endfunction mprintfCreating nmplot object nm nmplotnew nm nmplotconfigurenmnumberofvariables2 nm nmplotconfigurenmfunctionquadratic nm nmplotconfigurenmx020 20 nm nmplotconfigurenmmaxiter100 nm nmplotconfigurenmmaxfunevals300 nm nmplotconfigurenmtolxrelative1e8 nm nmplotconfigurenmsimplex0methodspendley nm nmplotconfigurenmmethodfixed Setup output files nm nmplotconfigurenmsimplexfnrosenbrockfixedhistorysimplextxt nm nmplotconfigurenmfbarfnrosenbrockfixedhistoryfbartxt nm nmplotconfigurenmfoptfnrosenbrockfixedhistoryfopttxt nm nmplotconfigurenmsigmafnrosenbrockfixedhistorysigmatxt Perform optimization mprintfSearching for minimum nm nmplotsearchnm nmplotdisplaynm Plot the contours of the cost function and the simplex history mprintfPlotting contour nm xdata ydata zdata nmplotcontour nm xmin 20 xmax 40 ymin 20 ymax 40 nx 100 ny 100 f scf contour xdata ydata zdata 01 10 20 50 100 150 200 nmplotsimplexhistory nm mprintfPlotting history of fbar f scf nmplothistoryplot nm rosenbrockfixedhistoryfbartxt mytitle Function Value Average myxlabel Iterations mprintfPlotting history of fopt f scf nmplothistoryplot nm rosenbrockfixedhistoryfopttxt mytitle Minimum Function Value myxlabel Iterations mprintfPlotting history of sigma f scf nmplothistoryplot nm rosenbrockfixedhistorysigmatxt mytitle Maximum Oriented length myxlabel Iterations deletefilerosenbrockfixedhistorysimplextxt deletefilerosenbrockfixedhistoryfbartxt deletefilerosenbrockfixedhistoryfopttxt deletefilerosenbrockfixedhistorysigmatxt nm nmplotdestroynm TODO add an example Neldermead 1488 Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 See Also neldermead Neldermead 1489 Nom optimget Queries an optimization data structure val optimget options key val optimget options key value Description This function allows to make queries on an existing optimization data structure This data structure must have been created and updated by the optimset function The optimget allows to retrieve the value associated with a given key In the following we analyse the various ways to call the optimget function The following calling sequence val optimgetoptions key returns the value associated with the given key The key is expected to be a string We search the key among the list of all possible fields in the options data structure In this search the case is ignored The key which matches a possible field is returned Some letters of the field may be dropped provided that the matching field is unique For example the key MaxF corresponds to the field MaxFunEval But the key Tol corresponds both to the TolX and TolFun fields and therefore will generate an error The following calling sequence val optimgetoptions key value allows to manage default value for optimization parameters Indeed if the field corresponding to the key is empty ie has not been set by the user the input argument value is returned Instead if the field corresponding the the key is not empty ie has been set by the user the parameter stored in the options argument is returned Parameters options A struct which contains the optimization fields key A string corresponding to a field of the optimization structure value A real default value val The real value corresponding to the key Example 1 In the following example we create an optimization structure and set the TolX field to 1e12 Then we use optimget to get back the value Neldermead 1490 op optimset op optimsetopTolX1e12 val optimgetopTolX val is 1e12 Example 2 In the following example we create an empty optimization structure Then we use optimget to get back the value corresponding to the TolX field with 1e5 as the default value Since the field is empty we retrieve 1e5 op optimset val optimgetopTolX 1e5 val 1e5 Example 3 In the following example we create an optimization structure and set the TolX field to 1e12 Then we use optimget to get back the value corresponding to the TolX field with 1e5 as the default value Since the field is not empty we retrieve 1e12 op optimset op optimsetopTolX1e12 val optimgetopTolX 1e5 val 1e12 Example 4 In the following example we create an optimization structure and configure the maximum number of function evaluations to 1000 Then we quiery the data structure giving only the MaxF key to the optimget function Since that corresponds only to the MaxFunEvals field there is only one match and the function returns 10000 op optimset op optimsetop MaxFunEvals 1000 val optimgetop MaxF val 1000 Authors Michael Baudin Digiteo 2009 See Also optimset Neldermead 1491 Nom optimplotfunccount Plot the number of function evaluations of an optimization algorithm optimplotfunccount x optimValues state Description This function creates and updates a plot of the number of function evaluations depending on the num ber of iterations It is a predefined plot function which should be used as an option of the PlotFcns option Example In the following example we use the optimplotfunccount function for use with the fminse arch function function y rosenbrock x y 100x2x122 1x12 endfunction opt optimset PlotFcns optimplotfunccount x fval fminsearch rosenbrock 12 1 opt Authors Michael Baudin Digiteo 2009 See Also optimset fminsearch optimplotx optimplotfval Neldermead 1492 Nom optimplotfval Plot the function value of an optimization algorithm optimplotfval x optimValues state Description This function creates and updates a plot of the function value depending on the number of iterations It is a predefined plot function which should be used as an option of the PlotFcns option Example In the following example we use the optimplotfval function for use with the fminsearch function function y rosenbrock x y 100x2x122 1x12 endfunction opt optimset PlotFcns optimplotfval x fval fminsearch rosenbrock 12 1 opt Authors Michael Baudin Digiteo 2009 See Also optimset fminsearch optimplotx optimplotfunccount Neldermead 1493 Nom optimplotx Plot the value of the parameters of an optimization algorithm optimplotx x optimValues state Description This function creates and updates a plot of the value of the parameters depending on the number of iterations It is a predefined plot function which should be used as an option of the PlotFcns option Example In the following example we use the optimplotx function for use with the fminsearch function function y rosenbrock x y 100x2x122 1x12 endfunction opt optimset PlotFcns optimplotx x fval fminsearch rosenbrock 12 1 opt Authors Michael Baudin Digiteo 2009 See Also optimset fminsearch optimplotfval optimplotfunccount Neldermead 1494 Nom optimset Configures and returns an optimization data structure options optimset options optimset funname options optimset key value options optimset key1 value1 key2 value2 options optimset oldoptions key value Description This function creates or updates a data structure which can be used on modify the behaviour of opti mization methods The goal of this function is to manage the options data structure which is a struct with a set of fields for example MaxFunEvals MaxIter etc The user can create a new struc ture with empty fields or create a new structure with default fields which correspond to a particular algorithm The user can also configure each field and set it to a particular value Finally the user pass the structure to an optimization function so that the algorithm uses the options configured by the user In the following we analyse the various ways to call the optimset function The following calling sequence options optimset creates a new data structure where the fields have been set to the empty matrix ie The following calling sequence options optimset funname creates a new data structure where the default parameters which correspond to the funname function have been set For example options optimset fminsearch returns a new data structure where the default parameters which correspond to the fminsearch func tion have been set The following calling sequence options optimset oldoptions key value creates a new data structure where all fields from the oldoptions structure have been copied except the field corresponding to the key which has been set to value Parameters key a string The following keys are available Neldermead 1495 Display FunValCheck MaxFunEvals MaxIter OutputFcn PlotFcns value the value of the parameter options A struct which contains the following fields By default all fields are empty Specific settings are associated with a particular function name optionsDisplay The verbose level The default value is notify The following is a list of available verbose levels optionsDisplay off the algorithm displays no message at all optionsDisplay notify the algorithm displays message if the termination criteria is not reached at the end of the optimization This may happen if the maximum number of iterations of the maximum number of function evaluations is reached and warns the user of a convergence problem optionsDisplay final the algorithm displays a message at the end of the optimization showing the number of iterations the number of function evaluations and the status of the optimization This option includes the messages generated by the notify option ie warns in case of a convergence problem optionsDisplay iter the algorithm displays a oneline message at each iteration This option includes the messages generated by the notify option ie warns in case of a con vergence problem It also includes the message generated by the final option optionsFunValCheck A boolean to enable the checking of function values optionsMaxFunEvals The maximum number of evaluations of the cost function optionsMaxIter The maximum number of iterations optionsOutputFcn A function which is called at each iteration to print out intermediate state of the optimization algorithm for example into a log file optionsPlotFcns A function which is called at each iteration to plot the intermediate state of the optimization algorithm for example into a 2D graphic optionsTolFun The absolute tolerance on function value optionsTolX The absolute tolerance on the variable x Neldermead 1496 funname A string containing the name of an optimization function which takes the options structure as input argument Currently the only possible value is fminsearch Design Most optimization algorithms require many algorithmic parameters such as the number of iterations or the number of function evaluations If these parameters are given to the optimization function as input parameters this forces both the user and the developper to manage many input parameters For example the optim function provides more than 20 input arguments The goal of the optimset function is to simplify the management of input arguments by gathering all the parameters into a single data structure While the current implementation of the optimset function only supports the fminsearch function it is designed to be extended to as many optimization function as required Because all optimization algorithms do not require the same parameters the data structure aims at remaining flexible But most of the time most parameters are the same from algorithm to algorithm for example the tolerance parameters which drive the termination criteria are often the same even if the termination criteria itself is not the same Output and plot functions The OutputFcn and PlotFcns options accept as argument a function or a list of functions In the client optimization algorithm this output or plot function is called back once per iteration It can be used by the user to display a message in the console write into a file etc The output or plot function is expected to have the following definition function myfun x optimValues state where the input parameters are x the current point optimValues a struct which contains the following fields optimValuesfunccount the number of function evaluations optimValuesfval the best function value optimValuesiteration the current iteration number optimValuesprocedure the type of step performed This string depends on the specific algorithm see fminsearch for details state the state of the algorithm The following states are available init iter and done init when the algorithm is initializing iter when the algorithm is performing iterations done when the algorithm is terminated Example 1 In the following example we create an empty optimization structure Neldermead 1497 op optimset Example 2 In the following example we create an optimization structure with all fields set to specific settings op optimset Displayiter FunValCheckon MaxFunEvals100 MaxIter110 OutputFcnmyoutputfun PlotFcnsmyplotfun TolFun1e12 TolX1e13 Example 3 In the following example we create an optimization structure with all fields set to the default settings for the fminsearch optimization function op optimset fminsearch Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 See Also optimget Capítulo 3 Optimization base Optimization base 1499 Nom optimbase Provides an abstract class for a general optimization component newobj optimbasenew this optimbasedestroy this this optimbaseconfigure thiskeyvalue value optimbasecget thiskey value optimbaseget thiskey this optimbaseset this key value this isok optimbasecheckbounds this opt isok optimbasecheckx0 this this optimbasedisplay this this f index data optimbasefunction this x index data this f c index data optimbasefunction this x index data this f g index data optimbasefunction this x index data this f g c gc index data optimbasefunction this x index data this hasbounds optimbasehasbounds this this hascons optimbasehasconstraints this this hasnlcons optimbasehasnlcons this value optimbasehistget this iter key this optimbasehistset this iter key value this optimbaseincriter this this isfeasible optimbaseisfeasible this x this optimbaselog thismsg optimbaseoutputcmd this state data data optimbaseoutstruct this this p optimbaseproj2bnds this x this optimbasestoplog this msg this terminate status optimbaseterminate this previousfopt currentfopt previousxopt currentxopt this optimbasecheckcostfun this this isfeasible optimbaseisinbounds this x this isfeasible optimbaseisinnonlinconst this x Purpose The goal of this component is to provide a building block for optimization methods The goal is to pro vide a building block for a large class of specialized optimization methods This component manages the number of variables the minimum and maximum bounds the number of non linear inequality constraints the cost function the logging system various termination criteria etc Design This toolbox is designed with Oriented Object ideas in mind Optimization base 1500 Features The following is a list of features the Optimbase toolbox currently provides Manage cost function optionnal additionnal argument direct communication of the task to perform cost function or inequality constraints Manage various termination criteria including maximum number of iterations tolerance on function value relative or absolute tolerance on x relative or absolute maximum number of evaluations of cost function Manage the history of the convergence including history of function values history of optimum point Provide query features for the status of the optimization process the number of iterations the number of function evaluations function value at initial point function value at optimal point the optimum parameters etc Description This set of commands allows to manage an abstract optimization method The goal is to provide a building block for a large class of specialized optimization methods This component manages the number of variables the minimum and maximum bounds the number of non linear inequality cons traints the logging system various termination criteria the cost function etc The optimization problem to solve is the following min fx li xi hi i 1n gix 0 i 1nbineq where n number of variables Optimization base 1501 nbineq number of inequality constraints Functions The following functions are available newobj optimbasenew Creates a new optimization object newobj The new object this optimbasedestroy this Destroy the given object this The current object this optimbaseconfigure thiskeyvalue Configure the current object with the given value for the given key this The current object key the key to configure The following keys are available verbose set to 1 to enable verbose logging default is 0 verbosetermination set to 1 to enable verbose termination logging default is 0 x0 the initial guess maxfunevals the maximum number of function evalutations default is 100 If this criteria is triggered the status of the optimization is set to maxfuneval maxiter the maximum number of iterations default is 100 If this criteria is triggered the status of the optimization is set to maxiter tolfunabsolute the absolute tolerance for the function value default is 00 tolfunrelative the relative tolerance for the function value default is eps tolfunmethod the method used for the tolerance on function value in the termination criteria The following values are available t f default is f If this criteria is triggered the status of the optimization is set to tolf tolxabsolute the absolute tolerance on x default is 00 tolxrelative the relative tolerance on x default is eps Optimization base 1502 tolxmethod the method used for the tolerance on x in the termination criteria The following values are available t f default is t If this criteria is triggered the status of the optimization is set to tolx function the objective function which computes the value of the cost and the non linear constra ints if any See below for the details of the communication between the optimization system and the cost function costfargument an additionnal argument passed to the cost function outputcommand a command which is called back for output See below for the details of the communication between the optimization system and the output command function outputcommandarg an additionnal argument passed to the output command numberofvariables the number of variables to optimize default is 0 storehistory set to t to enable the history storing default is f boundsmin the minimum bounds for the parameters as an array of values default is empty ie there are no bounds boundsmax the maximum bounds for the parameters as an array of values default is empty ie there are no bounds nbineqconst the number of inequality constraints default is 0 logfile the name of the log file withderivatives set to t if the algorithm uses derivatives Default is f value the value value optimbasecget thiskey Get the value for the given key If the key is unknown generates an error this The current object key the name of the key to quiery The list of available keys is the same as for the optimbaseconfigure function Optimization base 1503 this isok optimbasecheckbounds this Check if the bounds are consistent and puts an error message if not One could generate an error but errors are not testable with the current system this The current object opt isok optimbasecheckx0 this Returns T if the initial guess is consistent with the bounds and the non linear inequality cons traints if any this The current object this optimbasedisplay this Display the current settings in the console this The current object this f index data optimbasefunction this x index data this f c index data optimbasefunction this x index data this f g index data optimbasefunction this x index data this f g c gc index data optimbasefunction this x index data Call the cost function and return the required results If a cost function additionnal argument is defined in current object pass it to the function as the last argument See below for details this The current object x the current point as a column vector index what value to compute See below in the section Cost function for details on this index f the value of the cost function g the gradient of the cost function c the nonlinear positive inequality constraints gc the gradient of the nonlinear positive inequality constraints data an optionnal userprovided argument this optimbaseset this key value Set the value for the given key If the key is unknown generates an error this The current object Optimization base 1504 key the key to set The following keys are available funevals the number of function evaluations iterations the number of iterations xopt the x optimum fopt the optimum cost function value historyxopt an array with nbiter values containing the history of x during the iterations This array is available after optimization if the history storing was enabled with the storehistory option historyfopt an array with nbiter values containing the history of the function value during the ite rations This array is available after optimization if the history storing was enabled with the storehistory option fx0 the function value for the initial guess status a string containing the status of the optimization value the value to set value optimbaseget thiskey Get the value for the given key If the key is unknown generates an error This command corres ponds with options which are not available directly to the optimbaseconfigure function but are computed internally this The current object key the name of the key to quiery The list of available keys is the same as the optimbaseset function this hasbounds optimbasehasbounds this Returns T if current problem has bounds this The current object this hascons optimbasehasconstraints this Returns T if current problem has bounds constraints linear constraints or non linear constraints this The current object Optimization base 1505 this hasnlcons optimbasehasnlcons this Returns T if current problem has non linear constraints this The current object this optimbasehistset this iter key value Set the history value at given iteration for the given key If the key is unknown generates an error this The current object iter the iteration number to get key the name of the key to quiery The list of available keys is the following xopt fopt value the value to set value optimbasehistget this iter key Returns the history value at the given iteration number for the given key If the key is unknown generates an error this The current object iter the iteration number to get key the name of the key to quiery The list of available keys is the same as the optimbasehistset function this optimbaseincriter this Increments the number of iterations this The current object this isfeasible optimbaseisfeasible this x Returns 1 if the given point satisfies bounds constraints and inequality constraints Returns 0 if the given point is not in the bounds Returns 1 if the given point does not satisfies inequality constraints this The current object x the current point this optimbaselog thismsg If verbose logging is enabled prints the given message in the console If verbose logging is di sabled does nothing If the lofgile option has been set writes the message into the file instead of writing to the console If the console is too slow writing into a file can be a solution since it is very fast Optimization base 1506 this The current object msg the message to print optimbaseoutputcmd this state data Calls back users output command this The current object data optimbaseoutstruct this Returns a tlist with basic optimization fields This tlist is suitable for use as an input argument of the output function This tlist may be enriched by children specialize optimization methods this The current object this p optimbaseproj2bnds this x Returns a point which is the projection of the given point into the bounds this The current object x the current point this optimbasestoplog this msg Prints the given stopping rule message if verbose termination is enabled If verbose termination is disabled does nothing this The current object msg the message to print this terminate status optimbaseterminate this previousfopt currentfopt previousxopt currentxopt Returns 1 if the algorithm terminates Returns 0 if the algorithm must continue If the verbose termination option is enabled messages are printed detailing the termination intermediate steps The optimbaseterminate function takes into account the number of iterations the number of eva luations of the cost function the tolerance on x and the tolerance on f See below in the section Termination for more details this The current object previousfopt the previous value of the cost function currentfopt the current value of the cost function previousxopt the previous x optimum currentxopt the current x optimum Optimization base 1507 terminate t if the algorithm must terminate f if the algorithm must continue status if terminate t the detailed status of the termination as a string If terminate f the status is continue The following status are available maxiter the maximum number of iterations provided by the maxiter option is reached maxfuneval the maximum number of function evaluations provided by the maxfunevals option is reached tolf the tolerance on the function value is reached This status is associated with the tolfun method tolfunabsolute and tolfunrelative options tolx the tolerance on x is reached This status is associated with the tolxmethod tolxabsolute and tolxrelative options this optimbasecheckcostfun this Check that the cost function is correctly connected Generate an error if there is one Takes into account for the cost function at the initial guess x0 only Checks that all values of the index argument are valid If there are nonlinear constraints check that the matrix has the correct shape This function requires at least one call to the cost function to make the necessary checks this The current object this isfeasible optimbaseisinbounds this x Returns isfeasible t if the given point satisfies bounds constraints Returns isfeasible f if the given point is not in the bounds this The current object isfeasible a boolean this isfeasible optimbaseisinnonlinconst this x Returns isfeasible t if the given point satisfies the nonlinear constraints Returns isfeasible f if the given point does not satisfy the nonlinear constraints this The current object isfeasible a boolean The cost function The function option allows to configure the cost function The cost function is used depending on the context to compute the cost the nonlinear inequality positive constraints the gradient of the function and the gradient of the nonlinear inequality constraints The cost function can also be used to produce outputs and to terminate an optimization algorithm Optimization base 1508 In the following the variables are f scalar the objective g row matrix the gradient of the objective c row matrix the constraints gc matrix the gradient of the constraints Each calling sequence of the optimbasefunction function corresponds to a specific calling sequence of the userprovided cost function If the withderivatives is false and there is no nonlinear constraint the calling sequence is this f index optimbasefunction this x index which corresponds to the cost functions function f index costf x index function f index data costf x index data if there is a costfargument If the withderivatives is false and there are nonlinear constraints the calling sequence is this f c index optimbasefunction this x index which corresponds to the cost functions function f c index costf x index function f c index data costf x index data if there is a costfargument If the withderivatives is true and there is no nonlinear constraint the calling sequence is this f g index optimbasefunction this x index which corresponds to the cost functions function f g index costf x index function f g index data costf x index data if there is a costfargument If the withderivatives is true and there is are nonlinear constraints the calling sequence is this f g c gc index optimbasefunction this x index which corresponds to the cost functions function f g c gc index costf x index Optimization base 1509 function f g c gc index data costf x index data if there is a costfargument Each calling sequence corresponds to a particular class of algorithms including for example unconstrained derivativefree algorithms nonlinearily constrained derivativefree algorithms unconstrained derivativebased algorithms nonlinearilyconstrained derivativebased algorithms etc The current component is designed in order to be able to handle many situations The index input parameter has the following meaning index 1 nothing is to be computed the user may display messages for example index 2 compute f index 3 compute g index 4 compute f and g index 5 compute c index 6 compute f and c index 7 compute f g c and gc The index output parameter has the following meaning index 0 everything is fine index 0 the optimization must stop index 0 one function could not be avaluated The output function The option outputcommand allows to configure a command which is called back at the start of the optimization at each iteration and at the end of the optimization The output function must have the following header function outputcmdstate data myobj where state a string representing the current state of the algorithm Available values are init iter done data a tlist containing at least the following entries x the current optimum Optimization base 1510 fval the current function value iteration the current iteration index funccount the number of function evaluations myobj a userdefined parameter This input parameter is defined with the outputcommandarg option The output function may be used when debugging the specialized optimization algorithm so that a verbose logging is produced It may also be used to write one or several report files in a specialized format ASCII LaTeX Excel Hdf5 etc The userdefined parameter may be used in that case to store file names or logging options The data tlist argument may contain more fields than the current presented ones These additionnal fields may contain values which are specific to the specialized algorithm such as the simplex in a NelderMead method the gradient of the cost function in a BFGS method etc Termination The current component takes into account for several generic termination criterias Specialized ter mination criterias should be implemented in specialized optimization algorithms by calling the optimbasetermination function and adding external criterias rather than by modification of this func tion The optimbaseterminate function uses a set of rules to compute if the termination occurs which leads to an optimization status which is equal to one of the following continue maxiter maxfunevals tolf tolx The set of rules is the following By default the status is continue and the terminate flag is 0 The number of iterations is examined and compared to the maxiter option if the following con dition iterations maxiter is true then the status is set to maxiter and terminate is set to t The number of function evaluations and compared to the maxfunevals option is examined if the following condition funevals maxfunevals is true then the status is set to maxfuneval and terminate is set to t The tolerance on function value is examined depending on the value of the tolfunmethod disabled then the tolerance on f is just skipped enabled if the following condition Optimization base 1511 abscurrentfopt tolfunrelative abspreviousfopt tolfunabsolute is true then the status is set to tolf and terminate is set to t The relative termination criteria on the function value works well if the function value at optimum is near zero In that case the function value at initial guess fx0 may be used as previousfopt The absolute termination criteria on the function value works if the user has an accurate idea of the optimum function value The tolerance on x is examined depending on the value of the tolxmethod f then the tolerance on x is just skipped t if the following condition normcurrentxopt previousxopt tolxrelative normcurrentxopt tolxabsolute is true then the status is set to tolx and terminate is set to t The relative termination criteria on x works well if x at optimum is different from zero In that case the condition measures the distance between two iterates The absolute termination criteria on x works if the user has an accurate idea of the scale of the optimum x If the optimum x is near 0 the relative tolerance will not work and the absolute tolerance is more appropriate Example Setting up an optimization In the following example one searches the minimum of the 2D Rosenbrock function One begins by defining the function rosenbrock which computes the Rosenbrock function The traditionnal initial guess 12 10 is used The initial simplex is computed along the axes with a length equal to 01 The NelderMead algorithm with variable simplex size is used The verbose mode is enabled so that messages are generated during the algorithm After the optimization is performed the optimum is retrieved with quiery features function f index rosenbrock x index f 100x2x122 1x12 endfunction opt optimbasenew opt optimbaseconfigureoptnumberofvariables2 nbvar optimbasecgetoptnumberofvariables opt optimbaseconfigureoptfunctionrosenbrock this f index optimbasefunction opt 00 00 index opt optimbasedestroyopt Authors Michael Baudin 20082009 Optimization base 1512 TODO manage equality constraints manage linear constraints manage quadratic objective manage linear objective manage linear inequality constraints manage non linear equality constraints manage linear equality constraints rename outputcommand to outputfunction 1513 Capítulo 4 Optimization simplex Optimization simplex 1514 Nom optimsimplex Manage a simplex with arbitrary number of points newobj data optimsimplexnew coords fun data newobj data optimsimplexnew axes x0 fun len data newobj data optimsimplexnew spendley x0 fun len data newobj data optimsimplexnew pfeffer x0 fun deltausual deltazero data newobj data optimsimplexnew randbounds x0 fun boundsmin boundsmax nbve data newobj data optimsimplexnew oriented simplex0 fun data this optimsimplexdestroy this this optimsimplexsetall this simplex this optimsimplexsetallfv this fv this optimsimplexsetallx this x this optimsimplexsetfv this ive fv this optimsimplexsetn this n this optimsimplexsetnbve this nbve this optimsimplexsetve this ive fv x this optimsimplexsetx this ive x simplex optimsimplexgetall this fv optimsimplexgetallfv this x optimsimplexgetallx this fv optimsimplexgetfv this ive n optimsimplexgetn this nbve optimsimplexgetnbve this vertex optimsimplexgetve this ive x optimsimplexgetx this ive sicenter optimsimplexcenter this optimsimplexcheck this this data optimsimplexcomputefv this fun data df optimsimplexdeltafv this dfm optimsimplexdeltafvmax this m optimsimplexdirmat this m optimsimplexfvmean this sd optimsimplexfvstdev this v optimsimplexfvvariance this g data optimsimplexgradientfv this fun method data optimsimplexprint this r data optimsimplexreflect this fun data this data optimsimplexshrink this fun sigma data ssize optimsimplexsize this method this optimsimplexsort this str optimsimplextostring this cen optimsimplexxbar this iexcl Purpose The goal of this component is to provide a building block for optimization algorithms based on a simplex The optimsimplex package may be used in the following optimization methods the Spendley et al simplex method the NelderMead method the Box algorithm for constrained optimization the multidimensional search by Virginia Torczon etc Optimization simplex 1515 Design This toolbox is designed with Oriented Object ideas in mind Features The following is a list of features the NelderMead prototype algorithm currently provides Manage various simplex initializations initial simplex given by user initial simplex computed with a length and along the coordinate axes initial regular simplex computed with Spendley et al formula initial simplex computed by a small perturbation around the initial guess point initial simplex computed from randomized bounds sort the vertices by increasing function values compute the standard deviation of the function values in the simplex compute the simplex gradient with forward or centered differences shrink the simplex toward the best vertex etc Description This set of commands allows to manage a simplex made of kn1 points in a ndimensional space This component is the building block for a class of direct search optimization methods such as the NelderMead algorithm or Torczons MultiDimensionnal Search A simplex is designed as a collection of kn1 vertices Each vertex is made of a point and a function value at that point The simplex can be created with various shapes It can be configured and quieried at will The simplex can also be reflected or shrinked The simplex gradient can be computed with a order 1 forward formula and with a order 2 centered formula The optimsimplexnew function allows to create a simplex If vertices coordinates are gi ven there are registered in the simplex If a function is provided it is evaluated at each vertex The optimsimplexdestroy function destroys the object and frees internal me mory Several functions allow to create a simplex with special shapes including axesbyaxes optimsimplexaxes regular optimsimplexspendley randomized bounds simplex with arbitrary nbve vertices optimsimplexrandbounds and an heuristical small variation around a given point optimsimplexpfeffer In the following functions simplices and vertices are depending on the functions either input or output arguments The following general principle have been used to manage the storing of the coordinates of the points The vertices are stored row by row while the coordinates are stored column by column This implies the following rules The coordinates of a vertex are stored in a row vector ie a 1 x n matrix where n is the dimension of the space Optimization simplex 1516 The function values are stored in a column vector ie a nbve x 1 matrix where nbve is the number of vertices Functions The following functions are available newobj optimsimplexnew Creates a new simplex object All input arguments are optional If no input argument is provided returns an empty simplex object The following is a complete list of available calling sequences newobj optimsimplexnew coords newobj optimsimplexnew coords fun newobj data optimsimplexnew coords fun data newobj The new object coords optional matrix of point coordinates in the simplex The coords matrix is expected to be a nbve x n matrix where n is the dimension of the space and nbve is the number of vertices in the simplex with nbve n1 fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x where x is a row vector data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexnew axes x0 Creates a new simplex object so that it is computed axis by axis with the given length The following is a complete list of available calling sequences this optimsimplexnew axes x0 fun this optimsimplexnew axes x0 fun len Optimization simplex 1517 this data optimsimplexnew axes x0 fun len data this The current simplex object x0 the initial point as a row vector fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x len optional the length of the simplex The default length is 10 If length is a value that unique length is used in all directions If length is a vector with n values each length is used with the corresponding direction data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexnew pfeffer x0 Creates a new simplex so that it is computed from Pfeffers method ie a relative delta for non zero values and an absolute delta for zero values The following is a complete list of available calling sequences this optimsimplexnew pfeffer x0 fun this optimsimplexnew pfeffer x0 fun deltausual this optimsimplexnew pfeffer x0 fun deltausual deltazero this data optimsimplexnew pfeffer x0 fun deltausual deltazero data this The current simplex object x0 the initial point as a row vector fun optional the function to compute at vertices The function is expected to have the following input and output arguments Optimization simplex 1518 function y myfunction x deltausual optional the absolute delta for nonzero values The default value is 005 deltazero optional the absolute delta for zero values The default value is 00075 data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexnew randbounds x0 fun boundsmin boundsmax nbpoints Creates a new simplex so that it is computed by taking the bounds into account with random scaling The number of vertices in the simplex is arbitrary The following is a complete list of available calling sequences this data optimsimplexnew randbounds x0 fun boundsmin boundsmax nbpoints data this The current simplex object x0 the initial point as a row vector It is the first vertex in the simplex fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x boundsmin array of minimum bounds boundsmax array of maximum bounds Each component ix 1n of the vertex k 2nbve is computed from the formula x k ix boundsmin ix rand boundsmax ix boundsmin ix Optimization simplex 1519 nbpoints total number of points in the simplex data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexnew spendley x0 Creates a new simplex so that it is computed from Spendleys et al method ie a regular simplex made of nbve n1 vertices The following is a complete list of available calling sequences this optimsimplexnew spendley x0 fun this optimsimplexnew spendley x0 fun len this data optimsimplexnew spendley x0 fun len data this The current simplex object x0 the initial point as a row vector fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x len optional the length of the simplex The default length is 10 data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called Optimization simplex 1520 this optimsimplexnew oriented simplex0 fun Returns a new oriented simplex in sorted order The new simplex has the same sigma length of the base simplex but is oriented depending on the function value The created simplex may be used as Kelley suggests for a restart of NelderMead algorithm The following is a complete list of available calling sequences this data optimsimplexnew oriented simplex0 fun data this The current simplex object simplex0 the base simplex fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called this optimsimplexdestroy this Destroy the given object this The current simplex object this optimsimplexsetall this simplex Set all the coordinates and and the function values of all the vertices this The current simplex object simplex the simplex to set The given matrix is expected to be a nbve x n1 matrix where n is the dimension of the space nbve is the number of vertices and with the following content where the data is organized by row with function value first and x coordinates simplexk1 is the function value of the vertex k with k 1 nbve Optimization simplex 1521 simplexk2n1 is the coordinates of the vertex k with k 1 nbve this optimsimplexsetallfv this fv Set all the function values of all the vertices The vertex k is expected to be stored in fvk with k 1 nbve The fv input argument is expected to be a row vector this The current simplex object fv the array of function values this optimsimplexsetallx this x Set all the coordinates of all the vertices The vertex k is expected to be stored in xk1n with k 1 nbve this The current simplex object x the coordinates of the vertices this optimsimplexsetfv this ive fv Set the function value at given index and returns an updated simplex this The current simplex object ive vertex index fv the function value this optimsimplexsetn this n Set the dimension of the space of the simplex this The current simplex object n the dimension this optimsimplexsetnbve this nbve Set the number of vertices of the simplex this The current simplex object nbve the number of vertices this optimsimplexsetve this ive fv x Sets the coordinates of the vertex and the function value at given index in the current simplex this The current simplex object ive the vertex index fv the function value Optimization simplex 1522 x the coordinates of the point as a row vector this optimsimplexsetx this ive x Set the coordinates of the vertex at given index as a row vector into the current simplex this The current simplex object ive the vertex index x the coordinates of the point as a row vector simplex optimsimplexgetall this Returns all the coordinates of all the vertices and the function values in the same matrix this The current simplex object simplex the simplex data The simplex matrix has size nbve x n1 and is organized by row by row as follows simplexk1 is the function value of the vertex k with k 1 nbve simplexk2n1 is the coordinates of the vertex k with k 1 nbve fv optimsimplexgetallfv this Returns all the function values of all the vertices as a row vector this The current simplex object fv The array of function values The function value of vertex k is stored in fvk with k 1 nbve x optimsimplexgetallx this Returns all the coordinates of all the vertices this The current simplex object x the coordinates The vertex k is stored in xk1n with k 1 nbve fv optimsimplexgetfv this ive Returns the function value at given index this The current simplex object ive the vertex index n optimsimplexgetn this Returns the dimension of the space of the simplex Optimization simplex 1523 this The current simplex object nbve optimsimplexgetnbve this Returns the number of vertices in the simplex this The current simplex object vertex optimsimplexgetve this ive Returns the vertex at given index as a tlist with fields n x and fv this The current simplex object ive the vertex index x optimsimplexgetx this ive Returns the coordinates of the vertex at given index as a row vector this The current simplex object ive the vertex index sicenter optimsimplexcenter this Returns the center of the given simplex this The current simplex object optimsimplexcheck this Check the consistency of the internal data Generates an error if necessary this The current simplex object this data optimsimplexcomputefv this fun data Set the values of the function at vertices points this The current simplex object fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data Optimization simplex 1524 The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called df optimsimplexdeltafv this Returns the vector of difference of function values with respect to the function value at vertex 1 this The current simplex object dfm optimsimplexdeltafvmax this Returns the difference of function value between the high and the low vertices It is expected that the vertex 1 is associated with the smallest function value and that the vertex nbve is associated with the highest function value Since vertices are ordered the high is greater than the low this The current simplex object m optimsimplexdirmat this Returns the n x n matrix of simplex directions ie the matrix of differences of vertices coordinates with respect to the vertex 1 this The current simplex object m optimsimplexfvmean this Returns the mean of the function value on the simplex this The current simplex object sd optimsimplexfvstdev this Returns the standard deviation of the function value on the simplex this The current simplex object v optimsimplexfvvariance this Returns the variance of the function value on the simplex this The current simplex object g optimsimplexgradientfv this fun method Returns the simplex gradient of the function The following is a complete list of available calling sequences g optimsimplexgradientfv this fun method g data optimsimplexgradientfv this fun method data this The current simplex object fun optional the function to compute at vertices The function is expected to have the following input and output arguments Optimization simplex 1525 function y myfunction x method optional the method to use to compute the simplex gradient Two methods are available forward or centered The forward method uses the current simplex to compute the simplex gradient The centered method creates an intermediate reflected simplex and computes the average If not provided the default method is forward data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called optimsimplexprint this Display the current simplex with coordinates and function values this The current simplex object r data optimsimplexreflect this fun data Returns a new simplex by reflexion of current simplex by reflection with respect to the first vertex in the simplex This move is used in the centered simplex gradient this The current simplex object fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing Optimization simplex 1526 the function value This feature may be used for example to count the number of times that the function has been called this data optimsimplexshrink this fun sigma data Shrink the simplex with given coefficient sigma and returns an updated simplex The shrink is performed with respect to the first point in the simplex this The current simplex object fun optional the function to compute at vertices The function is expected to have the following input and output arguments function y myfunction x sigma optional the shrinkage coefficient The default value is 05 data optional userdefined data passed to the function If data is provided it is passed to the callback function both as an input and output argument In that case the function must have the following header function y data myfunction x data The data input parameter may be used if the function uses some additionnal parameters It is returned as an output parameter because the function may modify the data while computing the function value This feature may be used for example to count the number of times that the function has been called ssize optimsimplexsize this method Returns the size of the simplex this The current simplex object method optional the method to use to compute the size The available methods are the following sigmaplus this is the default The sigmamplus size is the maximum 2norm length of the vector from each vertex to the first vertex It requires one loop over the vertices sigmaminus The sigmaminus size is the minimum 2norm length of the vector from each vertex to the first vertex It requires one loop over the vertices Nash The Nash size is the sum of the norm of the norm1 length of the vector from the given vertex to the first vertex It requires one loop over the vertices Optimization simplex 1527 diameter The diameter is the maximum norm2 length of all the edges of the simplex It requires 2 nested loops over the vertices this optimsimplexsort this Sorts the simplex with increasing function value order so that the smallest function value is at vertex 1 this The current simplex object str optimsimplextostring this Returns the current simplex as a string this The current simplex object cen optimsimplexxbar this iexcl Returns the center of n vertices by excluding the vertex with index iexcl Returns a row vector this The current simplex object iexcl the index of the vertex to exclude in center computation The default value of iexcl is the number of vertices in that case if the simplex is sorted in increasing function value order the worst vertex is excluded Example Creating a simplex with given vertices coor dinates In the following example one creates a simplex with known vertices coordinates The function values at the vertices are unset coords 0 0 1 0 0 1 s1 optimsimplexnew coords computed optimsimplexgetallx s1 computed optimsimplexgetns1 computed optimsimplexgetnbve s1 s1 optimsimplexdestroys1 Example Creating a simplex with randomized bounds In the following example one creates a simplex with in the 2D domain 5 52 with 12 10 as the first vertex One uses the randomized bounds method to generate a simplex with 5 vertices The function takes an additionnal argument mystuff which is counts the number of times the function is called After the creation of the simplex the value of mystuffnb is 5 which is the expected result because there is one function call by vertex Optimization simplex 1528 function y rosenbrock x y 100x2x1221x12 endfunction function y mystuff mycostf x mystuff y rosenbrockx mystuffnb mystuffnb 1 endfunction mystuff tlistTMYSTUFFnb mystuffnb 0 s1 optimsimplexnew s1 mystuff optimsimplexrandbounds s1 x0 12 10 fun mycostf boundsmin 50 50 boundsmax 50 50 nbve5 data mystuff mprintfFunction evaluations d mystuffnb s1 optimsimplexdestroy s1 Initial simplex strategies In this section we analyse the various initial simplex which are provided in this component It is known that direct search methods based on simplex designs are very sensitive to the initial simplex This is why the current component provides various ways to create such an initial simplex The first historical simplexbased algorithm is the one presented in Sequential Application of Sim plex Designs in Optimisation and Evolutionary Operation by W Spendley G R Hext and F R Himsworth The spendley simplex creates the regular simplex which is presented in the paper The randbounds simplex is due to MJ Box in A New Method of Constrained Optimization and a Comparison With Other Methods Pfeffers method is an heuristic which is presented in Global Optimization Of LennardJones Atomic Clusters by Ellen Fan It is due to L Pfeffer at Stanford and it is used in fminsearch TODO implement reflection and expansion as in multidimensional search by Torczon turn optimsimplexreflect into a proper constructor ie an option of the the optimsimplexnew function Another possibility is to reflect in place as in the optimsimplexshrink function but in this case we must provide a copy constructor from current simplex before reflecting it Authors Michael Baudin INRIA 20082009 Michael Baudin Digiteo 2009 Bibliography Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation Spendley W and Hext G R and Himsworth F R American Statistical Association and American Society for Quality 1962 A Simplex Method for Function Minimization Nelder J A and Mead R The Computer Journal January 1965 308313 Optimization simplex 1529 A New Method of Constrained Optimization and a Comparison With Other Methods M J Box The Computer Journal 1965 814252 1965 by British Computer Society Iterative Methods for Optimization CT Kelley 1999 Chapter 6 section 62 Compact Numerical Methods For Computers Linear Algebra and Function Minimization JC Nash 1990 Chapter 14 Direct Search Methods Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation W Spend ley G R Hext F R Himsworth Technometrics Vol 4 No 4 Nov 1962 pp 441461 Section 31 A New Method of Constrained Optimization and a Comparison With Other Methods M J Box The Computer Journal 1965 814252 1965 by British Computer Society Detection and Remediation of Stagnation in the NelderMead Algorithm Using a Sufficient Decrease Condition SIAM J on Optimization Kelley C T 1999 MultiDirectional Search A Direct Search Algorithm for Parallel Machines by E Boyd Kenneth W Kennedy Richard A Tapia Virginia Joanne Torczon Virginia Joanne Torczon 1989 Phd Thesis Rice University Grid Restrained NelderMead Algorithm Árpád Brmen Janez Puhan Tadej Tuma Computational Optimization and Applications Volume 34 Issue 3 July 2006 Pages 359 375 A convergent variant of the NelderMead algorithm C J Price I D Coope D Byatt Journal of Optimization Theory and Applications Volume 113 Issue 1 April 2002 Pages 5 19 Global Optimization Of LennardJones Atomic Clusters Ellen Fan Thesis February 26 2002 Mc Master University 1530 Name NDcost generic external for optim computing gradient using finite differences fgindNDcostxindfunvarargin Parameters x real vector or matrix ind integer parameter see optim fun Scilab function with calling sequence Ffunxvarargin varargin may be use to pass pa rameters p1pn f criterion value at point x see optim g gradient value at point x see optim Description This function can be used as an external for optim to minimize problem where gradient is too com plicated to be programmed only the function fun which computes the criterion is required This function should be used as follow fxoptgoptoptimlistNDcostfunp1pnx0 Examples example 1 a simple one function to minimize function frosenbrockxvarargin pvarargin1 f1sum px2x1122 1x22 endfunction x01234 fxoptgoptoptimlistNDcostrosenbrock200x0 example 2 This example by Rainer von Seggern shows a quick way to identify the parameters of a linear differential equation with the help of scilab The model is a simple damped linear oscillator xt c xt k xt 0 and we write it as a system of two differential equations of first order with y1 x and y2 x dy1dt y2 dy2dt cy2 ky1 We suppose to have m measurements of x that is y1 at different times NDcost 1531 tobs1 tobsm called xobs1 xobsm in this example these measuresments will be simulated and we want to identify the parameters c and k by minimizing the sum of squared errors between xobs and y1tobsp This method is not the most efficient but it is easy to implement function dy DEQtyp The rhs of our first order differential equation system c p1kp2 dyy2cy2ky1 endfunction function yuNp t t0 y0 Numerical solution obtained with ode In this linear case an exact analytic solution can easily be found but ode would also work for any system Note the ode output must be an approximation of the solution at times given in the vector tt1t y odey0t0tlistDEQp endfunction function r costfuncp tobs xobs t0 y0 This is the function to be minimized that is the sum of the squared errors between what gives the model and the measuments sol uNp tobs t0 y0 e sol1 xobs r sumee endfunction Data y0 100 t0 0 Initial conditions y0 for initial time t0 T 30 Final time for the measurements Here we simulate experimental data from which the parameters should be identified pe 023 Exact parameters m 80 tobs linspacet02Tm Observation times Noise each measurement is supposed to have a gaussian random error of mean 0 and std deviation proportional to the magnitude of the value sigmaxexacttobsi sigma 01 yexact uNpe tobs t0 y0 xobs yexact1 grand1mnor0 sigmaabsyexact1 Initial guess parameters p0 05 5 The value of the cost function before optimization cost0 costfuncp0 tobs xobs t0 y0 mprintf r The value of the cost function before optimization g r Solution with optim costoptpoptoptimlistNDcostcostfunc tobs xobs t0 y0p0 ar40401e3 mprintf r The value of the cost function after optimization gcostopt mprintf r The identified values of the parameters c g k g r popt1popt2 NDcost 1532 A small plot t linspace0T400 y uNpopt t t0 y0 clf plot2dty1style5 plot2dtobsxobs1style5 legendmodelmeasurements xtitleLeast square fit to identify ode parameters See Also optim external derivative 1533 Name aplat Flattens a list lfind aplatlr Parameters l a list r an optional flat list lf a flat list a single hierachical level ind a list each entry give the path of the corresponding lf entry in the original list Description Creates a flat list built with the initial l list leaves and if given prepended by the r list entries Examples lfindaplatlist12list31xxxlist321 See Also recons Authors FD and SS INRIA 1534 Name datafit Parameter identification based on measured data perrdatafitimp G DGZ Wcontrp0algodf0mem workstopin Parameters imp scalar argument used to set the trace mode imp0 nothing execpt errors is reported imp1 initial and final reports imp2 adds a report per iteration imp2 add reports on linear search Warning most of these reports are written on the Scilab standard output G function descriptor eGpz e ne x 1 p np x 1 z nz x 1 DG partial of G wrt p function descriptor optional SDGpz S ne x np Z matrix z1z2zn where zi nz x 1 is the ith measurement W weighting matrix of size ne x ne optional defaut no ponderation contr bbinfbsup with binf and bsup real vectors with same dimension as p0 binf and bsup are lower and upper bounds on p p0 initial guess size np x 1 algo qn or gc or nd This string stands for quasiNewton default conjugate gradient or nondifferentiable respectively Note that nd does not accept bounds on x df0 real scalar Guessed decreasing of f at first iteration df01 is the default value mem integer number of variables used to approximate the Hessian algogc or nd Default value is around 6 stop sequence of optional parameters controlling the convergence of the algorithm stop arnap iter epsg epsf epsx ar reserved keyword for stopping rule selection defined as follows nap maximum number of calls to fun allowed iter maximum number of iterations allowed epsg threshold on gradient norm datafit 1535 epsf threshold controlling decreasing of f epsx threshold controlling variation of x This vector possibly matrix of same size as x0 can be used to scale x in reserved keyword for initialization of parameters used when fun in given as a Fortran routine see below p Column vector optimal solution found err scalar least square error Description datafit is used for fitting data to a model For a given function Gpz this function finds the best vector of parameters p for approximating Gpzi0 for a set of measurement vectors zi Vector p is found by minimizing Gpz1WGpz1Gpz2WGpz2 GpznWGpzn datafit is an improved version of fitdat Examples generate the data function yFFxpyp1xp2p3xxendfunction XY pg341214 parameter used to generate data for x013 YYFFxpg100rand5XXxend ZYX The criterion function function eGpz yz1xz2 eyFFxp endfunction Solve the problem p03510 perrdatafitGZp0 scf0clf plot2dXFFXpg5 the curve without noise plot2dXY1 the noisy data plot2dXFFXp12 the solution the gradient of the criterion function function sDGpz ap1bp2cp3yz1xz2 sxbaxx endfunction perrdatafitGDGZp0 datafit 1536 scf1clf plot2dXFFXpg5 the curve without noise plot2dXY1 the noisy data plot2dXFFXp12 the solution Add some bounds on the estimate of the parameters We want positive estimation the result will not change perrdatafitGDGZb000infinfinfp0algogc scf1clf plot2dXFFXpg5 the curve without noise plot2dXY1 the noisy data plot2dXFFXp12 the solution See Also lsqrsolve optim leastsq 1537 Name derivative approximate derivatives of a function derivativeFx J H derivativeFx h order Hform Q Parameters F a Scilab function F Rn Rm or a listFp1pk where F is a scilab function in the form yFxp1pk p1 pk being any scilab objects matrices lists x real column vector of dimension n h optional real the stepsize used in the finite difference approximations order optional integer the order of the finite difference formula used to approximate the derivatives order 12 or 4 default is order2 Hform optional string the form in which the Hessean will be returned Possible forms are Hformdefault H is a m x n2 matrix in this form the kth row of H corresponds to the Hessean of the kth component of F given as the following row vector gradFk being a row vector Hformblockmat H is a mxn x n block matrix the classic Hessean matrices of each component of F are stacked by row H H1 H2 Hm in scilab syntax Hformhypermat H is a n x n matrix for m1 and a n x n x m hypermatrix otherwise Hk is the classic Hessean matrix of the kth component of F Q optional real matrix orthogonal default is eyenn Q is added to have the possibility to remove the arbitrariness of using the canonical basis to approximate the derivatives of a function and it should be an orthogonal matrix It is not mandatory but better to recover the derivative as you need the inverse matrix and so simply Q instead of invQ J approximated Jacobian H approximated Hessian Description Numerical approximation of the first and second derivatives of a function F Rn Rm at the point x The Jacobian is computed by approximating the directional derivatives of the components of derivative 1538 F in the direction of the columns of Q For m1 vQk gradFxv DvFx The second derivatives are computed by composition of first order derivatives If H is given in its default form the Taylor series of Fx up to terms of second order is given by JHderivativeFxHformdefault JJx HHx Performances If the problem is correctly scaled increasing the accuracy reduces the total error but requires more function evaluations The following list presents the number of function evaluations required to com pute the Jacobian depending on the order of the formula and the dimension of x denoted by n order1 the number of function evaluations is n1 order2 the number of function evaluations is 2n order4 the number of function evaluations is 4n Computing the Hessian matrix requires square the number of function evaluations as detailed in the following list order1 the number of function evaluations is n12 order2 the number of function evaluations is 4n2 order4 the number of function evaluations is 16n2 Remarks The step size h must be small to get a low error but if it is too small floating point errors will dominate by cancellation As a rule of thumb do not change the default step size To work around numerical difficulties one may also change the order andor choose different orthogonal matrices Q the default is eyenn especially if the approximate derivatives are used in optimization routines All the optional arguments may also be passed as named arguments so that one can use calls in the form derivativeF x Hform hypermat derivativeF x order 4 etc Examples function yFx ysinx1x2expx2x3x1 sumx3 endfunction function yGxp ysinx1x2pexpx2x3x1 sumx3 endfunction x123 JHderivativeFxHformblockmat n3 derivative 1539 form an orthogonal matrix Q qrrandnn Test order 1 2 and 4 formulas for i124 JHderivativeFxorderiHformblockmatQQ mprintforder d i H end p1 h1e3 JHderivativelistGpxh2Hformhypermat H JHderivativelistGpxh4QQ H Taylor series example dx1e3111 JHderivativeFx Fxdx FxdxFx FxdxFxJdx FxdxFxJdx12Hdx dx A trivial example function yfxApw yxAxpxw endfunction with Jacobian and Hessean given by JxxAAp and HxAA A rand33 p rand31 w 1 x rand31 JHderivativelistfApwxh1Hformblockmat Since fx is quadratic in x approximate derivatives of order2 or 4 by finite differences should be exact for all h0 The apparent errors are caused by cancellation in the floating point operations so a big h is choosen Comparison with the exact matrices Je xAAp He AA cleanJe J cleanHe H Accuracy issues The derivative function uses the same step h whatever the direction and whatever the norm of x This may lead to a poor scaling with respect to x An accurate scaling of the step is not possible without many evaluations of the function Still the user has the possibility to compare the results produced by the derivative and the numdiff functions Indeed the numdiff function scales the step depending on the absolute value of x This scaling may produce more accurate results especially if the magnitude of x is large In the following Scilab script we compute the derivative of an univariate quadratic function The exact derivative can be computed analytically and the relative error is computed In this rather extreme case the derivative function produces no significant digits while the numdiff function produces 6 significant digits derivative 1540 Difference between derivative and numdiff when x is large function y myfunction x y xx endfunction x 1e100 fe 20 x fp derivativemyfunctionx e absfpfefe mprintfRelative error with derivative e e fp numdiffmyfunctionx e absfpfefe mprintfRelative error with numdiff e e The previous script produces the following output Relative error with derivative 1000000e000 Relative error with numdiff 7140672e006 In a practical situation we may not know what is the correct numerical derivative Still we are warned that the numerical derivatives should be used with caution in this specific case See Also numdiff derivat Authors Rainer von Seggern Bruno Pincon 1541 Name fitdat Parameter identification based on measured data perrfitdatGp0Z W pminpmax DG Parameters G Scilab function eGpz e nex1 p npx1 z nzx1 p0 initial guess size npx1 Z matrix z1z2zn where zi nzx1 is the ith measurement W weighting matrix of size nexne optional default 1 pmin lower bound on p optional size npx1 pmax upper bound on p optional size npx1 DG partial of G wrt p optional SDGpz S nexnp Description fitdat is used for fitting data to a model For a given function Gpz this function finds the best vector of parameters p for approximating Gpzi0 for a set of measurement vectors zi Vector p is found by minimizing Gpz1WGpz1Gpz2WGpz2 GpznWGpzn Examples deffyFFxyaxbcxx XY a34b12c14for x013 YYFFx100rand5XXxend ZYX deffeGpzap1bp2cp3yz1xz2eyFFx perrfitdatG3510Z xsetwindow0 clf plot2dXY1 plot2dXFFX5002 ap1bp2cp3plot2dXFFX12002 a34b12c14 deffsDGpzyz1xz2sxp2p1xx perrfitdatG3510ZDG fitdat 1542 xsetwindow1 clf plot2dXY1 plot2dXFFX5002 ap1bp2cp3plot2dXFFX12002 See Also optim datafit 1543 Name fsolve find a zero of a system of n nonlinear functions x v infofsolvex0fct fjac tol Parameters x0 real vector initial value of function argument fct external ie function or list or string fjac external ie function or list or string tol real scalar precision tolerance termination occurs when the algorithm estimates that the relative error between x and the solution is at most tol tol1d10 is the default value x real vector final value of function argument estimated zero v real vector value of function at x info termination indicator 0 improper input parameters 1 algorithm estimates that the relative error between x and the solution is at most tol 2 number of calls to fcn reached 3 tol is too small No further improvement in the approximate solution x is possible 4 iteration is not making good progress Description find a zero of a system of n nonlinear functions in n variables by a modification of the powell hybrid method Jacobian may be provided 0 fctx wrt x fct is an external This external returns vfctx given x The simplest calling sequence for fct is fsolve 1544 vfctx If fct is a character string it refers to a C or Fortran routine which must be linked to Scilab Fortran calling sequence must be fctnxviflag integer niflag double precision xnvn and C Calling sequence must be fctint n double xdouble vint iflag Incremental link is possible help link jac is an external This external returns vdfctdx x given x The simplest calling sequence for jac is vjacx If jac is a character string it refers to a to a C or Fortran routine which must be linked to Scilab calling sequences are the same as those for fct Note however that v must be a nxn array Examples A simple example with fsolve a1728b1011 deffyfsol1xyaxb deffyfsolj1xya xresfsolve100100fsol1 axresb xresfsolve100100fsol1fsolj1 axresb See SCImodulesoptimizationscigatewayfortranExfsolvef xresfsolve100100fsol1fsolj11e7 axresb For some starting points and some equations system the fsolve method can fail The fsolve method is a local search method So to have a good chance to find a solution to your equations system you must ship a good starting point to fsolve Here is an example on which fsolve can fail Another example with fsolve function Ffeulerxr fsolve 1545 Fxrdtx2x3 endfunction function JdFdxx definition de la derivee de F J1dt2x3x2 endfunction r 004257794928862307 dt 10 xvinfofsolverlistfeulerrdFdx fsolve dont find the solution dispv The residual dispinfo The termination indicator xvinfofsolve1listfeulerrdFdx fsolve find the solution dispv The residual dispinfo The termination indicator clfxlinspace011000plotxfeulerx agcaagrid5 5 So each time you use fsolve be sure to check the termination indicator and the residual value to see if fsolve has converged See Also external qpsolve optim 1546 Name karmarkar karmarkar algorithm x1karmarkarabcx0 Parameters a matrix np b n vector c p vector x0 initial vector eps threshold default value 1d5 gamma descent step 0gamma1 default value 14 x1 solution crit value of cx1 Description Computes x which minimizes Examples n10p20 arandnp crandp1 x0absrandp1 bax0 x1karmarkarabcx0 1547 Name leastsq Solves nonlinear least squares problems foptxoptgrdoptleastsqfun x0 foptxoptgrdoptleastsqfun dfun x0 foptxoptgrdoptleastsqfun cstr x0 foptxoptgrdoptleastsqfun dfun cstr x0 foptxoptgrdoptleastsqfun dfun cstr x0 algo foptxoptgrdoptleastsqimp fun dfun cstrx0 algodf0memstop Parameters fopt value of the function fxfunx2 at xopt xopt best value of x found to minimize funx2 grdopt gradient of f at xopt fun a scilab function or a list defining a function from Rn to Rm see more details in DESCRIP TION x0 real vector initial guess of the variable to be minimized dfun a scilab function or a string defining the Jacobian matrix of fun see more details in DESCRIP TION cstr bound constraints on x They must be introduced by the string keyword b followed by the lower bound binf then by the upper bound bsup so cstr appears as bbinfbsup in the calling sequence Those bounds are real vectors with same dimension than x0 inf and inf may be used for dimension which are unrestricted algo a string with possible values qn or gc or nd These strings stand for quasiNewton default conjugate gradient or nondifferentiable respectively Note that nd does not accept bounds on x imp scalar argument used to set the trace mode imp0 nothing except errors is reported imp1 initial and final reports imp2 adds a report per iteration imp2 add reports on linear search Warning most of these reports are written on the Scilab standard output df0 real scalar Guessed decreasing of fun2 at first iteration df01 is the default value mem integer number of variables used to approximate the Hessean second derivatives of f when algoqn Default value is around 6 stop sequence of optional parameters controlling the convergence of the algorithm They are intro duced by the keyword ar the sequence being of the form arnap iter epsg epsf epsx leastsq 1548 nap maximum number of calls to fun allowed iter maximum number of iterations allowed epsg threshold on gradient norm epsf threshold controlling decreasing of f epsx threshold controlling variation of x This vector possibly matrix of same size as x0 can be used to scale x Description fun being a function from Rn to Rm this routine tries to minimize wrt x the function which is the sum of the squares of the components of fun Bound constraints may be imposed on x How to provide fun and dfun fun can be either a usual scilab function case 1 or a fortran or a C routine linked to scilab case 2 For most problems the definition of fun will need supplementary parameters and this can be done in both cases case 1 when fun is a Scilab function its calling sequence must be yfunx optpar1optpar2 When fun needs optional parameters it must appear as listfunoptpar1optpar2 in the calling sequence of leastsq case 2 when fun is defined by a Fortran or C routine it must appear as listfunnamem optpar1optpar2 in the calling sequence of leastsq funname a string being the name of the routine which must be linked to Scilab see link The generic calling se quences for this routine are In Fortran subroutine funm n x params y integer mn double precision xn params ym In C void funint m int n double x double params double y where n is the dimension of vector x m the dimension of vector y which must store the evaluation of fun at x and params is a vector which contains the optional parameters optpar1 optpar2 each parameter may be a vector for instance if optpar1 has 3 components the description of optpar2 begin from params4 fortran case and from params3 C case etc Note that even if fun doesnt need supplementary parameters you must anyway write the fortran code with a params argument which is then unused in the subroutine core In many cases it is adviced to provide the Jacobian matrix dfun dfunijdfidxj to the optimizer which uses a finite difference approximation otherwise and as for fun it may be given as a usual scilab function or as a fortran or a C routine linked to scilab leastsq 1549 case 1 when dfun is a scilab function its calling sequence must be ydfunx optional parameters notes that even if dfun needs optional parameters it must appear simply as dfun in the calling sequence of leastsq case 2 when dfun is defined by a Fortran or C routine it must appear as dfunname a string in the calling sequence of leastsq dfunname being the name of the routine which must be linked to Scilab The calling sequences for this routine are nearly the same than for fun In Fortran subroutine dfunm n x params y integer mn double precision xn params ymn In C void funint m int n double x double params double y in the C case dfunijdfidxj must be stored in ymj1i1 Remarks Like datafit leastsq is a front end onto the optim function If you want to try the LevenbergMar quard method instead use lsqrsolve A least squares problem may be solved directly with the optim function in this case the function NDcost may be useful to compute the derivatives see the NDcost help page which provides a simple example for parameters identification of a differential equation Examples We will show different calling possibilities of leastsq on one trivial example which is non linear but doesnt really need to be solved with leastsq applying log linearizes the model and the problem may be solved with linear algebra In this example we look for the 2 parameters x1 and x2 of a simple exponential decay model x1 being the unknow initial value and x2 the decay constant function y ytht x y x1expx2t endfunction we have the m measures ti yi m 10 tm 025 05 075 10 125 15 175 20 225 25 ym 079 059 047 036 029 023 017 015 012 008 wm onesm1 measure weights here all equal to 1 and we want to find the parameters x such that the model fits the given datas in the least square sense minimize fx sumi wmi2 ythtmix ymi 2 initial parameters guess x0 15 08 in the first examples we define the function fun and dfun in scilab language leastsq 1550 function e myfunx tm ym wm e wm ythtm x ym endfunction function g mydfunx tm ym wm v wmexpx2tm g v x1tmv endfunction now we could call leastsq 1 the simplest call fxopt gropt leastsqlistmyfuntmymwmx0 2 we provide the Jacobian fxopt gropt leastsqlistmyfuntmymwmmydfunx0 a small graphic before showing other calling features tt linspace011maxtm100 yy ythtt xopt clf plot2dtm ym style2 plot2dtt yy style 2 legendmeasure points fitted curve xtitlea simple fit with leastsq 3 how to get some information we use imp1 fxopt gropt leastsq1listmyfuntmymwmmydfunx0 4 using the conjugate gradient instead of quasi Newton fxopt gropt leastsq1listmyfuntmymwmmydfunx0gc 5 how to provide bound constraints not useful here xinf infinf xsup inf inf fxopt gropt leastsqlistmyfuntmymwmbxinfxsupx0 without Jacobian fxopt gropt leastsqlistmyfuntmymwmmydfunbxinfxsupx0 with Jacobian 6 playing with some stopping parameters of the algorithm allows only 40 function calls 8 iterations and set epsg001 epsf01 fxopt gropt leastsq1listmyfuntmymwmmydfunx0ar40800101 7 and 8 now we want to define fun and dfun in fortran then in C Note that the compile and link to scilab method used here is believed to be OS independant but there are some requirements in particular you need a C and a fortran compiler and they must be compatible with the ones used to build your scilab binary 7 fun and dfun in fortran 71 Let s Scilab write the fortran code in the TMPDIR directory fcode subroutine myfunmnxparamf parami tmi parammi ymi param2mi wmi implicit none integer nm double precision xn param fm integer i do i 1m leastsq 1551 fi param2mi x1expx2parami parammi enddo end subroutine fun subroutine mydfunmnxparamdf parami tmi parammi ymi param2mi wmi implicit none integer nm double precision xn param dfmn integer i do i 1m dfi1 param2miexpx2parami dfi2 x1paramidfi1 enddo end subroutine dfun cd TMPDIR mputlfcodeTMPDIRmyfunf 72 compiles it You need a fortran compiler names myfun mydfun flibname ilibforlinknamesmyfunof 73 link it to scilab see link help page linkflibnamenamesf 74 ready for the leastsq call be carreful dont forget to give the dimension m after the routine name fxopt gropt leastsqlistmyfunmtmymwmx0 without Jacobian fxopt gropt leastsqlistmyfunmtmymwmmydfunx0 with Jacobian 8 last example fun and dfun in C 81 Let s Scilab write the C code in the TMPDIR directory ccode include mathh void myfuncint mint n double x double param double f parami tmi parammi ymi param2mi wmi int i for i 0 i m i fi param2mi x0expx1parami parammi return void mydfuncint mint n double x double param double df parami tmi parammi ymi param2mi wmi int i for i 0 i m i dfi param2miexpx1parami dfim x0paramidfi return mputlccodeTMPDIRmyfuncc 82 compiles it You need a C compiler leastsq 1552 names myfunc mydfunc clibname ilibforlinknamesmyfuncoc 83 link it to scilab see link help page linkclibnamenamesc 84 ready for the leastsq call fxopt gropt leastsqlistmyfuncmtmymwmmydfuncx0 See Also lsqrsolve optim NDcost datafit external qpsolve 1553 Name list2vec Catenates list entries in a matrix bigVectorvarsizes list2vecli Parameters li a list with n entries The list entries must be 2D matrices with comptible types bigVector A column vector Formed by the elements of the corresponding list entry varsizes An n by 3 matrix Each row contains the dimensions of the corresponding list entry Description Catenates list entries in a column vector The list entries are supposed to be matrices with compatible types with respect to catenation This function is a subsidiary for lmisolver Examples list2veclist123 list2veclist1 2 345s s1 See Also vec2list Authors FD INRIA 1554 Name lmisolver linear matrix inequation solver XLISTFOPT lmisolverXLIST0evalfunc options Parameters XLIST0 a list of containing initial guess eg XLIST0listX1X2Xn evalfunc a Scilab function external function with specific syntax The syntax the function evalfunc must be as follows LMELMIOBJevalfunctX where X is a list of matrices LME LMI are lists and OBJ a real scalar XLISTF a list of matrices eg XLIST0listX1X2Xn options optional parameter If given options is a real row vector with 5 components Mboundabstolnumaxitersreltol Description lmisolver solves the following problem minimize fX1X2Xn a linear function of Xis under the linear constraints GiX1X2Xn0 for i1p and LMI linear matrix inequali ties constraints HjX1X2Xn 0 for j1q The functions f G H are coded in the Scilab function evalfunc and the set of matrices Xis in the list X ie XlistX1Xn The function evalfun must return in the list LME the matrices G1XGpX ie LMEiGiX1Xn i1p evalfun must return in the list LMI the matrices H1X0HqX ie LMIjHjX1Xn j1q evalfun must return in OBJ the value of fX ie OBJfX1Xn lmisolver returns in XLISTF a list of real matrices i e XLISTlistX1X2Xn where the Xis solve the LMI problem Defining YZ and cost by YZcostevalfuncXLIST Y is a list of zero matrices YlistY1Yp Y10 Y20 Yp0 Z is a list of square symmetric matrices ZlistZ1Zq which are semi positive definite Z10 Z20 Zq0 ie specZj 0 cost is minimized lmisolver can also solve LMI problems in which the Xis are not matrices but lists of matrices More details are given in the documentation of LMITOOL lmisolver 1555 Examples Find diagonal matrix X ie XdiagdiagX p1 such that A1XXA1Q1 0 A2XXA2Q2 0 q2 and traceX is maximized n 2 A1 randnn A2 randnn Xs diag1n Q1 A1XsXsA101eye Q2 A2XsXsA202eye deffLMELMIOBJevalfXlistX Xlist1 LME XdiagdiagX LMI listA1XXA1Q1A2XXA2Q2 OBJ sumdiagX XlmisolverlistzerosA1evalf XX1 YZcevalfX See Also lmitool 1556 Name lmitool tool for solving linear matrix inequations lmitool lmitoolfilename txtlmitoolprobnamevarlistdatalist Parameters filename a string referring to a sci function probname a string containing the name of the problem varlist a string containing the names of the unknown matrices separated by commas if there are more than one datalist a string containing the names of data matrices separated by commas if there are more than one txt a string providing information on what the user should do next Description lmitool or lmitoolfilename is used to define interactively a LMI problem In the non interactive mode txtlmitoolprobnamevarlistdatalist generates a file in the cur rent directory The name of this file is obtained by adding sci to the end of probname This file is the skeleton of a solver function and the corresponding evaluation function needed by lmisolver See Also lmisolver 1557 Name lsqrsolve minimize the sum of the squares of nonlinear functions levenbergmarquardt algorithm x v infolsqrsolvex0fctm stop diag x v infolsqrsolvex0fctm fjac stop diag Parameters x0 real vector of size n initial estimate of the solution vector fct external ie function or list or string m integer the number of functions m must be greater than or equal to n fjac external ie function or list or string stop optional vector ftolxtolgtolmaxfevepsfcnfactor the default value is 1d81d81d510000100 ftol A positive real numbertermination occurs when both the actual and predicted relative reduc tions in the sum of squares are at most ftol therefore ftol measures the relative error desired in the sum of squares xtol A positive real number termination occurs when the relative error between two consecutive iterates is at most xtol therefore xtol measures the relative error desired in the approx imate solution gtol A nonnegative input variable termination occurs when the cosine of the angle between fctx and any column of the jacobian is at most gtol in absolute value therefore gtol measures the orthogonality desired between the function vector and the columns of the ja cobian maxfev A positive integer termination occurs when the number of calls to fct is at least maxfev by the end of an iteration epsfcn A positive real number used in determining a suitable step length for the forwarddifference approximation this approximation assumes that the relative errors in the functions are of the order of epsfcn if epsfcn is less than the machine precision it is assumed that the relative errors in the functions are of the order of the machine precision factor A positive real number used in determining the initial step bound this bound is set to the product of factor and the euclidean norm of diagx if nonzero or else to factor itself in most cases factor should lie in the interval 01100 100 is a generally recommended value diag is an array of length n diag must contain positive entries that serve as multiplicative scale factors for the variables lsqrsolve 1558 x real vector final estimate of the solution vector v real vector value of fctx info termination indicator 0 improper input parameters 1 algorithm estimates that the relative error between x and the solution is at most tol 2 number of calls to fcn reached 3 tol is too small No further improvement in the approximate solution x is possible 4 iteration is not making good progress 5 number of calls to fcn has reached or exceeded maxfev 6 ftol is too small no further reduction in the sum of squares is possible 7 xtol is too small no further improvement in the approximate solutionx is possible 8 gtol is too small fvec is orthogonal to the columns of the jacobian to machine precision Description minimize the sum of the squares of m nonlinear functions in n variables by a modification of the levenbergmarquardt algorithm the user must provide a subroutine which calculates the functions the jacobian is then calculated by a forwarddifference approximation minimize sumfctxm2 where fct is function from Rn to Rm fct should be a Scilab function whose calling sequence is vfctxm given x and m a character string which refers to a C or Fortran routine which must be linked to Scilab Fortran calling sequence should be fctmnxviflag where m n iflag are integers x a double precision vector of size n and v a double precision vector of size m C calling sequence should be fctint m int n double xdouble vint iflag fjac is an external which returns vdfctdx x it should be a Scilab function whose calling sequence is Jfjacxm given x and m lsqrsolve 1559 a character string it refers to a C or Fortran routine which must be linked to Scilab Fortran calling sequence should be fjacmnxjaciflag where m n iflag are inte gers x a double precision vector of size n and jac a double precision vector of size mn C calling sequence should be fjacint m int n double xdouble vint iflag return 1 in iflag to stop the algoritm if the function or jacobian could not be evaluated Examples A simple example with lsqrsolve a17 28 4 3 b10111 function yf1xm yaxb endfunction xsolvlsqrsolve100100f13 xsolab function yfj1xm ya endfunction xsolvlsqrsolve100100f13fj1 xsolab Data fitting problem 1 build the data a34b12c14 deffyFFxyaxbcxx X013YFFX100rand5 solve function ef1abcm aabc1babc2cabc3 eYaXbcXX endfunction abcvlsqrsolve101010f1sizeX1 abc normv See Also external qpsolve optim fsolve Used Functions lmdif lmder from minpack Argonne National Laboratory 1560 Name numdiff numerical gradient estimation gnumdifffunx dx Parameters fun an external Scilab function or list See below for calling sequence see also external for details about external functions x vector the argument of the function fun dx vector the finite difference step Default value is dxsqrteps11d3absx g vector the estimated gradient Description given a function funx from Rn to Rp computes the matrix g such as gij dfidxj using finite difference methods Without parameters the function fun calling sequence is yfunx and numd iff can be called as gnumdifffunx Else the function fun call ing sequence must be yfunxparam1pararm2paramq If parame ters param1param2paramq exist then numdiff can be called as follow gnumdifflistfunparam1param2paramqx See the derivative with respect to numerical accuracy issues and comparison between the two algo rithms Examples example 1 without parameters myfun is a function from R2 to R x1x2 myfunx function fmyfunx fx1x1x1x2 endfunction x5 8 gnumdiffmyfunx The exact gradient ie derivate belong x1 first component and derivate belong x2 second component is exact2x1x2 x1 example 2 with parameters myfun is a function from R to R x1 myfunx myfun contains 3 parameters a b c numdiff 1561 function fmyfunxabc fxacb endfunction a3 b4 c2 x1 g2numdifflistmyfunabcx The exact gradient ie derivate belong x1 is exact2cxac1 See Also optim derivative external 1562 Name optim nonlinear optimization routine fxoptoptimcostfx0 f xopt gradopt workoptimcostf contrx0 algo df0 mem work stop params impiflag Parameters costf external ie Scilab function list or string costf is the cost function that is a Scilab script a Fortran 77 routine or a C function x0 real vector initial value of variable to be minimized f value of optimal cost fcostfxopt xopt best value of x found contr keyword representing the following sequence of arguments bbinfbsup with binf and bsup are real vectors with same dimension as x0 binf and bsup are lower and upper bounds on x algo qn quasiNewton this is the default solver gc conjugate gradient nd nondifferentiable Note that the conjugate gradient solver does not accept bounds on x df0 real scalar Guessed decreasing of f at first iteration df01 is the default value mem integer number of variables used to approximate the Hessian Default value is 10 This feature is available for the GradientConjugate algorithm gc without constraints and the nonsmooth algorithm nd without constraints stop keyword representing the sequence of optional parameters controlling the convergence of the algorithm arnap iter epsg epsf epsx ar reserved keyword for stopping rule selection defined as follows nap maximum number of calls to costf allowed default is 100 iter maximum number of iterations allowed default is 100 epsg threshold on gradient norm optim 1563 epsf threshold controlling decreasing of f epsx threshold controlling variation of x This vector possibly matrix of same size as x0 can be used to scale x params keyword representing the method to initialize the arguments ti td passed to the objective function provided as a C or Fortran routine This option has no meaning when the cost function is a Scilab script params can be set to only one of the following values in That mode allows to allocate memory in the internal Scilab workspace so that the objective function can get arrays with the required size but without directly allocating the memory in stands for initialization In that mode before the value and derivative of the objective func tion is to be computed there is a dialog between the optim Scilab primitive and the objective function In this dialog the objective function is called two times with particular values of the ind parameter The first time ind is set to 10 and the objective function is expected to set the nizs nrzs and ndzs integer parameters of the nird common common nird nizsnrzsndzs This allows Scilab to allocate memory inside its internal workspace The second time the ob jective function is called ind is set to 11 and the objective function is expected to set the ti tr and tz arrays After this initialization phase each time it is called the objective function is ensured that the ti tr and tz arrays which are passed to it have the values that have been pre viously initialized tivalti In this mode valti is expected to be a Scilab vector variable containing integers Whenever the objective function is called the ti array it receives contains the values of the Scilab variable td valtd In this mode valtd is expected to be a Scilab vector variable containing double values When ever the objective function is called the td array it receives contains the values of the Scilab variable tivaltitdvaltd This mode combines the two previous The ti td arrays may be used so that the objective function can be computed For example if the objective function is a polynomial the ti array may may be used to store the coefficients of that polynomial Users should choose carefully between the in mode and the ti and td mode depending on the fact that the arrays are Scilab variables or not If the data is available as Scilab variables then the ti valti td valtd mode should be chosen If the data is available directly from the objective function the in mode should be chosen Notice that there is no tr mode since in Scilab all real values are of double type If neither the in mode nor the ti td mode is chosen that is if params is not present as an option of the optim primitive the user may should not assume that the titr and td arrays can be used reading or writing the arrays may generate unpredictable results optim 1564 impiflag named argument used to set the trace mode The possible values for iflag are 012 and 2 Use this option with caution most of these reports are written on the Scilab standard output iflag0 nothing except errors is reported this is the default iflag1 initial and final reports iflag2 adds a report per iteration iflag2 add reports on linear search iflag0 calls the cost function with ind1 every imp iterations gradopt gradient of costf at xopt work working array for hot restart for quasiNewton method This array is automatically initialized by optim when optim is invoked It can be used as input parameter to speedup the calculations Description Nonlinear optimization routine for programs without constraints or with bound constraints min costfx wrt x costf is an external ie a Scilab function a list or a string giving the name of a C or Fortran routine see external This external must return the value f of the cost function at the point x and the gradient g of the cost function at the point x Scilab function case If costf is a Scilab function the calling sequence for costf must be fgindcostfxind Here costf is a function which returns f value real number of cost function at x and g gradient vector of cost function at x The variable ind is described below List case If costf is a list it should be of the form listrealcostf arg1argn with realcostf a Scilab function with calling sequence fgindcostfxindarg1 argn The x f g ind arguments have the same meaning that above argi arguments can be used to pass function parameters String case If costf is a character string it refers to the name of a C or Fortran routine which must be linked to Scilab Fortran case The interface of the Fortran subroutine computing the objective must be subroutine costfindnxfgtitrtd optim 1565 with the following declarations integer indn ti double precision xnfgntd real tr The argument ind is described below If ind 2 3 or 4 the inputs of the routine are x ind n ti trtd If ind 2 3 or 4 the outputs of the routine are f and g C case The interface of the C function computing the objective must be void costfint ind int n double x double f double g int ti float tr double td The argument ind is described below The inputs and outputs of the function are the same as in the fortran case The ind input argument is a message sent from the solver to the cost function so that the cost function knows what to compute If ind2 costf must provide f If ind3 costf must provide g If ind4 costf must provide f and g If ind1 costf can print messages When the imp option is set to a negative integer value say m for example the cost function is called back every m iterations with the ind1 parameter This can be used to print messages fill a log file or creating an interactive plot See below for sample uses of this feature On output ind0 means that f cannot be evaluated at x and ind0 interrupts the optimization Example Scilab function The following is an example with a Scilab function Notice for simplifications reasons the Scilab function cost of the following example computes the objective function f and its derivative no matter of the value of ind This allows to keep the example simple In practical situations though the com putation of f and g may raise performances issues so that a direct optimization may be to use the value of ind to compute f and g only when needed External function written in Scilab function fgind costxind xref123 f05normxxref2 gxxref endfunction Simplest call x0111 optim 1566 fxoptoptimcostx0 By conjugate gradient you can use qn gc or nd fxoptgoptoptimcostx0gc Seen as non differentiable fxoptgoptoptimcostx0nd Upper and lower bounds on x fxoptgoptoptimcostb1020514x0 Upper and lower bounds on x and setting up the algorithm to gc fxoptgoptoptimcostb1020514x0gc Bound on the number of call to the objective function fxoptgoptoptimcostb1020514x0gcar3 Set max number of call to the objective function 3 Set max number of iterations 100 Set stopping threshold on the value of f 1e6 on the value of the norm of the gradient of the objective function 1e6 on the improvement on the parameters xopt 1e61e61e6 fxoptgoptoptimcostb1020514x0gcar31001e61e61e31e31e3 Additionnal messages are printed in the console fxoptoptimcostx0imp3 Example C function The following is an example with a C function where a C source code is written into a file dynamically compiled and loaded into Scilab and then used by the optim solver The interface of the rosenc function is fixed even if the arguments are not really used in the cost function This is because the un derlying optimization solvers must assume that the objective function has a known constant interface In the following example the arrays ti and tr are not used only the array td is used as a parameter of the Rosenbrock function Notice that the content of the arrays ti and td are the same that the content of the Scilab variable as expected External function written in C C compiler required write down the C code Rosenbrock problem Cinclude mathh double sqdouble x return xx void rosencint ind int n double x double f double g int ti float tr double td double p int i ptd0 if ind2ind4 f10 for i1ini fpsqxisqxi1sq10xi if ind3ind4 g040px1sqx0x0 optim 1567 for i1in1i gi20pxisqxi140pxi1sqxixi2010xi gn120pxn1sqxn22010xn1 cd TMPDIR mputlCTMPDIRrosencc compile the C code lilibforlinkrosencrosenccc incremental linking linklrosencc solve the problem x0401050 p100 fxogooptimrosencx0tdp Example Fortran function The following is an example with a Fortran function External function written in Fortran Fortran compiler required write down the Fortran code Rosenbrock problem F subroutine rosenfind n x f g ti tr td integer indnti double precision xnfgntd real tr c double precision yp ptd1 if indeq2orindeq4 then f10d0 do i2n ffpxixi12210d0xi2 enddo endif if indeq3orindeq4 then g140d0px2x12x1 ifngt2 then do i2n1 gi20d0pxixi1240d0pxi1xi2xi 20d010d0xi enddo endif gn20d0pxnxn1220d010d0xn endif return end cd TMPDIR mputlFTMPDIRrosenff compile the Fortran code lilibforlinkrosenfrosenfff optim 1568 incremental linking linklrosenff solve the problem x0401050 p100 fxogooptimrosenfx0tdp Example Fortran function with initialization The following is an example with a Fortran function in which the in option is used to allocate memory inside the Scilab environment In this mode there is a dialog between Scilab and the objective function The goal of this dialog is to initialize the parameters of the objective function Each part of this dialog is based on a specific value of the ind parameter At the beginning Scilab calls the objective function with the ind parameter equals to 10 This tells the objective function to initialize the sizes of the arrays it needs by setting the nizs nrzs and ndzs integer parameters of the nird common Then the objective function returns At this point Scilab creates internal variables and allocate memory for the variable izs rzs and dzs Scilab calls the objective function back again this time with ind equals to 11 This tells the objective function to initialize the arrays izs rzs and dzs When the objective function has done so it returns Then Scilab enters in the real optimization mode and calls the optimization solver the user requested Whenever the objective function is called the izs rzs and dzs arrays have the values that have been previously initialized Define a fortran source code and compile it fortran compiler required fortransource subroutine rosenfindnxfgizsrzsdzs C c Example of cost function given by a subroutine c if n2 returns ind0 c fbonnans oct 86 implicit double precision ahoz real rzs1 double precision dzs dimension xngnizs commonnirdnizsnrzsndzs if nlt3 then ind0 return endif ifindeq10 then nizs2 nrzs1 ndzs2 return endif ifindeq11 then izs15 izs210 dzs21000d0 return endif ifindeq2go to 5 ifindeq3go to 20 ifindeq4go to 5 optim 1569 ind1 return 5 f10d0 do 10 i2n im1i1 10 ff dzs2xixim122 10d0xi2 ifindeq2return 20 g140d0dzs2x2x12x1 nm1n1 do 30 i2nm1 im1i1 ip1i1 gi20d0dzs2xixim12 30 gigi 40d0dzs2xip1xi2xi 20d010d0xi gn20d0dzs2xnxnm12 20d010d0xn return end cd TMPDIR mputlfortransourceTMPDIRrosenff compile the C code libpathilibforlinkrosenfrosenfff incremental linking linkidlinklibpathrosenff x012ones15 Solve the problem fxgoptimrosenfx0in Example Fortran function with initialization on Win dows with Intel Fortran Compiler Under the Windows operating system with Intel Fortran Compiler one must carefully design the for tran source code so that the dynamic link works properly On Scilabs side the optimization compo nent is dynamically linked and the symbol nird is exported out of the optimization dll On the cost functions side which is also dynamically linked the nird common must be imported in the cost function dll The following example is a rewriting of the previous example with special attention for the Windows operating system with Intel Fortran compiler as example In that case we introduce additionnal com piling instructions which allows the compiler to import the nird symbol fortransourcesubroutine rosenfindnxfgizsrzsdzs cDEC IF DEFINED FORDLL cDEC ATTRIBUTES DLLIMPORT nird cDEC ENDIF C c Example of cost function given by a subroutine c if n2 returns ind0 c fbonnans oct 86 implicit double precision ahoz optim 1570 etc Example Logging features The imp flag may take negative integer values say k In that case the cost function is called once every k iterations This allows to draw the function value or write a log file In the following example we solve the Rosenbrock test case For each iteration of the algorithm we print the value of x f and g function fgind costxind xref123 if ind 1 ind 4 then f05normxxref2 end if ind 1 ind 4 then gxxref end if ind 1 then mprintf mprintfx s strcatstringx mprintff e f gxxref mprintfg s strcatstringg end endfunction x0111 fxoptoptimcostx0imp1 The previous script produces the following output x 1 1 1 f 6500000e000 g 0 3 2 x 1 0 16666667 f 2888889e000 g 0 2 13333333 x 1 2 3 f 9860761e031 g 0 4441D16 1332D15 x 1 2 3 f 0000000e000 g 0 0 0 In the following example we solve the Rosenbrock test case For each iteration of the algorithm we plot the current value of x into a 2D graph containing the contours of Rosenbrocks function This allows to see the progress of the algorithm while the algorithm is performing We could as well write the value of x f and g into a log file if needed optim 1571 1 Define rosenbrock function f g ind rosenbrock x ind if ind 1 ind 4 then f 1000 x2x122 1x12 end if ind 1 ind 4 then g1 400 x2 x12 x1 2 1 x1 g2 200 x2 x12 end if ind 1 then plot x1 x2 g end endfunction x0 12 10 xopt 10 10 2 Draw the contour of Rosenbrocks function xmin 20 xmax 20 stepx 01 ymin 10 ymax 20 stepy 01 nx 100 ny 100 stepx xmax xminnx xdata xminstepxxmax stepy ymax yminny ydata yminstepyymax for ix 1lengthxdata for iy 1lengthydata x xdataix ydataiy f g ind rosenbrock x 4 zdata ix iy f end end contour xdata ydata zdata 1 10 100 500 1000 plotx01 x02 b plotxopt1 xopt2 r 3 Plot the optimization process during optimization fopt xopt optim rosenbrock x0 imp 1 Example Optimizing with numerical derivatives It is possible to optimize a problem without an explicit knowledge of the derivative of the cost function For this purpose we can use the numdiff or derivative function to compute a numerical derivative of the cost function In the following example we use the numdiff function to solve Rosenbrocks problem function f rosenbrock x f 1000 x2x122 1x12 endfunction optim 1572 function f g ind rosenbrockCost x ind if ind 1 ind 4 then f rosenbrock x end if ind 1 ind 4 then g numdiff rosenbrock x end endfunction x0 12 10 fopt xopt optim rosenbrockCost x0 In the following example we use the derivative function to solve Rosenbrocks problem Given that the step computation strategy is not the same in numdiff and derivative this might lead to improved results function f rosenbrock x f 1000 x2x122 1x12 endfunction function f g ind rosenbrockCost2 x ind if ind 1 ind 4 then f rosenbrock x end if ind 1 ind 4 then g derivative rosenbrock x order 4 end endfunction x0 12 10 fopt xopt optim rosenbrockCost2 x0 Example Counting function evaluations and number of iterations The imp option can take negative values If the imp is equal to m where m is a negative integer then the cost function is evaluated every m iterations with the ind input argument equal to 1 The following example uses this feature to compute the number of iterations The global variable mydata is used to store the number of function evaluations as well as the number of iterations xref123 x0111 global MYDATA MYDATA tlist TMYDATAniternfevals MYDATAniter 0 MYDATAnfevals 0 function fgind costxind global MYDATA dispind if ind 1 MYDATAniter MYDATAniter 1 end MYDATAnfevals MYDATAnfevals 1 optim 1573 f05normxxref2 gxxref endfunction fxoptoptimcostx0imp1 mprintf Number of function evaluationsd MYDATAnfevals mprintf Number of iterationsd MYDATAniter While the previous example perfectly works there is a risk that the same variable MYDATA is used by some internal function used by optim In this case the value may be wrong This is why a sufficiently weird variable name has been used Example Passing extra parameters In most practical situations the cost function depends on extra parameters which are required to eval uate the cost function There are several methods to achieve this goal In the following example the cost function uses 4 parameters a b c and d We define the cost function with additionnal input arguments which are declared after the index argument Then we pass a list as the first input argument of the optim solver The first element of the list is the cost function The additionnal variables are directly passed to the cost function function f g ind costfunction x ind a b c d f a x1 c 2 b x2 d 2 g1 2 a x1 c g2 2 b x2 d endfunction x0 1 1 a 10 b 20 c 30 d 40 costf list costfunction a b c d fopt xopt optim costf x0 imp 2 These coefficients are defined before the optimizer is called There are directly used in the cost func tion The example NOT to follow function f g ind costfunction x ind f a x1 c 2 b x2 d 2 g1 2 a x1 c g2 2 b x2 d endfunction x0 1 1 a 10 b 20 c 30 d 40 fopt xopt optim costfunction x0 imp 2 optim 1574 While the previous example perfectly works there is a risk that the same variables are used by some internal function used by optim In this case the value of the parameters are not what is expected and the optimization can fail or worse give a wrong result In the following example we define the cost function with the classical header Inside the function definition we declare that the parameters a b c and d are global variables Then we declare and set the global variables Another example NOT to follow function f g ind costfunction x ind global a b c d f a x1 c 2 b x2 d 2 g1 2 a x1 c g2 2 b x2 d endfunction x0 1 1 global a b c d a 10 b 20 c 30 d 40 fopt xopt optim costfunction x0 imp 2 While the previous example perfectly works there is a risk that the same variables are used by some internal function used by optim In this case the value of the parameters are not what is expected and the optimization can fail or worse give a wrong result Example Checking that derivatives are correct Many optimization problem can be avoided if the derivatives are computed correctly One common reason for failure in the steplength procedure is an error in the calculation of the cost function and its gradient Incorrect calculation of derivatives is by far the most common user error In the following example we give a false implementation of Rosenbrocks gradient In order to check the computation of the derivatives we use the derivative function We define the simplified function which delegates the computation of f to the rosenbrock function The simplified func tion is passed as an input argument of the derivative function function f g index rosenbrock x index f 1000 x2x122 1x12 Exact g1 400 x2 x12 x1 2 1 x1 Wrong g1 1200 x2 x12 x1 2 1 x1 g2 200 x2 x12 endfunction function f simplified x index 1 f g index rosenbrock x index endfunction x0 12 1 index 1 f g index rosenbrock x0 index optim 1575 gnd derivative simplified x0 mprintf Exact derivatives strcat stringg mprintf Numerical derivatives strcat stringgnd The previous script produces the following output Obviously the difference between the two gradient is enormous which shows that the wrong formula has been used in the gradient Exact derivative638 88 Numerical derivative2156 88 See Also external qpsolve datafit leastsq numdiff derivative NDcost References The following is a map from the various options to the underlying solvers with some comments about the algorithm when available qn without constraints n1qn1 a quasiNewton method with a Wolfetype line search qn with bounds constraints qnbd a quasiNewton method with projection RR0242 A variant of a projected variable metric method for bound constrained optimization problems Bonnans Frederic Rapport de recherche de lINRIA Rocquencourt Octobre 1983 gc without constraints n1qn3 a conjugate gradient method with BFGS gc with bounds constraints gcbd a BFGStype method with limited memory and projection nd without constraints n1fc1 a bundle method nd with bounds constraints not available Author The Modulopt library JFrederic Bonnans JeanCharles Gilbert Claude Lemarechal The interfaces to the Modulopt library JFrederic Bonnans This help Michael Baudin 1576 Name qld linear quadratic programming solver xlagrqldQpCbcicsme tol xlagrinfoqldQpCbcicsme tol Parameters Q real positive definite symmetric matrix dimension n x n p real column vector dimension n C real matrix dimension me md x n b RHS column vector dimension me md ci column vector of lowerbounds dimension n If there are no lower bound constraints put ci If some components of x are bounded from below set the other unconstrained values of ci to a very large negative number eg cij numberpropertieshuge cs column vector of upperbounds Same remarks as above me number of equality constraints ie C1mex b1me tol Floatting point number required prÃcision x optimal solution found lagr vector of Lagrange multipliers If lower and upperbounds cics are provided lagr has n me md components and lagr1n is the Lagrange vector associated with the bound constraints and lagr n1 n me md is the Lagrange vector associated with the linear constraints If an upperbound resp lowerbound constraint i is active lagri is 0 resp 0 If no bounds are provided lagr has only me md components info integer return the execution status instead of sending errors info1 Too many iterations needed info2 Accuracy insufficient to statisfy convergence criterion info5 Length of working array is too short info10 The constraints are inconsistent qld 1577 Description This function requires Q to be positive definite if it is not the case one may use the The contributed toolbox quapro Examples Find x in R6 such that C1x b1 3 equality constraints ie me3 C1 111031 103456 253010 b1123 C2x b2 2 inequality constraints C2010121 102110 b2125 with x between ci and cs ci1000100000100010001000cs10000100151001001000 and minimize 05xQx px with p123456 Qeye66 No initial point is given CC1C2 bb1b2 me3 xlagrqldQpCbcicsme Only linear constraints 1 to 4 are active lagr160 See Also qpsolve optim The contributed toolbox quapro may also be of interest in particular for singular Q Authors KSchittkowski University of Bayreuth Germany AL Tits and JL Zhou University of Maryland qld 1578 Used Functions ql0001f in modulesoptimizationsrcfortranql0001f 1579 Name qpsolve linear quadratic programming solver builtin x iact iter fqpsolveQp1C1bme Parameters Q real positive definite symmetric matrix dimension n x n p real column vector dimension n C real matrix dimension me md x n This matrix may be dense or sparse b RHS column vector dimension mme md me number of equality constraints ie xC1me b1me x optimal solution found iact vector indicator of active constraints The first non zero entries give the index of the active con straints iter 2x1 vector first component gives the number of main iterations the second one says how many constraints were deleted after they became active Description This function requires Q to be symmetric positive definite If this hypothesis is not satisfied one may use the contributed quapro toolbox Examples Find x in R6 such that xC1 b1 3 equality constraints ie me3 C1 11 2 1 0 5 13 3 04 0 3 5 1 1 6 0 qpsolve 1580 b1123 xC2 b2 2 inequality constraints C2 0 1 1 0 02 11 21 1 0 b2 125 and minimize 05xQx px with p123456 Qeye66 me3 xiactiterfqpsolveQpC1 C2b1b2me Only linear constraints 1 to 4 are active See Also optim qld qpsolve The contributed toolbox quapro may also be of interest in particular for singular Q Memory requirements Let r be rminmn Then the memory required by qpsolve during the computations is 2nrr52 2m 1 Authors S Steer INRIA Scilab interface Berwin A Turlach School of Mathematics and Statistics M019 The University of Western Australia Crawley AUSTRALIA solver code References Goldfarb D and Idnani A 1982 Dual and PrimalDual Methods for Solving Strictly Convex Quadratic Programs in JP Hennart ed Numerical Analysis Proceedings Cocoyoc Mexico 1981 Vol 909 of Lecture Notes in Mathematics SpringerVerlag Berlin pp 226239 Goldfarb D and Idnani A 1983 A numerically stable dual method for solving strictly convex quadratic programs Mathematical Programming 27 133 QuadProg Quadratic Programming Routines Berwin A Turlachhttpwwwmathsuwaeduau berwinsoftwarequadproghtml qpsolve 1581 Used Functions qpgen2f and qpgen1f also named QPsolvef developped by Berwin A Turlach according to the GoldfarbIdnani algorithm 1582 Name qpsolve linear quadratic programming solver x iact iter fqpsolveQpCbcicsme Parameters Q real positive definite symmetric matrix dimension n x n p real column vector dimension n C real matrix dimension me md x n This matrix may be dense or sparse b RHS column vector dimension mme md ci column vector of lowerbounds dimension n If there are no lower bound constraints put ci If some components of x are bounded from below set the other unconstrained values of ci to a very large negative number eg cij numberpropertieshuge cs column vector of upperbounds Same remarks as above me number of equality constraints ie C1mex b1me x optimal solution found iact vector indicator of active constraints The first non zero entries give the index of the active con straints iter 2x1 vector first component gives the number of main iterations the second one says how many constraints were deleted after they became active Description This function requires Q to be symmetric positive definite If that hypothesis is not satisfied one may use the quapro function which is provided in the Scilab quapro toolbox The qpsolve solver is implemented as a Scilab script which calls the compiled qpsolve primitive It is provided as a facility in order to be a direct replacement for the former quapro solver indeed the qpsolve 1583 qpsolve solver has been designed so that it provides the same interface that is the same inputoutput arguments But the x0 and imp input arguments are available in quapro but not in qpsolve Examples Find x in R6 such that C1x b1 3 equality constraints ie me3 C1 111031 103456 253010 b1123 C2x b2 2 inequality constraints C2010121 102110 b2125 with x between ci and cs ci1000100000100010001000 cs10000100151001001000 and minimize 05xQx px with p123456 Qeye66 No initial point is given CC1C2 bb1b2 me3 xiactiterfqpsolveQpCbcicsme Only linear constraints 1 to 4 are active See Also optim qpsolve qld The contributed toolbox quapro may also be of interest in particular for singular Q Memory requirements Let r be rminmn Then the memory required by qpsolve during the computations is 2nrr52 2m 1 Authors S Steer INRIA Scilab interface qpsolve 1584 Berwin A Turlach School of Mathematics and Statistics M019 The University of Western Australia Crawley AUSTRALIA solver code References Goldfarb D and Idnani A 1982 Dual and PrimalDual Methods for Solving Strictly Convex Quadratic Programs in JP Hennart ed Numerical Analysis Proceedings Cocoyoc Mexico 1981 Vol 909 of Lecture Notes in Mathematics SpringerVerlag Berlin pp 226239 Goldfarb D and Idnani A 1983 A numerically stable dual method for solving strictly convex quadratic programs Mathematical Programming 27 133 QuadProg Quadratic Programming Routines Berwin A Turlachhttpwwwmathsuwaeduau berwinsoftwarequadproghtml Used Functions qpgen1f also named QPsolvef developped by Berwin A Turlach according to the GoldfarbIdnani algorithm 1585 Name quapro linear quadratic programming solver obsolete Description This function is superseded by qpsolve Users who are still interested by quapro may consider the Scilab quapro toolbox which provide the same features as in older Scilab releases See at httpwwwscilaborgcontribindexcontribphppagedownloadphp See Also qpsolve 1586 Name readmps reads a file in MPS format mps readmps filenamebounds maxsizes Parameters filename a string the name of the mps file bounds 2vector lowboundupbound default lower and upper bounds maxsizes 3vector maxmmaxnmaxnza Maximum number of contraints and variables maximum number of nonzeros entries in the LP constraint matrix If omitted readmps reads the file once just to compute these numbers mps tlist with following fields irobj integer index of the objective row namec character string Name of the objective nameb character string Name of the right hand side namran character string Name of the ranges section nambnd character string Name of the bounds section name character string Name of the LP problem rownames character string column vector Name of the rows colnames character string row vector Name of the columns rowstat integer vector row types 1 row type is 2 row type is 3 row type is 4 objective row readmps 1587 5 other free row rowcode real matrix hdrowcdlnkrow with hdrowcd real vector Header to the linked list of rows with the same codes lnkrow integer vector Linked list of rows with the same codes colcode real matrix hdcolcdlnkcol with hdcolcd integer vector Header to the linked list of columns with the same codes lnkcol integer vector Linked list of columns with the same codes rownmbs integer vector Row numbers of nonzeros in columns of matrix A colpnts integer vector Pointers to the beginning of columns of matrix A acoeff real vector Array of nonzero elements for each column rhs real vector Right hand side of the linear program ranges real vector of constraint ranges bounds real matrix lboundsubounds with ubounds full column vector of upper bounds lbounds full column vector of lower bounds stavar full column vector of variable status 0 standard non negative variable 1 upper bounded variable 2 lower bounded variable 3 lower and upper bounded variable 4 minus infinity type variable ie infxu readmps 1588 5 plus infinity type variable ie lx inf 6 fixed type variable ie lxu k free variable Description Reads a file containing description of an LP problem given in MPS format and returns a tlist which describes the problem It is an interface with the program rdmps1f of hopdm J Gondzio For a description of the variables see the file rdmps1f MPS format is a standard ASCII medium for LP codes MPS format is described in more detail in Murtaghs book Murtagh B 1981 Advanced Linear Programming McGrewHill New York 1981 Examples Let the LP problem objective min XONE 4 YTWO 9 ZTHREE constraints LIM1 XONE YTWO 5 LIM2 XONE ZTHREE 10 MYEQN YTWO ZTHREE 7 Bounds 0 XONE 4 1 YTWO 1 Generate MPS file txtNAME TESTPROB ROWS N COST L LIM1 G LIM2 E MYEQN COLUMNS XONE COST 1 LIM1 1 XONE LIM2 1 YTWO COST 4 LIM1 1 YTWO MYEQN 1 ZTHREE COST 9 LIM2 1 ZTHREE MYEQN 1 RHS RHS1 LIM1 5 LIM2 10 RHS1 MYEQN 7 BOUNDS UP BND1 XONE 4 LO BND1 YTWO 1 UP BND1 YTWO 1 ENDATA mputltxtTMPDIRtestmps readmps 1589 Read the MPS file PreadmpsTMPDIRtestmps0 1030 dispP 1590 Nom recons reciprocal function for aplat r reconsflind Parameters fl a flat list ind a list of paths r a hierachical list build with the leaves of fl Description Reciprocal function for aplat Creates a hierachical list given a flat one and a list of paths utility function for vec2list and lmisolver Examples lfindaplatlist12list31xxxlist321 reconslfind See Also aplat Authors FD and SS INRIA 1591 Name semidef semidefinite programming xZulinfosemidefx0Z0Fblckszscoptions Parameters x0 m x 1 real column vector must be strictly primal feasible see below Z0 L x 1 real vector compressed form of a strictly feasible dual matrix see below F L x m1 real matrix blckszs p x 2 integer matrix sizes of the blocks defining the dimensions of the square diagonal blocks sizeFijblckszsj j1m1 c m x 1 real vector options row vector with five entries nuabstolreltol0maxiters ul row vector with two entries Description xZulinfosemidefx0Z0Fblckszscoptions solves semidefinite pro gram and its dual exploiting block structure in the matrices Fi It interfaces L Vandenberghe and S Boyd spc program The Fis matrices are stored columnwise in F in compressed format if Fij i0m j1L denote the jth symmetric diagonal block of Fi then semidef 1592 where packM for symmetric M is the vector M11M12M1nM22M23M2nMnn ob tained by scanning columnwise the lower triangular part of M blckszs gives the size of block j ie sizeFijblckszsj Z is a block diagonal matrix with L blocks Z0 ZL1 Zj has size blckszsj times blckszsj Every block is stored using packed storage of the lower triangular part The 2 vector ul contains the primal objective value cx and the dual objective value traceF0Z The entries of options are respectively nu a real parameter which ntrols the rate of convergence abstol absolute tolerance reltol relative tolerance has a special meaning when negative tv target value only referenced if reltol 0 iters on entry maximum number of iterations 0 on exit the number of iterations taken Notice that the absolute tolerance cannot be lower than 10e8 that is the absolute tolerance used in the algorithm is the maximum of the userdefined tolerance and the constant tolerance 10e8 info returns 1 if maxiters exceeded 2 if absolute accuracy is reached 3 if relative accuracy is reached 4 if target value is reached 5 if target value is not achievable negative values indicate errors Convergence criterion 1 maxiters is exceeded 2 duality gap is less than abstol 3 primal and dual objective are both positive and duality gap is less than reltol dual objective or primal and dual objective are both negative and duality gap is less than reltol minus the primal objective 4 reltol is negative and primal objective is less than tv or dual objective is greater than tv Examples F02100 1200 0031 0013 F11200 2100 0013 0031 semidef 1593 F22200 2200 0034 0044 blckszs22 F01F01212F02F03434 F11F11212F12F13434 F21F21212F22F23434 x000 Z02F0 Z01Z01212Z02Z03434 FFF01F02F11F12F21F22 ZZ0Z01Z02 ctraceF1Z0traceF2Z0 options101d101d10050 xZulinfosemidefx0packZZ0packFFblckszscoptions wvec2listunpackZblckszsblckszsblckszsZsysdiagw1w2 cxtraceF0Z specF0F1x1F2x2 traceF1Zc1 traceF2Zc2 References L Vandenberghe and S Boyd Semidefinite Programming Informations Systems Laboratory Stan ford University 1994 Ju E Nesterov and M J Todd SelfScaled Cones and InteriorPoint Methods in Nonlinear Program ming Working Paper CORE Catholic University of Louvain LouvainlaNeuve Belgium April 1994 SP Software for Semidefinite Programming httpwwweeuclaeduvandenbesphtml 1594 Name vec2list list2vec reciprocal function livec2listbigVectorvarsizesind Parameters bigVector An m by n matrix Each column is used to generate the corresponding list entry varsizes An n by 2 matrix Each row give the dimensions of the matrix to be built with the correponding column of bigVector ind a list with n entries Each entry is a vector of positive integers which gives the hierchical path where the corresponding matrix has to be put li a list or a recursive list with n leaves The list entries or leaves are 2D matrices built with the corresponding column of bigVector and size given by the corresponding row of varsizes Description If the ind argument is not given this function creates a list The list entries or leaves are 2D matrices built with the corresponding column of bigVector and size given by the corresponding row of varsizes If the ind argument is given this function creates a hierachical list with n leaves The leaves are 2D matrices built with the corresponding column of bigVector and size given by the corresponding row of varsizes The hierachical path for each leaf if given by the corresponding entry of ind This function is a subsidiary for lmisolver Examples vec2list14ones42 vec2list142 11 2 vec2list14ones42list1231321 See Also list2vec Authors FD INRIA SS INRIA Parte XXVI Sobrecarga 1596 Name overloading capacidades de overloading sobrecarga de exibições funções e operadores Descrição No Scilab exibições funções e operadores de variáveis podem ser definidos para novos objetos uti lizando funções codificadas no Scilab ou primitivas Exibição Display a exibição de objetos definidos por uma estrutura tlist pode ser sobrecarregada a exibição padrão é semelhante a de lists A função de sobrecarga não deve ter argumentos de saída e deve ter um único argumento de entrada Seu nome é formado como segue tlisttypep onde tlisttype significa a primeira entrada do componente do tipo tlist truncado aos 9 primeiros caracteres Operadores Operators cada operador que não está definido para dados tipos de operandos pode ser definido A função de sobrecarga deve ter um único argumento de saída e um ou dois de entrada de acordo com o número de operandos O nome da função é definido como segue para operadores binários tipodoprimeirooperandocódigodo operadortipodosegundooperando para operadores unários tipodooperandocódigodooperador Operadores de extração e inserção que são nnários são descritos abaixo tipodooperando tipodoprimeirooperando tipodosegundooperando são seqüências de caracteres associadas a cada tipo de dado como descrito na tabela seguinte tipo de dado código char tipo de dado código char constante s booleano b string c bibilioteca f ponteiro de função fptr manipulador h inteiro i lista l função m função compilada mc polinômio p esparso sp esparso booleano spb tlist tlisttype polinômio de tamanho implícito ip matriz esparsa do Mat lab msp mlist mlisttype ponteiro ptr códigodooperador é um único caractere associado a cada operador como descrito na tabela seguinte operador código char operador código char t a s m r l p x d q overloading 1597 k y z b u v w ab c ab f extraction e insertion i o n g h j 5 0 1 2 3 4 iext 6 A função de sobrecarga para sintaxe de extração bai1in tem a seguinte seqüência de chamamento btipodeaei1ina e a sintaxex1xmai1in tem a seguinte seqüência de chamamento x1xmtipodeaei1ina A função de sobrecarga associada à sintaxe de inserção ai1inb tem a segunite seqüência de chamamento atipodebitipodeai1inba O código char 6 pode ser usado para alguns algoritmos de inserção complexos como xb233 onde o campo b não está definido na estrutura x A inserção é automaticamente decomposta em tempxb temp233 xbtemp O código char 6 é usado para o primeiro passo desse algoritmo A função de sobrecarga de 6 é muito semelhante à função de es Funções Functions algumas funções primitivas básicas também podem ser sobrecarregadas para novos tipo de dados Quando tal função não é definida para tipos de dados particulares a função tipodeumargumentonomedafunção é chamada O usuário pode adi cionar a esta função chamada a definição associada aos tipos de dados de entrada Exemplos EXIBIÇÃO defftabpldisp l3 l2stringl4 tlisttababxyrand22 OPERADOR deffxcasabxastringb s1 FUNÇÃO deffxcsinaxsina sin2x Ver Também tlist disp symbols Parte XXVII Polinômios 1599 Name bezout equação de Bezout para polinômios ou inteiros thegcdUbezoutp1p2 Parâmetros p1 p2 dois polinômios reais ou dois escalares inteiros tipo igual a 8 Descrição thegcdUbezoutp1p2 computa o MDC thegcd de p1 e p2 e também uma matriz 2x2 unimodular U tal quet p1p2U thegcd0 O MMC de p1 e p2 é dado por p1U12 or p2U22 Exemplos caso polinomial xpoly0x p1x1x35p2x2x33 thegcdUbezoutp1p2 detU cleanp1p2U thelcmp1U12 lcmp1p2 caso inteiro i1int32235 i2int322332 thegcdUbezouti1i2 Vint322235 233222345 thegcdUgcdV VU lcmV Ver Também poly roots simp clean lcm Autor S Steer INRIA 1600 Name clean limpa matrizes arredonda para zero entradas pequenas BcleanA epsa epsr Parâmetros A uma matriz numérica de escalares de polinômios esparsa epsaepsr números reais valores padrões respectivos 1d10 e 1d10 Descrição Esta função elimina ie ajusta para zero todos os coeficientes com valores absolutos epsa e val ores relativos epsr relativo siginifica em relação à norma1 de coeficientes em um polinômio possivelmente uma matriz de polinômios ou matriz de razões de polinômios Os valores padrões são epsa1d10 e epsr1d10 Para uma matriz de constantes cleanAepsa ajusta para zero todas as entradas menores que epsa Exemplos xpoly0x wx12x3x2xx2123x3 winvw cleanwinvw 1601 Name cmndred forma de denominador comum ndcmndrednumden Parâmetros num den duas matrizes de polinômios de dimensões iguais Descrição ndcmndrednumden computa uma matriz de polinômios n e um polinômio denominador comum d tais que ndnumden A matriz de razões de polinômios definida por numden é nd Ver Também simp clean 1602 Name coeff coeficientes de matrizes de polinômios CcoeffMp v Parâmetros Mp matriz de polinômios v vetor linha ou coluna de inteiros dos graus selecionados C matriz grande dos coeficientes Descrição CcoeffMp retorna em uma matriz grande C os coeficientes da matriz de polinômios Mp C é particionada como CC0C1Ck onde os Ci estão dispostos em ordem crescente k maxidegreeMp CcoeffMpv retorna a matriz de coeficientes com graus em v v é um vetor linha ou coluna Ver Também poly degree invcoeff Autor S Steer INRIA 1603 Name coffg matriz inversa de polinômios NsdcoffgFs Parâmetros Fs matriz quadrada de polinômios Descrição coffg computa Fs1 onde Fs é uma matriz de polinômios pelo método dos cofatores Fs inverse Nsd d denominador comum Ns numerador uma matriz de polinômios Para matrizes grandes seja paciente os resultados geralmente são confiáveis Exemplos spoly0s a s s21 s s21 a1dcoffga a1dinva Ver Também determ detr invr penlaur glever Autor F D 1604 Name colcompr compressão de colunas de matrizes de polinômios YrkaccolcomprA Parâmetros A matriz de polinômios Y matriz de polinômios quadrada base unimodular direita rk posto normal de A Ac AcAY matriz de polinômios Descrição Compressão de colunas da matriz de polinômios A compressão para a esquerda Exemplos spoly0s psss122s2s3 Yrkaccolcomprpp ppY Ver Também rowcompr 1605 Name degree grau da matriz de polinômios DdegreeM Parâmetros M matriz de polinômios D matriz de inteiros Descrição Retorna a matriz de graus mais elevados de M Ver Também poly coeff clean 1606 Name denom denominador dendenomr Parâmetros r matriz de polinômios de razões de polinômios ou de constantes den matriz de polinômios Descrição dendenomr retorna o denominador de uma matriz de razões de polinômios Desde que razões de polinômios são representadas internamente como rlistrnumdendtnumden denomr é o mesmo que r3 rden ou rden Ver Também numer 1607 Name derivat derivada de matriz de razões de polinômios pdderivatp Parâmetros p matriz de polinômios ou de razões de polinômios Descrição Computa a derivada da matriz de polinômios ou de funções racionais em relação à variável livre Exemplos spoly0s derivat1s 1s2 1608 Name determ determinante de matrizes de polinômios resdetermW k Parâmetros W matriz quadrada de polinômios reais k inteiro limite superior para o grau do determinante de W Descrição Retorna o determinante de uma matriz de polinômios reais computação feita por Transformada Rápida de Fourier TRF se W possuir tamanho maior do que 22 resdetermW kk é um inteiro maior do que o grau verdadeiro do determinante de W O valor padrão de k é a menor potência de 2 que é maior que nmaxidegreeW Método apenas se o tamanho de W for maior que 22 avalia o determinante de W para as freqüências de Fourier e aplica a TRF inversa para os coeficientes do determinante Exemplos spoly0s wsrand1010 determw detcoeffw1s10 Ver Também det detr coffg Autor FD 1609 Name detr determinante polinomial ddetrh Parâmetros h matriz quadrada de polinômios ou de razões de polinômios Descrição ddetrh retorna o determinante d da matriz de funções polinomiais ou racionais h É baseado no algoritmo de Leverrier Ver Também det determ 1610 Name diophant equação de Bezout diofantina xerrdiophantp1p2b Parâmetros p1p2 vetor de polinômios p1p2 p1 p2 b polinômio x vetor de polinômios x1x2 Descrição diophant resolve a equação de Bezout p1x1p2x2b com p1p2 um vetor de polinômios Se a equação não for solúvel de outro modo err0 Exemplos spoly0sp1s32p21s x1sx22s xerrdiophantp1p2p1x1p2x2 p1x1p2x2p1x1p2x2 1611 Name factors fatoração numérica real lnumgfactorspol flag lnumldengfactorsrat flag ratfactorsratflag Parâmetros pol polinômio real rat razão de polinômios reais ratpol1pol2 lnum lista de polinômios de graus 1 ou 2 lden lista de polinômios de graus 1 ou 2 g número real flag string c ou d Descrição Retorna os fatores do polinômio pol na lista lnum e o ganho g Temse pol g vezes o produto das entradas da lista lnum se flag não for fornecido Se flagc for dado então temse poli omega gprodlnumji omega Se flagd for dado então temse polexpi omega gprodlnumiexpi omega Se o argumento de factors for uma razão ratpol1pol2 os fatores do numerador pol1 e do denominador pol2 são retornados nas listas lnum e lden respectivamente O ganho é retornado como g ie temse rat g vezes produto das entradas de lnum produto das entradas de lden Se flag for c respectivamente d as raízes pol serão refletidas em relação em relação ao eixo imaginário respectivamente ao círculo unitário ie os fatores em lnum são polinômios estáveis A mesma coisa se factors for invocado com argumentos racionais as entradas em lnum e lden são polinômios estáveis se flag for dado R2factorsR1c ou R2factorsR1d com R1 uma função racional ou lista syslin SISO então a saída R2 é uma transferência com com numerador e denominador estáveis e com a mesma magnitude de R1 ao longo do eixo imaginário c ou do círculo unitário d Exemplos npoly0225z dpoly01037z Rsyslindnd R1factorsRd rootsR1num factors 1612 rootsR1den wexp2ipi0011 normabshornerR1wabshornerRw Ver Também simp 1613 Name gcd cálculo de máximo divisor comum pgcdUgcdp Parâmetros p vetor linha de polinômios pp1pn ou vetor linha de inteiros tipo igual a 8 Descrição Computa o MDC dos componentes de p e uma matriz unimodular inversa de polinômios U com grau mínimo tais que pU0 0 pgcd Exemplos caso polinomial spoly0s psss122s2s3 pgcdugcdp pu caso inteiro Vint322235 233222345 thegcdUgcdV VU Ver Também bezout lcm hermit 1614 Name hermit forma hermitiana ArUhermitA Parâmetros A matriz de polinômios Ar matriz de polinômios triangular U matriz de polinômios unimodular Descrição Forma hermitiana U é uma matriz unimodular tal que AU está na forma triangular de Hermite A variável de saída é ArAU Aviso versão experimental Exemplos spoly0s ps ss12 2s2s3 ArUhermitpp cleanppU detU Ver Também hrmt htrianr 1615 Name horner avaliação polinomialracional hornerPx Parâmetros P matriz de polinômios ou de razões de polinômios x número real polinômio ou razão de polinômios Descrição Avalia a matriz de polinômios ou de razões de polinômios P Ps quando a variável s do polinômio é substituida por x hornerPxPx Exemplo transformação bilinear admita que P Ps uma matriz de razões de polinômios então a matriz de razões de polinômios P1s1s é obtida por hornerP1s1s Para avaliar uma matriz de razões de polinômios em dadas freqüências use preferivelmente a primitiva freq Exemplos avaliação de um polinômio para um vetor de números Ppoly13x hornerP1 2 5 hornerP1 2 5i avaliação de uma razão spoly0sMs1s hornerM1 hornerMi hornerM1s avaliação de um polinômio para uma matriz de números X 1 23 4 ppoly13xc mhornerp X 1X02X13X2 Ver Também freq repfreq evstr 1616 Name hrmt máximo divisor comum de polinômios pgUhrmtv Parâmetros v vetor linha de polinômios ie matriz de polinômios 1xk pg polinômio U matriz de polinômios unimodular Descrição pgUhrmtv retorna uma matriz unimodular U e pg MDC do vetor linha de polinômios v tais que vU pg0 Exemplos xpoly0x vxx1x2x1x2x13x22x1 pgUhrmtvUcleanU detU Ver Também gcd htrianr Autor S Steer INRIA 1617 Name htrianr triangularização de matrizes de polinômios ArUrkhtrianrA Parâmetros A matriz de polinômios Ar matriz de polinômios U matriz unimodular de polinômios rk inteiro posto normal def A Descrição Triangularização da matriz de polinômios A A is mn m n ArAU Aviso há eliminação de termos pequenos ver código da função Exemplos xpoly0x Mxx22x31x2x4 MuUrkhtrianrM detU MU12 Ver Também hrmt colcompr 1618 Name invr inversão de matrizes de razões de polinômios F invrH Parâmetros H matriz de polinômios ou de razões de polinômios F matriz de polinômios ou de razões de polinômios Descrição Se H é uma matriz de polinômios ou de razões de polinômios invr computa H1 utilizando o algoritmo de Leverrier ver código da função Exemplos spoly0s Hsss21s1s invrH NumdencoffgHNumden H1ss11s2s3sinvrH Ver Também glever coffg inv 1619 Name lcm mínimo múltiplo comum ppfactlcmp Parâmetros p vetor de polinômios fact vetor de polinômios ou inteiros tipo igual a 8 pp polinômio ou inteiro Descrição pplcmp computa o MMC pp do vetor de polinômios p ppfactlcmp computa ainda o vetor fact tal que pfactpponesp Exemplos caso polinomial spoly0s psss12s2s2 ppfactlcmp pfact pp caso inteiro Vint322235 233222345 lcmV Ver Também gcd bezout 1620 Name lcmdiag fatoração diagonal por MMC NDlcmdiagH NDlcmdiagHflag Parâmetros H matriz de razões de polinômios N matriz de polinômios D matriz de polinômios diagonal flag string row ou col padrão Descrição NDlcmdiagHrow computa uma fatoração DHN ie HD1N onde D é uma matriz diagonal com DkkMMC da késima linha de Hden NDlcmdiagH ou NDlcmdiagHcol retorna HND1 com matriz diag onal D e DkkMMC da késima coluna de Hden Exemplos spoly0s H1ss2ss121s2s22s2 NDlcmdiagH NDH Ver Também lcm gcd bezout 1621 Name ldiv divisão longa entre matrizes de polinômios xldivndk Parâmetros nd duas matrizes de polinômios reais k inteiro Descrição xldivndk fornece os k primeiros coeficientes da divisão longa de n por d ie the a expansão de Taylor da matriz de razões de polinômios nijzdijz aproximandose do infinito Os coeficientes de expansão de nijdij são armazenados em xi1nkj k1n Exemplos wssssrand113abcdabcdwss wtfss2tfwss x1ldivnumerwtfdenomwtf5 x2cbcabca2bca3bca4b wssbismarkp2ssx1511 wtfbiscleanss2tfwssbis x3ldivnumerwtfbisdenomwtfbis5 Ver Também arl2 markp2ss pdiv 1622 Name numer numerador numnumerR Parâmetros R matriz de polinômios de razões de polinômios ou de constantes num matriz de polinômios Descrição Função utilitária numnumerR retorna o numerador num de uma matriz de funções racionais R R também pode ser uma matriz de polinômios ou de constantes numerR é equivalente a R2 Rnum ou Rnum Ver Também denom 1623 Name pdiv divisão polinomial RQpdivP1P2 QpdivP1P2 Parâmetros P1 matriz de polinômios P2 polinômio ou matriz de polinômios RQ duas matrizes de polinômios Descrição Divisão euclidiana elemento a elemento da matriz de polinômios P1 pelo polinômio P2 ou pela matriz de polinômios P2 Rij é a matriz de restos Qij é a matriz de quocientes e P1ij QijP2 Qij ou P1ij QijP2ij Qij Exemplos xpoly0x p11x21xp21x rqpdivp1p2 p2qp1 p21x rqpdivp1p2 p2qrp1 Ver Também ldiv gcd 1624 Name pol2des conversão de matrizes de polinômios para formas descritoras NBCpol2desDs Parâmetros Ds matriz de polinômios N B C três matrizes de reais Descrição Dada a matriz de polinômios DsD0 D1 s D2 s2 Dk sk pol2des retorna três matrizes N B C com sendo N nilpotente tais que Ds C sNeye1 B Exemplos spoly0s G1s1s23s3NBCpol2desG G1cleanCinvsNeyeBG2numerG1 Ver Também ss2des tf2des Autor FD 1625 Name pol2str conversão de polinômio para string strpol2strp Parâmetros p polinômio real str string Descrição Converte um polinômio para um string função utilitária Ver Também string pol2tex 1626 Name polfact fatores mínimos fpolfactp Parâmetros p polinômio f vetor f0 f1 fn tal que pprodf f0 constante fi polinômio Descrição fpolfactp retorna os valores mínimos de p ie ff0 f1 fn tal que pprodf Ver Também lcm cmndred factors Autor S Steer INRIA 1627 Name residu resíduo VresiduPQ1Q2 Parâmetros P Q1 Q2 polinômios ou matrizes de polinômios de coeficientes reais ou complexos Descrição VresiduPQ1Q2 retorna a matriz V tal que Vij é a soma dos resíduos da fração racional PijQ1ijQ2ij calculada nos zeros de Q1ij Q1ij e Q2ij não devem possuir raízes em comum Exemplos spoly0s Hss121s2NnumerHDdenomH wresiduNhornerNsDhornerDs Ns Ns Ds Ds sqrtsumw This is H2 norm h2normtf2ssH ps1s1s2s10as5s1sss122 bs3s25s3 residupab5318634410 Exato zpoly0zaz307z205z03bz303z202z01 atildgtildadbtildgtildbd residubbtildzaatild29488038 Exato aa0ibb0i realresidubbtildzaatild29488038 Caso complexo Ver Também pfss bdiag roots poly gtild Autor FDelebecque INRIA 1628 Name roots raízes de polinômios xrootsp xrootspe Parâmetros p polinômio com coeficientes reais ou complexos ou vetor dos coeficientes do polinômio em ordem de graus decrescentes para compatibilidade com o Matlab Descrição xrootsp retorna no vetor de complexos x as raízes do polinômio p Para polinômios reais de grau 100 o algoritmo rápido RPOLY é utilizado Em outros casos as raízes são computadas como os autovalores da matriz companheira associada Use xrootspe para forçar este algoritmo em qualquer caso Exemplos ppoly0101i1ix rootsp Arand33rootspolyAx avaliações por polinômios característicos specA Ver Também poly spec companion Autor Serge Steer INRIA References O algoritmo RPOLY é descrito em Algorithm 493 Zeros of a Real Polynomial ACM TOMS Vol ume 1 edição 2 Junho 1975 pp 178189 Jenkins M A e Traub J F 1970 A ThreeStage Algorithm for Real Polynomials Using Quadratic Iteration SIAM J Numer Anal 71970 545566 Jenkins M A e Traub J F 1970 Principles for Testing Polynomial Zerofinding Programs ACM TOMS 1 1 Março1975 pp 2634 Funções Utilizadas O código fonte de rpolyf pode ser achado no diretório SCImodulespolynomialssrcfortran de uma distribuição fonte do Scilab A computação de autovalores é feita utilizandose os códigos do LA PACK DGEEV e ZGEEV 1629 Name rowcompr compressão de linhas de uma matriz de polinômios XrkAcrowcomprA Parâmetros A matriz de polinômios Y matriz de polinômios quadrada base unimodular esquerda rk posto normal de A Ac AcXA matriz de polinômios Descrição Compressão de linhas da matriz de polinômios A X é uma base polinomial unimodular esquerda que comprime as linhas de A rk é o posto normal de A Aviso há eliminação de termos pequenos utilize com cuidado Ver Também colcompr 1630 Name sfact fatoração espectral em tempo discreto FsfactP Parâmetros P matriz de polinômios reais Descrição Acha F um fator espectral de P P é uma matriz de polinômios tal que cada raiz de P possui uma imagem simétrica em relação ao círculo unitário O problema é singular se uma raiz estiver no círculo unitário sfactP retorna uma matriz de polinômios Fz que é antiestável e tal que P Fz F1z zn Para polinômios escalares um algorimto específico é implementado Os algoritmos são implementados do livro de Kucera Exemplos exemplo polinomial zpoly0z pz122z wsfactp wnumerhornerw1z exemplo matricial F1z12z12z221zzz32zz12z PF1gtildF1d P é simétrica FsfactP rootsdetP rootsdetgtildFd as raízes estáveis rootsdetF as raízes antiestáveis cleanPFgtildFd exemplo de uso de tempo contínuo spoly0s p3s1is1is05s05s1is1iprealp ps polinômio em s2 procura por f estável tal que pfsfs whornerp1s1s transformação bilinear wp1s1s wnnumerw tomando o numerador fnsfactwnfnumerhornerfn1ss1 fator e transformação de volta ffsqrthornerfgtildfc0ffsqrthornerp0 normalização rootsf f é estável cleanfgtildfcp fsfs é ps Ver Também gtild fspecg 1631 Name simp simplificação racional N1D1simpND H1simpH Parâmetros ND polinômios reais ou matrizes de polinômios reais H matriz de razões de polinômios ie matriz com entradas nd n e d polinômios reais Descrição n1d1simpnd calcula dois polinômios n1 e d1 tais que n1d1 nd Se N e D são matrizes de polinômios os cálculos são feitos elemento a elemento H1simpH também é válido cada entrada de H é simplificada em H1 Cuidado Nenhum limiar é dado ie simp não pode forçar uma simplificação Para sistemas lineares dinâmicos que incluem integradores a simplificação modifica o ganho estático H0 para sistemas contínuos H1 para sistemas discretos Para dados complexos simp retorna suas entradas Uma simplificação racional é chamada após aproximadamente cada operação sobre razões de polinômios É possível alternar o modo de simplificação entre on e off ligado e desligado uti lizando a função simpmode Exemplos spoly0s ndsimps1s2s1s2 simpmodeFhnsss simpmodeThnsss Ver Também roots trfmod poly clean simpmode 1632 Name simpmode modifica o modo de simplificação racional modsimpmode simpmodemod Parâmetros mod um booleano Descrição A simplificação racional é chamada após quase cada operação sobre razões de polinômios É possível alternar o modo de simplificação entre on e off ligado e desligado utilizando a função simpmode simpmodt ajusta o modo de simplificação racional para on simpmodf ajusta o modo de simplificação racional para off modsimpmod retorna em mod o modo de simplificação racional corrente Exemplos spoly0s modsimpmode simpmodefhnsss simpmodethnsss simpmodemod Ver Também simp 1633 Name sylm matriz de Sylvester Ssylmab Parâmetros ab duas matrizes de polinômios S matriz Descrição sylmab fornece a matriz de Sylvester associada aos polinômios a e b ie a matriz S tal que coeff ax by S coeffxcoeffy A dimensão de S é igual a degreeadegreeb Se a e b são polinômios primos entre si então ranksylmabdegreeadegreeb e as instruções u sylmab eyenanb1 x polyu1nbzcoeff y polyunb1nanbzcoeff computam os fatores de Bezout x e y de graus mínimos tais que axby 1 1634 Name systmat matriz sistema SmsystmatSl Parâmetros Sl sistema linear lista syslin ou sistema descritor Sm feixe de matrizes Descrição Matriz sistema do sistema linear Sl lista syslin em forma de espaço de estados função utilitária Sm sI A B C D Para um sistema descritor SllistdesABCDE systmat retorna Sm sE A B C D Ver Também ss2des sm2des sm2ss Parte XXVIII Processamento de Sinais 1636 Índice 5 How to 1637 How to design an elliptic filter 1638 Capítulo 5 How to How to 1638 Nome How to design an elliptic filter How to design an elliptic filter analog and digital Description The goal is to design a simple analog and digital elliptic filter Designing an analog elliptic filter There are several possibilities to design an elliptic lowpass filter We can use analpf or zpell We will use zpell to produce the poles and zeros of the filter Once we have got these poles and zeros we will have to translate this representation into a syslin one And then the filter can be represented in bode plot analog elliptic Bessel order 2 cutoff 1 Hz Epsilon 3 ripple of filter in pass band 0epsilon1 A 60 attenuation of filter in stop band A1 OmegaC 10 pass band cutoff frequency in Hertz OmegaR 50 stop band cutoff frequency in Hertz Generate the filter zerospolsgain zpell3601050 Generate the equivalent linear system of the filter num gain realpolyzeross den realpolypolss elatf syslincnumden Plot the resulting filter bodeelatf001100 titleAnalog Elliptic filter Bode plot is only suited for analog filters How to 1639 If you want to design a highpass bandpass or bandstop filter you can first design a lowpass and then transfrom this lowpass filter using the trans function Designing a digital elliptic filter Now lets focus on how to produce a digital lowpass elliptic filter We can produce two kinds of digital filters an IIR Infinite Impulse Response To compute such a filter we can use the following functions iir eqiir a FIR Finite Impulse Response To compute such a filter we can use the following functions How to 1640 eqfir ffilt wfir fsfirlin For our demonstration we will use the iir function Order 2 The order of the filter Fs 1000 The sampling frequency Fcutoff 40 The cutoff frequency We design a low pass elliptic filter hz iirOrderlpellipFcutoffFs2 001 01 We compute the frequency response of the filter frqrepfrepfreqhz0000105 dbrepf phirepf dbphirepf And plot the bode like representation of the digital filter subplot211 plot2dFsfrqdbrepf xtitleObtained Frequency Response Magnitude subplot212 plot2dFsfrqphirepf xtitleObtained Frequency Response Phase in degree Here is the representation of the digital elliptic filter How to 1641 To represent the filter in phase and magnitude we need first to convert the discrete impulse response into magnitude and phase using the dbphi function This convertion is done using a set of normalized frequencies Filtering a signal using the digital filter Designing a filter is a first step Once done this filter will be used to transform a signal To get rid of some noise for example In the following examples we will filter a gaussian noise randnormal Input rand11000 Produce a random gaussian noise t 11000 sl tf2sshz From transfert function to syslin representation y fltsInputsl Filter the signal How to 1642 subplot211 plottInput xtitleThe gaussian noisety subplot212 plotty xtitleThe filtered gaussian noisety Here is the representation of the signal before and after filtering As we can see in the result the high frequencies of the noise have been removed and it remains only the low frequencies The signal is still noisy but it contains mainly low frequencies Filtering a signal using the analog filter To filter a signal using an analog filter we have two strategies transform the analog filter into a discrete one using the dscr function apply the csim function to filter the signal How to 1643 First we try using the dscr flts functions randnormal Input rand11000 Produce a random gaussian noise n 11000 The sample index eldtf dscrelatf1100 Discretization of the linear filter y fltsInputeldtf Filter the signal subplot211 plotnInput xtitleThe gaussian noiseny subplot212 plotny xtitleThe filtered gaussian noiseny Here is the representation of the signal before and after filtering using the dscr flts approach How to 1644 Next we use the csim function randnormal Input rand11000 Produce a random gaussian noise t 11000 t t001 Convert sample index into time steps y csimInputtelatf Filter the signal subplot211 plottInput xtitleThe gaussian noisety subplot212 plotty xtitleThe filtered gaussian noisety Here is the representation of the signal before and after filtering using the csim approach How to 1645 The main difference between the dscr flts approach and the csim approach the dscr flts uses samples whereas the csim functions uses time steps See Also bode iir poly syslin zpell flts tf2ss dscr csim trans analpf 1646 Name Signal Signal manual description Filters analpf analog lowpass filter buttmag squared magnitude response of a Butterworth filter casc creates cascade realization of filter cheb1mag square magnitude response of a type 1 Chebyshev filter cheb2mag square magnitude response of a type 1 Chebyshev filter chepol recursive implementation of Chebychev polynomial convol convolution of 2 discrete series ell1 mag squared magnitude of an elliptic filter eqfir minimax multiband linear phase FIR filter eqiir design of iir filter faurre optimal lqg filter lindquis optimal lqg filter lindquist algorithm ffilt FIR lowpasshighpass bandpass or stopband filter filter compute the filter model findfreq parameter compatibility for elliptic filter design findm for elliptic filter design frmag magnitude of the frequency responses of FIR and IIR filters fsfirlin design of FIR linear phase frequency sampling technique fwiir optimum design of IIR filters in cascade realization Signal 1647 iir designs an iir digital filter using analog filter designs iirgroup group delay of iir filter iirlp Lp IIR filters optimization group calculate the group delay of a digital filter remezb minimax approximation of a frequency domain magnitude response kalm Kalman update and error variance lev resolve the YuleWalker equations levin solve recursively Toeplitz system normal equations srfaur squareroot algorithm for the algebraic Riccati equation srkf squareroot Kalman filter algorithm sskf steadystate Kalman filter system generates the next observation given the old state trans transformation of standardized lowpass filter into lowpass highpass bandpass stopband wfir linearphase windowed FIR lowpass bandpass highpass stopband wiener Wiener estimate forwardbackward Kalman filter formulation wigner timefrequency wigner spectrum of a signal window calculate symmetric window zpbutt Butterworth analog filter zpch1 poles of a type 1 Chebyshev analog filter zpch2 poles and zeros of a type 2 Chebyshev analog filter zpell poles and zeros of prototype lowpass elliptic filter Signal 1648 Spectral estimation corr correlation coefficients cspect spectral estimation using the modified periodogram method czt chirp ztransform algorithm intdec change the sampling rate of a 1D or 2D signal mese calculate the maximum entropy spectral estimate pspect auto and crossspectral estimate wigner WignerVille timefrequency spectral estimation Transforms dft discrete Fourier transform fft fast flourier transform hilb Hilbert transform centred around the origin hank hankel matrix of the covariance sequence of a vector process mfft fft for a multidimensional signal Identification lattnlattp recursive solution of normal equations phc State space realisation by the principal hankel component approximation method rpem identification by the recursive prediction error method Miscellaneous sinc calculate the function sin2pifltpit sincd calculates the function SinNxSinx Signal 1649 k Jacobis complete elliptic integral asn TP the elliptic integral sn Jacobi s elliptic function with parameter m bilt bilinear transform or biquadratic transform jmat permutes block rows or block columns of a matrix 1650 Name analpf create analog lowpass filter hspolszersgainanalpfnfdesignrpomega Parameters n positive integer filter order fdesign string filter design method butt or cheb1 or cheb2 or ellip rp 2vector of error values for cheb1 cheb2 and ellip filters where only rp1 is used for cheb1 case only rp2 is used for cheb2 case and rp1 and rp2 are both used for ellip case 0rp1rp21 for cheb1 filters 1rp1ripple1 in passband for cheb2 filters 0ripplerp2 in stopband for ellip filters 1rp1ripple1 in passband 0ripplerp2 in stopband omega cutoff frequency of lowpass filter in Hertz hs rational polynomial transfer function pols poles of transfer function zers zeros of transfer function gain gain of transfer function Description Creates analog lowpass filter with cutoff frequency at omega hsgainpolyzersspolypolss Examples Evaluate magnitude response of continuoustime system hsanalpf4cheb11 05 fr0115 hffreqhs2hs3ifr hmabshf plotfrhm Authors C B 1652 Name bilt bilinear or biquadratic transform SISO system given by a zeropoles representation nplnzrngn biltplzrgnnumden Parameters pl a vector the poles of the given system zr a vector the zeros of the given system num a polynomial with degree equal to the degree of den the numerator of the transform den a polynomial with degree 1 or 2 the denominator of the transform npl a vector the poles of the transformed system nzr a vector the zeros of the transformed system ngn a scalar the gain of the transformed system Description function for calculating the gain poles and zeros which result from a bilinear transform or from a biquadratic transform Used by the functions iir and trans Examples Hlpiir3lpellip01 008 03 plrootsHlpden zrrootsHlpnum gncoeffHlpnumdegreeHlpnumcoeffHlpdendegreeHlpden zpoly0z a03 numza den1az nplnzrngn biltplzrgnnumden Hlptngnpolynzrzrpolynplzr comparison with horner hornerHlpnumden Authors Carey Bunks bilt 1653 See Also iir trans horner 1654 Name buttmag response of Butterworth filter hbuttmagorderomegacsample Parameters order integer filter order omegac real cutoff frequency in Hertz sample vector of frequency where buttmag is evaluated h Butterworth filter values at sample points Description squared magnitude response of a Butterworth filter omegac cutoff frequency sample sample of frequencies Examples squared magnitude response of Butterworth filter hbuttmag1330011000 mag20loghlog10 plot2d11000mag2011 0180100020 Authors F D 1655 Name casc cascade realization of filter from coefficients celscascxz Parameters x 4xNmatrix where each column is a cascade element the first two column entries being the numerator coefficients and the second two column entries being the denominator coefficients z string representing the cascade variable cels resulting cascade representation Description Creates cascade realization of filter from a matrix of coefficients utility function Examples x123456789101112 celscascxz 1656 Name cepstrum cepstrum calculation fresp cepstrumwmag Parameters w positive real vector of frequencies radsec mag real vector of magnitudes same size as w fresp complex vector Description fresp cepstrumwmag returns a frequency response frespi whose magnitude at fre quency wi equals magi and such that the phase of freq corresponds to a stable and minimum phase system w needs not to be sorted but minimal entry should not be close to zero and all the entries of w should be different Examples w01015mag1abssinw frespcepstrumwmag plot2dwwmagabsfresp See Also frfit 1657 Name cheb1mag response of Chebyshev type 1 filter h2cheb1magnomegacepsilonsample Parameters n integer filter order omegac real cutoff frequency epsilon real ripple in pass band sample vector of frequencies where cheb1mag is evaluated h2 Chebyshev I filter values at sample points Description Square magnitude response of a type 1 Chebyshev filter omegacpassband edge epsilonsuch that 11epsilon2passband ripple samplevector of frequencies where the square magnitude is desired Examples Chebyshev ripple in the passband n13epsilon02omegac3sample000510 hcheb1magnomegacepsilonsample plot2dsampleh xtitlefrequenciesmagnitude See Also buttmag 1658 Name cheb2mag response of type 2 Chebyshev filter h2cheb2magnomegarAsample Parameters n integer filter order omegar real scalar cutoff frequency A attenuation in stop band sample vector of frequencies where cheb2mag is evaluated h2 vector of Chebyshev II filter values at sample points Description Square magnitude response of a type 2 Chebyshev filter omegar stopband edge sample vector of frequencies where the square magnitude h2 is desired Examples Chebyshev ripple in the stopband n10omegar6A102sample0000100510 h2cheb2magnomegarAsample plotsamplelogh2log10frequenciesmagnitude in dB Plotting of frequency edges minvalmaxilogh2log10 plot2domegaromegarminval02000 Computation of the attenuation in dB at the stopband edge attenuationlogAAlog10 plot2dsampleattenuationonessample5000 See Also cheb1mag 1659 Name chepol Chebychev polynomial Tnchepolnvar Parameters n integer polynomial order var string polynomial variable Tn polynomial in the variable var Description Recursive implementation of Chebychev polynomial Tn2poly0varchepoln1varchepoln2var with T01 and T1poly0var Examples chepol4x Authors F D 1660 Name convol convolution yconvolhx ye1convolhxe0 Parameters h a vector first input sequence short one x a vector second input sequence long one e0 a vectorold tail to overlap add not used in first call y a vector the convolution e1 new tail to overlap add not used in last call Description Calculates the convolution y hx of two discrete sequences by using the fft The convolution is defined as follow Overlap add method can be used USE OF OVERLAP ADD METHOD For xx1x2xNm1xN First call is y1e1convolhx1 Subsequent calls ykekconvolhxkekm1 Final call yNconvolhxNeNm1 Finally yy1y2yNm1yN The algorithm based on the convolution definition is implemented for polynomial product yconvolhx is equivalent to ycoeffpolyhzcpolyxzc but much more efficient if x is a long array Examples x13 h110000h201000h300100 x1convolh1xx2convolh2xx3convolh3x convolh1h2h3x p1polyxxcoeff p2polyh1h2h3xcoeff p1p2 See Also corr fft pspect convol 1661 Authors F D C Bunks Date 3 Oct 1988 1662 Name corr correlation covariance covMeancorrxynlags covMeancorrfftxmacroymacronsect wxucorrupdtx1y1w0 wxucorrupdtx2y2wxu wkcorrupdtxkykwxu Parameters x a real vector y a real vector default value x nlags integer number of correlation coefficients desired xmacro a scilab external see below ymacro a scilab external see below default value xmacro n an integer total size of the sequence see below sect size of sections of the sequence see below xi a real vector yi a real vectordefault value xi cov real vector the correlation coefficients Mean real number or vector the mean of x and if given y Description Computes n m 1 covm xk xmean ymk ymean n k 1 corr 1663 for m0nlag1 and two vectors xx1xn yy1yn Note that if x and y sequences are differents corrxy is different with corryx Short sequences covMeancorrxynlags returns the first nlags correlation coefficients and Mean meanx mean of xy if y is an argument The sequence x resp y is assumed real and x and y are of same dimension n Long sequences covMeancorrfftxmacroymacronsect Here xmacro is either a function of type xxxmacrosectistart which returns a vector xx of dimension nsect containing the part of the sequence with indices from istart to istartsect1 a fortran subroutine or C procedure which performs the same calculation See the source code of dgetx for an example n total size of the sequence sect size of sections of the sequence sect must be a power of 2 cov has dimension sect Calculation is performed by FFT Updating method wxucorrupdtx1y1w0 wxucorrupdtx2y2wxu wkcorrupdtxkykwxu With this calling sequence the calculation is updated at each call to corr w0 0ones12nlags nlags power of 2 x1x2 are parts of x such that xx1x2 and sizes of xi a power of 2 To get nlags coefficients a final fft must be performed cfftw1n covc1nlags n is the size of x y Caution this calling sequence assumes that xmean ymean 0 Examples xpi10pi101024pi randseedrandnormal y8sinx8sin2xrandx8sinx8sin199xrandx c for j12for k12cccorrykyj64endend cmatrixc2128cov for j164covcovcj1212jend randunif randnormalxrand1256yx deffzxxinciszxisisinc1 deffzyyinciszyisisinc1 cmxycorrxy32 xxmxy1onesxyymxy2onesy centring c1corrxy32c2corrx32 corr 1664 normc1c21 c3m3corrfftxxyy25632 normc1c31 c4m4corrfftxx25632 normm31normm41 normc3c11normc4c21 x1x1128x2x129256 y1y1128y2y129256 w00ones164 32 coeffs w1xucorrux1y1w0w2corrux2y2w1xu zzrealfftw21256c5zz132 normc5c11 w1xucorrux1w0w2corrux2w1xu zzrealfftw21256c6zz132 normc6c21 randunif test for Fortran or C external deffyxmacrosecistysinististsec1 xxmacro1001 cc1mm1corrx23 ccmmcorrfftxmacro10023 cc2mm2corrfftcorexx10023 maxiabscccc1maxiabsmmmm1maxiabscccc2maxiabsmmmm2 deffyymacrosecistycosististsec1 yymacro1001 cc1mm1corrxy23 ccmmcorrfftxmacroymacro10023 cc2mm2corrfftcorexxcorexy10023 maxiabscccc1maxiabsmmmm1maxiabscccc2maxiabsmmmm2 See Also fft 1665 Name cspect two sided crossspectral estimate between 2 discrete time signals using the correlation method sm cwpcspectnlagsnpointswtypex y wpar sm cwpcspectnlagsnpointswtypenx ny wpar Parameters x vector the data of the first signal y vector the data of the second signal If y is omitted it is supposed to be equal to x autocorrela tion If it is present it must have the same numer of element than x nx a scalar the number of points in the x signal In this case the segments of the x signal are loaded by a user defined function named getx see below ny a scalar the number of points in the y signal In this case the segments of the y signal are loaded by a user defined function named gety see below If present ny must be equal to nx nlags number of correlation lags positive integer npoints number of transform points positive integer wtype The window type re rectangular tr triangular hm Hamming hn Hanning kr Kaiserin this case the wpar argument must be given ch Chebyshev in this case the wpar argument must be given wpar optional parameters for Kaiser and Chebyshev windows kr wpar must be a strictly positive number ch wpar must be a 2 element vector mainlobewidthsidelobeheightwith 0mainlobewidth5 and sidelobeheight0 sm The power spectral estimate in the interval 01 of the normalized frequencies It is a row array of size npoints The array is real in case of autocorrelation and complex in case of cross correlation cspect 1666 cwp the unspecified Chebyshev window parameter in case of Chebyshev windowing or an empty matrix Description Computes the crossspectrum estimate of two signals x and y if both are given and the autospectral estimate of x otherwise Spectral estimate obtained using the correlation method The cross spectrum of two signal x and y is defined to be The correlation method calculates the spectral estimate as the Fourier transform of a modified estimate of the autocross correlation function This autocross correlation modified estimate consist of repeat edly calculating estimates of the autocorrelation function from overlapping subsegments if the data and then averaging these estimates to obtain the result The number of points of the window is 2nlags1 For batch processing the x and y data may be read segment by segment using the getx and gety user defined functions These functions have the following calling sequence xkgetxnsoffset and ykgetynsoffset where ns is the segment size and offset is the index of the first element of the segment in the full signal Warning For Scilab version up to 502 the returned value was the modulus of the current one Reference Oppenheim AV and RW Schafer DiscreteTime Signal Processing Upper Saddle River NJ Pren ticeHall 1999 Examples randnormalrandseed0 xrand11024331 make lowpass filter with eqfir nf33bedge0 1125 5des1 0wate1 1 heqfirnfbedgedeswate filter white data to obtain colored data h1h 0ones1maxisizex1 x1x 0ones1maxisizeh1 hfffth11 xffftx11yfhfxfyrealfftyf1 smcspect100200try smsizemaxisizesmfr1smsizesmsize plotfrlogsm See Also pspect mese corr Authors C Bunks INRIA 1668 Name czt chirp ztransform algorithm czxcztxmwphiatheta Parameters x input data sequence m czt is evaluated at m points in zplane w magnitude multiplier phi phase increment a initial magnitude theta initial phase czx chirp ztransform output Description chirp ztransform algorithm which calcultes the ztransform on a spiral in the zplane at the points aexpjthetawkexpjkphi for k01m1 Examples a7expipi6 ffrbdsxgetech preserve current context rect1212sqrt21212sqrt2 t2pi0179179xsetech00051 plot2dsintcost2012 rect plot2d0 reala0 imaga3000 xsegs100100010010 w093expipi15wexp09logw0zaw zrrealzziimagz plot2dzrzi5000 xsetech050051 plot2dsintcost2012 rect plot2d0 reala0 imaga1000 xsegs100100010010 w0w09393wexp09logw0zaw zrrealzziimagz plot2dzrzi5000 xsetechffrbds restore context Authors C Bunks 1670 Name detrend remove constant linear or piecewise linear trend from a vector y detrendx y detrendxflag y detrendxflagbp Parameters x vector or matrix of real or complex numbers the signal to treat flag a string equal to linear or l for linear or piecewise linear treatment or constant or c for constant treatment bp the breakpoints to provide if you want a piecewise linear treatment y output the signal x with the trend removed from it Description This function removes the constant or linear or piecewise linear trend from a vector x In general this can be useful before a fourier analysis If x is matrix this function removes the trend of each column of x When flag constant or c detrend removes the constant trend simply the mean of the signal and when flag linear or l the function removes the linear trend By adding a third argument bp it is possible to remove a continuous piecewise linear trend Note that the instants of the signal x goes from 0 to m1 m lengthx if x is a vector and m sizex1 in case x is a matrix So the breakpoints bpi must be reals in 0 m1 breakpoints outside are simply removed from bp vector The trend is got by a least square fit of x on the appropriate function space Examples example 1 t linspace016pi1000 x 20 t 03sin05t sint 2sin2t 05sin3t y detrendx clf plot2dtx ystyle2 5 legendbefore detrendafter detrend xgrid example 2 t linspace032pi2000 x abst16pi 03sin05t sint 2sin2t 05sin3t y detrendxlinear1000 clf plot2dtx ystyle2 5 legendbefore detrendafter detrend xgrid detrend 1671 Authors Bruno Pincon 1672 Name dft discrete Fourier transform xfdftxflag Parameters x input vector flag indicates dft flag1 or idft flag1 xf output vector Description Function which computes dft of vector x Examples n8omega exp2piin j0n1Fomegajj Fourier matrix x18xx Fx fftx1 dftx1 invFx fftx1 dftx1 See Also fft Authors C B 1673 Name ell1mag magnitude of elliptic filter vell1magepsm1z Parameters eps passband ripple11eps2 m1 stopband ripple11eps2m1 z sample vector of values in the complex plane v elliptic filter values at sample points Description Function used for squared magnitude of an elliptic filter Usually m1epsepsaa1 Returns vrealoneszoneszepsepsss for ssnzm1 Examples deffalphaBeTaalphabetanmm1 if 2intn2n then BeTaK1 else BeTa0end alphak1m1k1m epsilon01A10 ripple parameters m1epsilonepsilonAA1n5omegac6 mfindfreqepsilonAnomegar omegacsqrtm k1m1kmkm1k1mn Check alphaBetaalphabetanmm1 alphaasn1mnkm1 Check sample000120 Now we map the positive real axis into the contour zalphaasnsampleomegacmBetaonessample plotsampleell1magepsilonm1z See Also buttmag 1674 Name eqfir minimax approximation of FIR filter hneqfirnfbedgedeswate Parameters nf number of output filter points desired bedge Mx2 matrix giving a pair of edges for each band des Mvector giving desired magnitude for each band wate Mvector giving relative weight of error in each band hn output of linearphase FIR filter coefficients Description Minimax approximation of multiband linear phase FIR filter Examples hneqfir330 225 354 50 1 01 1 1 hmfrfrmaghn256 plotfrhm Authors C B 1675 Name eqiir Design of iir filters cellsfactzzeroszpoleseqiirftypeapproxomdeltapdeltas Parameters ftype filter type lphpsbbp approx design approximation buttcheb1cheb2ellip om 4vector of cutoff frequencies in radians omom1om2om3om4 0 om1 om2 om3 om4 pi When ftypelp or hp om3 and om4 are not used and may be set to 0 deltap ripple in the passband 0 deltap 1 deltas ripple in the stopband 0 deltas 1 cells realization of the filter as second order cells fact normalization constant zzeros zeros in the zdomain zpoles poles in the zdomain Description Design of iir filter based on syredi The filter obtained is hzfactproduct of the elements of cells That is hzfactprodcellsnumprodcellsden Examples cellsfactzzeroszpoleseqiirlpellip2pi104pi100020001 hfactpolyzzeroszpolyzpolesz See Also eqfir iir syredi 1676 Name faurre filter computation by simple Faurre algorithm PRTfaurrenHFGR0 Parameters n number of iterations H F G estimated triple from the covariance sequence of y R0 Eykyk P solution of the Riccati equation after n iterations R T gain matrix of the filter Description This function computes iteratively the minimal solution of the algebraic Riccati equation and gives the matrices R and T of the filter model The algorithm tries to compute the solution P as the growing limit of a sequence of matrices Pn such that 1 Pn1FPnFGFPnhR0HPnH GHPnF 1 P0GR0 G Note that this method may not convergeespecially when F has poles near the unit circle Use preferably the srfaur function See Also srfaur lindquist phc Authors G Le V 1677 Name ffilt coefficients of FIR lowpass xffiltftnflfh Parameters ft filter type where ft can take the values lp for lowpass filter hp for highpass filter bp for bandpass filter sb for stopband filter n integer number of filter samples desired fl real low frequency cutoff fh real high frequency cutoff x vector of filter coefficients Description Get n coefficients of a FIR lowpass highpass bandpass or stopband filter For low and highpass filters one cutoff frequency must be specified whose value is given in fl For bandpass and stop band filters two cutoff frequencies must be specified for which the lower value is in fl and the higher value is in fh Authors C B 1678 Name fft fast Fourier transform ifft fast Fourier transform xffta 1 or xffta xffta1 or xiffta xffta1dimincr xffta1dimincr Parameters x real or complex vector Real or complex matrix 2dim fft a real or complex vector matrix or multidimensionnal array dim integer incr integer Description Short syntax direct xffta1 or xffta gives a direct transform single variate If a is a vector a single variate direct FFT is computed that is xksum over m from 1 to n of amexp2ipim1k1n for k varying from 1 to n nsize of vector a the 1 argument refers to the sign of the exponent NOT to inverse multivariate If a is a matrix or or a multidimensionnal array a multivariate direct FFT is performed inverse afftx1 or aifftxperforms the inverse transform normalized by 1n single variate If a is a vector a single variate inverse FFT is computed multivariate If a is a matrix or or a multidimensionnal array a multivariate inverse FFT is performed Long syntax for multidimensional FFT xffta1dimincr allows to perform an multidimensional fft If a is a real or complex vector implicitly indexed by j1j2jp ie aj1j2jp where j1 lies in 1dim1 j2 in 1dim2 one gets a pvariate FFT by calling p times fft as follows fft 1679 incrk1 xa for k1p xfftx 1dimkincrk incrkincrkdimk end where dimk is the dimension of the current variable wrt which one is integrating and incrk is the increment which separates two successive jk elements in a In particularif a is an mxn matrix xffta1 is equivalent to the two instructions a1ffta1m1 and xffta11nm Examples Comparison with explicit formula a123nsizea norm1nexp2ipi0n10n1na ffta1 normexp2ipi0n10n1na ffta1 Frequency components of a signal build a noides signal sampled at 1000hz containing to pure frequencies at 50 and 70 Hz samplerate1000 t 01samplerate06 Nsizet number of samples ssin2pi50tsin2pi70tpi4grand1Nnor01 yffts the fft response is symmetric we retain only the first N2 points fsamplerate0N2N associated frequency vector nsizef clf plot2dfabsy1n See Also corr 1680 Name fft2 twodimension fast Fourier transform yfft2x yfft2xnm Parameters x a vectormatrixarray Real or Complex y a vectormatrixarray Real or Complex m integer number of rows n integer number of columns Description This functions performs the twodimension discrete Fourier transform yfft2xy and x have the same size yfft2xmn If m respectively n is less than the rows number respectively columns of x then the x rows number resp columns is truncated else if m resp n is more than the rows number resp columns of x then x rows are completed by zero resp columns if x is a matrix then y is a matrix if x is a hypermatrix then y is a hypermatrix with the size of the first dimension of y is equal to m the size of the second dimension of y is equal to n the size of the ith dimension of y for i2 case hypermatrix equal to the size of the ith dimension of x ie sizey1m sizey2n and sizeyisizexi for i2 Examples Comparison with explicit formula a1 2 3 4 5 6 7 8 9 10 11 12 msizea1 nsizea2 fourier transform along the rows for i1n a1iexp2ipi0m10m1mai end fourier transform along the columns for j1m a2tempexp2ipi0n10n1na1j a2ja2temp end norma2fft2a See Also 1682 Name fftshift rearranges the fft output moving the zero frequency to the center of the spectrum yfftshiftx job Parameters x real or complex vector or matrix y real or complex vector or matrix job integer dimension selection or string all Description if x results of an fft computation y fftshiftx or y fftshiftxall moves the zero frequency component to the center of the spectrum which is sometimes a more convenient form If x is a vector of size n y is the vector xn21n1n2 If x is an m by n matrix y is the matrix xm21n1m2n21n1n2 x11 x12 x22 x21 x gives y x21 x22 x12 x11 y fftshiftxn make the swap only along the nth dimension Examples make a signal t0011000 x3sint8sin3t05sin5t3randt compute the fft yfftx1 display clf subplot211plot2dabsy subplot212plot2dfftshiftabsy make a 2D image t00130 x3sintcos2t8sin3tsin5t 05sin5tsin5t3randtrandt compute the fft yfftx1 display clf xsetcolormaphotcolormap256 fftshift 1683 subplot211Matplotabsy subplot212Matplotfftshiftabsy See Also fft 1684 Name filtsinc samples of sinc function xfiltsincnfl Parameters n number of samples fl cutoff frequency of the associated lowpass filter in Hertz x samples of the sinc function Description Calculate n samples of the function sin2pifltpit for tn12n12 ie centred around the origin Examples plotfiltsinc10001 See Also sincd Authors C B 1685 Name filter filters a data sequence using a digital filter yzf filternumdenx zi Parameters num real vector the coefficients of the filter numerator in decreasing power order or a polynomial den real vector the coefficients of the filter denominator in decreasing power order or a polynomial x real row vector the input signal zi real row vector of length maxlengthalengthb1 the initial condition relative to a direct form II transposed state space representation The default value is a vector filled with zeros y real row vector the filtered signal zf real row vector the final state It can be used to filter a next batch of the input signal Description This function filters a data sequence using a digital filter using a direct form II transposed imple mentation References Oppenheim A V and RW Schafer DiscreteTime Signal Processing Englewood Cliffs NJ Pren ticeHall 1989 pp 311312 See Also flts rtitr ltitr Authors Serge Steer INRIA 1686 Name findfreq parameter compatibility for elliptic filter design mfindfreqepsilonAn Parameters epsilon passband ripple A stopband attenuation n filter order m frequency needed for construction of elliptic filter Description Search for m such that nK1m1KmKm1K1m with m1epsilonepsilonAA1 If m omegar2omegac2 the parameters epsilonAomegacomegar and n are then compatible for defining a prototype elliptic filter Here Kkm is the complete elliptic integral with parameter m See Also k Authors F D 1687 Name findm for elliptic filter design mfindmchi Description Search for m such that chi k1mkm For use with findfreq See Also k Authors F D 1688 Name frfit frequency response fit sysfrfitwfresporder numdenfrfitwfresporder sysfrfitwfresporderweight numdenfrfitwfresporderweight Parameters w positive real vector of frequencies Hz fresp complex vector of frequency responses same size as w order integer required order degree of den weight positive real vector default value onesw numden stable polynomials Description sysfrfitwfresporderweight returns a bistable transfer function Gssysnumden of of given order such that its frequency response Gwi matches frespi ie freqnumdeniw should be close to fresp weighti is the weight given to wi Examples w0010012spoly0s Gsyslinc2s201s2 s2s1s203s1 fresprepfreqGw Gidfrfitwfresp4 frespfitrepfreqGidw bodewfrespfrespfit See Also frep2tf factors cepstrum mrfit freq calfrq 1689 Name frmag magnitude of FIR and IIR filters xmfrfrmagsysnpts xmfrfrmagnumdennpts Parameters sys a single input single output discrete transfer function or a polynomial or the vector of polynomial coefficients the filter num a polynomial or the vector of polynomial coefficients the numerator of the filter den a polynomial or the vector of polynomial coefficients the denominator of the filter the default value is 1 npts integer the number of points in frequency response xm vector of magnitude of frequency response at the points fr fr points in the normalized frequency domain where magnitude is evaluated Description calculates the magnitude of the frequency responses of FIR and IIR filters The filter description can be one or two vectors of coefficients one or two polynomials or a single output discrete transfer function the frequency discretisation is given by frlinspace012npts Authors Carey Bunks Examples hziir3bpcheb115 2508 03 hzmfrfrmaghz256 plotfrhzm hziir3bpellip15 2508 03 hzmfrfrmaghz256 plotfrhzmr See Also iir eqfir repfreq calfrq phasemag 1690 Name fsfirlin design of FIR linear phase filters frequency sampling technique hstfsfirlinhdflag Parameters hd vector of desired frequency response samples flag is equal to 1 or 2 according to the choice of type 1 or type 2 design hst vector giving the approximated continuous response on a dense grid of frequencies Description function for the design of FIR linear phase filters using the frequency sampling technique Examples Example of how to use the fsfirlin macro for the design of an FIR filter by a frequency sampling technique Two filters are designed the first response hst1 with abrupt transitions from 0 to 1 between passbands and stop bands the second response hst2 with one sample in each transition band amplitude 05 for smoothing hdzeros115 ones110 zeros139desired samples hst1fsfirlinhd1filter with no sample in the transition hd155hd265samples in the transition bands hst2fsfirlinhd1corresponding filter pas1prodsizehst15 fg0pas5normalized frequencies grid plot2d1 1fg1257hst1 hst2 2nd example hd0ones115 ones110 0ones139desired samples hst1fsfirlinhd1filter with no sample in the transition hd155hd265samples in the transition bands hst2fsfirlinhd1corresponding filter pas1prodsizehst15 fg0pas5normalized frequencies grid nprodsizehst1 plotfg1nhst1 plot2dfg1nhst23000 See Also ffilt wfir G Le Vey 1692 Name group group delay for digital filter tgfrgroupnptsa1ia2ib1ib2i Parameters npts integer number of points desired in calculation of group delay a1i in coefficient polynomial rational polynomial or cascade polynomial form this variable is the transfer function of the filter In coefficient polynomial form this is a vector of coefficients see below a2i in coeff poly form this is a vector of coeffs b1i in coeff poly form this is a vector of coeffs b2i in coeff poly form this is a vector of coeffs tg values of group delay evaluated on the grid fr fr grid of frequency values where group delay is evaluated Description Calculate the group delay of a digital filter with transfer function hz The filter specification can be in coefficient form polynomial form rational polynomial form cascade polynomial form or in coefficient polynomial form In the coefficient polynomial form the transfer function is formulated by the following expression hzproda1ia2izz2prodb1ib2izz2 Examples zpoly0z hzz5 tgfrgroup100h plotfrtg Authors C B 1693 Name hank covariance to hankel matrix hkhankmncov Parameters m number of blocrows n number of bloccolumns cov sequence of covariances it must be given as R0 R1 R2Rk hk computed hankel matrix Description this function builds the hankel matrix of size mdnd from the covariance sequence of a vector process Examples Example of how to use the hank macro for building a Hankel matrix from multidimensional data covariance or Markov parameters eg This is used eg in the solution of normal equations by classical identification methods Instrumental Variables eg 1lets generate the multidimensional data under the form Cc0 c1 c2 cn where each bloc ck is a ddimensional matrix eg the kth correlation of a ddimensional stochastic process Xt ck EXt Xtk being the transposition in scilab we take here d2 and n64 crand2264 generate the hankel matrix H with 4 blocrows and 5 bloccolumns from the data in c Hhank45c See Also toeplitz Authors G Le Vey 1694 Name hilb FIR approximation to a Hilbert transform filter xhhilbn wtype par Parameters n odd integer number of points in filter wtype string window type retrhnhmkrch default re par window parameter for wtypekr or ch default par0 0 see the function window for more help xh Hilbert transform Description Returns the first n points of an FIR approximation to a Hilbert transform filter centred around the origin The FIR filter is designed by appropraitely windowing the ideal impulse response hn2 npisinnpi22 for n not equal 0 and h00 An approximation to an analytic signal generator can be built by designing an FIR Finite Impulse Re sponse filter approximation to the Hilbert transform operator The analytic signal can then be comput ed by adding the appropriately timeshifted real signal to the imaginary part generated by the Hilbert filter References httpieeexploreieeeorgiel478782300330385pdf tparnumber330385isnumber7823 A Reilly G Frazer and B Boashash Analytic signal generation Tips and traps IEEE Trans Signal Processing vol 42 pp32413245 Nov 1994 See Also window hilbert Examples plothilb51 Authors C B 1695 Name hilbert Discretetime analytic signal computation of a real signal using Hilbert transform xhilbertxr Parameters xr real vector the real signal samples x Complex vector the discretetime analytic signal Description Returns theanalytic signal from a real data sequence The analytic signal x xr ixi has a real part xr which is the original data and an imaginary part xi which contains the Hilbert transform The imaginary part is a version of the original real sequence with a 90 phase shift References httpieeexploreieeeorgiel5781697500782222pdf arnumber782222 Marple SL Computing the discretetime analytic signal via FFT IEEE Transactions on Signal Processing Vol 47 No9 September 1999 pp26002603 See Also window hil Examples compare the discretetime analytic signal imaginary part of the impulse real signal with the FIR approximation of the Hilbert transform filter m25 n2m1 yhilberteyen1 hhilbn hhm1h1m plotimagy h Authors C B 1696 Name iir iir digital filter hziirnftypefdesignfrqdelta Parameters n positive number witn inteher value the filter order ftype string specifying the filter type the possible values are lp for lowpasshp for high passbp for band pass and sb for stop band fdesign string specifying the analog filter design the possible values are butt cheb1 cheb2 and ellip frq 2vector of discrete cutoff frequencies ie 0frq5 For lp and hp filters only frq1 is used For bp and sb filters frq1 is the lower cutoff frequency and frq2 is the upper cutoff frequency delta 2vector of error values for cheb1 cheb2 and ellip filters where only delta1 is used for cheb1 case only delta2 is used for cheb2 case and delta1 and delta2 are both used for ellip case 0delta1delta21 for cheb1 filters 1delta1ripple1 in passband for cheb2 filters 0rippledelta2 in stopband for ellip filters 1delta1ripple1 in passband and 0rippledelta2 in stopband Description function which designs an iir digital filter using analog filter designs and bilinear transformation Examples hziir3bpellip15 2508 03 hzmfrfrmaghz256 plot2dfrhzm xtitleDiscrete IIR filter band pass 015ltfrlt025 qpoly0q to express the result in terms of the delay operator qz1 hzdhornerhz1q See Also eqfir eqiir analpf bilt Authors Carey Bunks 1697 Name iirgroup group delay Lp IIR filter optimization ltgradiirgroupprthetaomegawttd coutgradindiirlpxindpflaglambdaomegaadwatdwt Parameters r vector of the module of the poles and the zeros of the filters theta vector of the argument of the poles and the zeros of the filters omega frequencies where the filter specifications are given wt weighting function for and the group delay td desired group delay lt grad criterium and gradient values Description optimization of IIR filters for the Lp criterium for the the group delay Rabiner Gold pp270273 1698 Name iirlp Lp IIR filter optimization costgradindiirlpxindpflaglambdaomegaadwatdwt Parameters x 1X2 vector of the module and argument of the poles and the zeros of the filters flag string a for amplitude gd for group delay default case for amplitude and group delay omega frequencies where the filter specifications are given wawt weighting functions for the amplitude and the group delay lambda weighting with 1lambda of the costs a and gd for getting the global cost ad td desired amplitude and group delay cost grad criterium and gradient values Description optimization of IIR filters for the Lp criterium for the amplitude andor the group delay Rabiner Gold pp270273 1699 Name intdec Changes sampling rate of a signal yintdecxlom Parameters x input sampled signal lom For a 1D signal this is a scalar which gives the rate change For a 2D signal this is a 2Vector of sampling rate changes lomcol rate changerow rate change y Output sampled signal Description Changes the sampling rate of a 1D or 2D signal by the rates in lom Authors C B 1700 Name jmat row or column block permutation jjmatnm Parameters n number of block rows or block columns of the matrix m size of the square blocks Description This function permutes block rows or block columns of a matrix 1701 Name kalm Kalman update x1p1xpkalmyx0p0fghqr Parameters fgh current system matrices q r covariance matrices of dynamics and observation noise x0p0 state estimate and error variance at t0 based on data up to t1 y current observation Output from the function is x1p1 updated estimate and error covariance at t1 based on data up to t0 x updated estimate and error covariance at t0 based on data up to t0 Description function which gives the Kalman update and error variance Authors C B 1702 Name lattn recursive solution of normal equations lalblattnnpcov Parameters n maximum order of the filter p fixed dimension of the MA part If p 1 the algorithm reduces to the classical Levinson re cursions cov matrix containing the Rks dd matrices for a ddimensional processIt must be given the fol lowing way la listtype variable giving the successively calculated polynomials degree 1 to degree nwith co efficients Ak Description solves recursively on n p being fixed the following system normal equations ie identifies the AR part poles of a vector ARMAnp process where Rkk1nlag is the sequence of empirical covariances Authors G Le V 1703 Name lattp lattp lalblattpnpcov Description see lattn Authors GLevey 1704 Name lev YuleWalker equations Levinsons algorithm arsigma2rclevr Parameters r correlation coefficients ar autoRegressive model parameters sigma2 scale constant rc reflection coefficients Description resolve the YuleWalker equations using Levinsons algorithm Authors C B 1705 Name levin Toeplitz system solver by Levinson algorithm multidimensional lasiglevinncov Parameters n A scalar with integer value the maximum order of the filter cov A nlagd x d matrix It contains the Rk d x d matrices for a ddimensional process stored in the following way la A list the successively calculated Levinson polynomials degree 1 to n with coefficients Ak sig A list the successive meansquare errors Description function which solves recursively on n the following Toeplitz system normal equations where Rkk1nlag is the sequence of nlag empirical covariances Examples We use the levin macro for solving the normal equations on two examples a onedimensional and a twodimensional process We need the covariance sequence of the stochastic process This example may usefully be compared with the results from levin 1706 the phc macro see the corresponding help and example in it 1 A onedimensional process We generate the process defined by two sinusoids 1Hz and 2 Hz in additive Gaussian noise this is the observed process the simulated process is sampled at 10 Hz step 01 in t underafter t101100randnormal y1sin2pit1sin2pi2t1y1y1randy1plott1y1 covariance of y1 nlag128 c1corry1nlag c1c1c1 needs to be given columnwise see the section PARAMETERS of this help compute the filter for a maximum order of n10 la is a listtype variable each element of which containing the filters of order ranging from 1 to n try varying n in the ddimensional case this is a matrix polynomial square d X d sig gives the same way the meansquare error n15 la1sig1levinnc1 verify that the roots of la contain the frequency spectrum of the observed process y remember that y is sampled in our example at 10Hz T01s so that we need to retrieve the original frequencies 1Hz and 2 Hz through the log and correct scaling by the frequency sampling we verify this for each filter order for i1n s1rootsla1is1logs12pi1 now we get the estimated poles sorted positive ones only s1gsortimags1s1s11i2end the last two frequencies are the ones really present in the observed process the others are artifacts coming from the used model size This is related to the rather difficult problem of order estimation 2 A 2dimensional process 4 frequencies 1 2 3 and 4 Hz sampled at 01 Hz y1 y1sin2Pitsin2Pi2tGaussian noise y with y2 y2sin2Pi3tsin2Pi4tGaussian noise d2dt01 nlag64 t202pidt100 y2sint2sin2t2randt2sin3t2sin4t2randt2 c2 levin 1707 for j12 for k12 c2c2corry2ky2jnlagendend c2matrixc22128cov for j164covcovc2j1d1jdendcovar columnwise c2cov in the multidimensional case we have to compute the roots of the determinant of the matrix polynomial easy in the 2dimensional case but tricky if d3 We just do that here for the maximum desired filter order n mp is the matrix polynomial of degree n la2sig2levinnc2 mpla2ndeterminantmp11mp22mp12mp21 s2rootsdeterminants2logs22pi01same trick as above for 1D process s2gsortimags2s2s21dn2just the positive ones There the order estimation problem is seen to be much more difficult many artifacts The 4 frequencies are in the estimated spectrum but beneath many non relevant others See Also phc Authors G Le Vey 1708 Name lindquist Lindquists algorithm PRTlindquistnHFGR0 Parameters n number of iterations H F G estimated triple from the covariance sequence of y R0 Eykyk P solution of the Riccati equation after n iterations R T gain matrices of the filter Description computes iteratively the minimal solution of the algebraic Riccati equation and gives the matrices R and T of the filter model by the Lindquists algorithm See Also srfaur faurre phc Authors G Le V 1709 Name mese maximum entropy spectral estimation smfrmesex npts Parameters x Input sampled data sequence npts Optional parameter giving number of points of fr and sm default is 256 sm Samples of spectral estimate on the frequency grid fr fr npts equally spaced frequency samples in 05 Description Calculate the maximum entropy spectral estimate of x Authors C B 1710 Name mfft multidimensional fft xkmfftxflagdim Parameters x xijk input signal in the form of a row vector whose values are arranged so that the i index runs the quickest followed by the j index etc flag 1 FFT or 1 inverse FFT dim dimension vector which gives the number of values of x for each of its indices xk output of multidimensional fft in same format as for x Description FFT for a multidimensional signal For example for a three dimensional vector which has three points along its first dimension two points along its second dimension and three points along its third dimension the row vector is arranged as follows xx111x211x311 x121x221x321 x112x212x312 x122x222x322 x113x213x313 x123x223x323 and the dim vector is dim323 Authors C B 1711 Name mrfit frequency response fit sysmrfitwmagorder numdenmrfitwmagorder sysmrfitwmagorderweight numdenmrfitwmagorderweight Parameters w positive real vector of frequencies Hz mag real vector of frequency responses magnitude same size as w order integer required order degree of den weight positive real vector default value onesw numden stable polynomials Description sysmrfitwmagorderweight returns a bistable transfer function Gssysnum den of of given order such that its frequency response magnitude absGwi matches magi ie absfreqnumdeniw should be close to mag weighti is the weigth given to wi Examples w0010012spoly0s Gsyslinc2s201s2s2s1s203s1 syslincNumDen fresprepfreqGw magabsfresp Gidmrfitwmag4 frespfitrepfreqGidw plot2dwwmagabsfrespfit See Also cepstrum frfit freq calfrq 1712 Name asn elliptic integral yasnxm Parameters x upper limit of integral x0 can be a vector m parameter of integral 0m1 y value of the integral Description Calculates the elliptic integral If x is a vector y is a vector of same dimension as x Examples m08zasn1sqrtmmKrealzKtildeimagz x2max1sqrtm x100051x21x2max120x2maxx3x2max00510 xx1x2x3 yasnxm rect0Ktilde11K2Ktilde plot2drealyimagy1011 rect deffyfty1sqrt1t21mt2 intg009fasn09m Works for real case only Authors F D 1713 Name k Jacobis complete elliptic integral Kkm Parameters m parameter of the elliptic integral 0m1 m can be a vector K value of the elliptic integral from 0 to 1 on the real axis Description Calculates Jacobis complete elliptic integral of the first kind References Abramowitz and Stegun page 598 Examples m04 asn1m km See Also asn Authors FD 1714 Name sn Jacobi s elliptic function ysnxm Parameters x a point inside the fundamental rectangle defined by the elliptic integral x is a vector of complex numbers m parameter of the elliptic integral 0m1 y result Description Jacobi s sn elliptic function with parameter m the inverse of the elliptic integral for the parameter m The amplitude am is computed in fortran and the addition formulas for elliptic functions are applied Examples m036 Kkm P4K Real period realval0P50P plotrealvalrealsnrealvalm clf KKk1m Ip2KK imaval10Ip50KK0001 imaval2KK005Ip25IpKK z1sniimaval1mz2sniimaval2m plot2dimaval1imaval2imagz1imagz2 xgrid3 See Also asn k Authors F D 1715 Name phc Markovian representation HFGphchkdr Parameters hk hankel matrix d dimension of the observation r desired dimension of the state vector for the approximated model H F G relevant matrices of the Markovian model Description Function which computes the matrices H F G of a Markovian representation by the principal hankel component approximation method from the hankel matrix built from the covariance sequence of a stochastic process Examples This example may usefully be compared with the results from the levin macro see the corresponding help and example We consider the process defined by two sinusoids 1Hz and 2 Hz in additive Gaussian noise this is the observation the simulated process is sampled at 10 Hz t01100randnormal ysin2pitsin2pi2tyyrandyplotty covariance of y nlag128 ccorrynlag hankel matrix from the covariance sequence we can choose to take more information from covariance by taking greater n and m try it to compare the results n20m20 hhanknmc compute the Markov representation mhmfmg We just take here a state dimension equal to 4 this is the rather difficult problem of estimating the order Try varying ns the observation dimension is here equal to one phc 1716 ns4 mhmfmgphch1ns verify that the spectrum of mf contains the frequency spectrum of the observed process y remember that y is sampled in our example at 10Hz T01s so that we need to retrieve the original frequencies through the log and correct scaling by the frequency sampling sspecmfslogs ss2pi1 now we get the estimated spectrum imags See Also levin 1717 Name pspect two sided crossspectral estimate between 2 discrete time signals using the Welchs average periodogram method sm cwppspectsecstepseclengwtypex y wpar sm cwppspectsecstepseclengwtypenx ny wpar Parameters x vector the timedomain samples of the first signal y vector the timedomain samples of the second signal If y is omitted it is supposed to be equal to x autocorrelation If it is present it must have the same numer of element than x nx a scalar the number of samples in the x signal In this case the segments of the x signal are loaded by a user defined function named getx see below ny a scalar the number of samples in the y signal In this case the segments of the y signal are loaded by a user defined function named gety see below If present ny must be equal to nx secstep offset of each data window The overlap D is given by secleng secstep if secstepsecleng2 50 overlap is made The overlap secleng Number of points of the window wtype The window type re rectangular tr triangular hm Hamming hn Hanning kr Kaiserin this case the wpar argument must be given ch Chebyshev in this case the wpar argument must be given wpar optional parameters for Kaiser and Chebyshev windows kr wpar must be a strictly positive number ch wpar must be a 2 element vector mainlobewidthsidelobeheightwith 0mainlobewidth5 and sidelobeheight0 sm Two sided power spectral estimate in the interval 01 of the normalized frequencies It is a row array with seclen elements The array is real in case of autocorrelation and complex in case of crosscorrelation pspect 1718 The associated normalized frequencies array is linspace01seclen cwp unspecified Chebyshev window parameter in case of Chebyshev windowing or an empty matrix Description Computes the crossspectrum estimate of two signals x and y if both are given and the autospectral estimate of x otherwise Spectral estimate obtained using the modified periodogram method The cross spectrum of two signal x and y is defined to be The modified periodogram method of spectral estimation repeatedly calculates the periodogram of windowed subsections of the data containes in x and y These periodograms are then averaged to gether and normalized by an appropriate constant to obtain the final spectral estimate It is the aver aging process which reduces the variance in the estimate For batch processing the x and y data may be read segment by segment using the getx and gety user defined functions These functions have the following calling sequence xkgetxnsoffset and ykgetynsoffset where ns is the segment size and offset is the index of the first element of the segment in the full signal Reference Oppenheim AV and RW Schafer DiscreteTime Signal Processing Upper Saddle River NJ Pren ticeHall 1999 Examples randnormalrandseed0 xrand11024331 make lowpass filter with eqfir nf33bedge0 1125 5des1 0wate1 1 heqfirnfbedgedeswate filter white data to obtain colored data h1h 0ones1maxisizex1 x1x 0ones1maxisizeh1 hfffth11 xffftx11yrealffthfxf1 plot magnitude of filter h2h 0ones1968hf2ffth21hf2realhf2conjhf2 hsizemaxisizehf2fr1hsizehsizeplotfrloghf2 pspect example smpspect100200trysmsizemaxisizesmfr1smsizesmsize plotfrlogsm randunif See Also cspect pspect mese window C Bunks INRIA 1720 Name remez Remez exchange algorithm for the weighted chebyshev approximation of a continuous func tion with a sum of cosines anremezguessmagfgridweight Parameters guess real array of size n2 the initial guess fgrid real array of size ng the grid of normalized frequency points in 05 mag real array of size ng the desired magnitude on grid fg weight real array of size ng weighting function on error on grid fg an real array of size n cosine coefficients Description Minimax approximation of a frequency domain magnitude response The approximation takes the form h sumaicosweight i1n An FIR linearphase filter can be obtained from the the output of remez by using the following commands hn1nc1annc122 hnncan1 hnnc12nc1an2nc2 This function is mainly intended to be called by the remezb function Bibliography EW Cheney Introduction to Approximation Theory McGrawHill 1966 httpenwikipediaorgwikiRemezalgorithm References This function is based on the fortran code remezf written by James H Mcclellan department of electrical engineering and computer science Massachusetts In stitute of Technology Cambridge Massachussets 02139 Thomas W Parks department of electrical engineering Rice university Houston Texas 77001 remez 1721 Thomas W Parks department of electrical engineering Rice university Houston Texas 77001 Examples nc21 ngridnc250 fgrid50ngrid1ngrid1 mag1ngrid2ones1ngrid2 magngrid21ngrid0ones1ngrid2 weightonesfgrid guessround1ngridncngrid guessnc1ngrid guessnc2ngrid anremezguessmagfgridweight See Also remezb eqfir 1722 Name remezb Minimax approximation of magnitude response anremezbncfgdswt Parameters nc Number of cosine functions fg Grid of frequency points in 05 ds Desired magnitude on grid fg wt Weighting function on error on grid fg an Cosine filter coefficients Description Minimax approximation of a frequency domain magnitude response The approximation takes the form h sumancoswn for n01nc An FIR linearphase filter can be obtained from the the output of the function by using the following commands hn1nc1annc122 hnncan1 hnnc12nc1an2nc2 Examples Choose the number of cosine functions and create a dense grid in 024 and 265 nc21ngridnc16 fg240ngrid21ngrid21 fgngrid21ngridfg1ngrid226ones1ngrid2 Specify a low pass filter magnitude for the desired response ds1ngrid2ones1ngrid2 dsngrid21ngridzeros1ngrid2 Specify a uniform weighting function wtonesfg Run remezb anremezbncfgdswt Make a linear phase FIR filter hn1nc1annc122 hnncan1 remezb 1723 hnnc12nc1an2nc2 Plot the filters magnitude response plot50255256frmaghn256 Choose the number of cosine functions and create a dense grid in 05 nc21 ngridnc16 fg50ngrid1ngrid Specify a triangular shaped magnitude for the desired response ds1ngrid20ngrid21ngrid21 dsngrid21ngriddsngrid211 Specify a uniform weighting function wtonesfg Run remezb anremezbncfgdswt Make a linear phase FIR filter hn1nc1annc122 hnncan1 hnnc12nc1an2nc2 Plot the filters magnitude response plot50255256frmaghn256 See Also eqfir Authors C B 1724 Name rpem Recursive PredictionError Minimization estimation w1vrpemw0u0y0lambdakc Arguments w0 listthetaplphipsi where theta abc is a real vector of order 3n abc aa1an bb1bn cc1cn p 3n x 3n real matrix phipsil real vector of dimension 3n Applicable values for the first call thetaphipsil0ones13n peye3n3n u0 real vector of inputs arbitrary size u0 is not used by rpem y0 vector of outputs same dimension as u0 y01 is not used by rpem If the time domain is t0t0k1 the u0 vector contains the inputs ut0ut01ut0k1 and y0 the outputs yt0yt01yt0k1 Optional arguments lambda optional argument forgetting constant choosed close to 1 as convergence occur lambdalambda0alfabeta evolves according to lambdatalfalambdat1beta with lambda0lambda0 k contraction factor to be chosen close to 1 as convergence occurs kk0munu evolves according to rpem 1725 ktmukt1nu with k0k0 c Large argumentc1000 is the default value Outputs w1 Update for w0 v sum of squared prediction errors on u0 y0optional In particular w11 is the new estimate of theta If a new sample u1 y1 is available the update is obtained by w2vrpemw1u1y1lambdakc Arbitrary large series can thus be treated Description Recursive estimation of arguments in an ARMAX model Uses LjungSoderstrom recursive prediction error method Model considered is the following yta1yt1anytn b1ut1bnutnetc1et1cnetn The effect of this command is to update the estimation of unknown argument thetaabc with aa1an bb1bn cc1cn 1726 Name sincd digital sinc function or Direchlet kernel ssincdnflag Parameters n integer flag if flag 1 the function is centred around the origin if flag 2 the function is delayed by pi2n s vector of values of the function on a dense grid of frequencies Description function which calculates the function SinNxNSinx Examples plotsincd101 Authors G Le V 1727 Name srfaur squareroot algorithm pstlrtttsrfaurhfgr0npstl Parameters h f g convenient matrices of the statespace model r0 Eykyk n number of iterations p estimate of the solution after n iterations s t l intermediate matrices for successive iterations rt tt gain matrices of the filter model after n iterations p s t l may be given as input if more than one recursion is desired evaluation of intermediate values of p Description squareroot algorithm for the algebraic Riccati equation Examples GENERATE SIGNAL xpi10pi101024pi randseed0randnormal y11sinxsin2xsin19xrand21024 COMPUTE CORRELATIONS cfor j12for k12cccorrykyj64endend cmatrixc2128 FINDING HFG with 6 states hkhank2020c HFGphchk26 SOLVING RICCATI EQN r0c1212 PstlRtTtsrfaurHFGr0200 Make covariance matrix exactly symmetric RtRtRt2 srfaur 1728 See Also phc faurre lindquist 1729 Name srkf square root Kalman filter x1p1srkfyx0p0fhqr Parameters f h current system matrices q r covariance matrices of dynamics and observation noise x0 p0 state estimate and error variance at t0 based on data up to t1 y current observation Output from the function is x1 p1 updated estimate and error covariance at t1 based on data up to t0 Description square root Kalman filter algorithm Authors C B 1730 Name sskf steadystate Kalman filter xepesskfyfhqrx0 Parameters y data in form y0y1yn yk a column vector f system matrix dimNxN h observations matrix dimMxN q dynamics noise matrix dimNxN r observations noise matrix dimMxM x0 initial state estimate xe estimated state pe steadystate error covariance Description steadystate Kalman filter Authors C B 1731 Name syredi Design of iir filters syredi code interface factb2b1b0c1c0zzeroszpolessyrediitypiaproomdeltapdeltas Parameters itype integer the filter type 1 stands for lowpass 2 for highpass 3 for bandpass 4 for stopband iappro integer the design approximation type 1 stands for butterworth 2 for elliptic 3 for Chebytchev1 4 for Chebytchev2 om 4vector of cutoff frequencies in radians omom1om2om3om4 0 om1 om2 om3 om4 pi When ftypelp or hp om3 and om4 are not used and may be set to 0 deltap a real scalar the ripple in the passband 0 deltap 1 deltas a real scalar the ripple in the stopband 0 deltas 1 gain scalar the filter gain b2 real row vector degree 2 coefficients of numerators b1 real row vector degree 1 coefficients of numerators b0 real row vector degree 0 coefficients of numerators c1 real row vector degree 1 coefficients of denominators c0 real row vector degree 0 coefficients of denominators zzeros complex row vector filter zeros in the zdomain zpoles complex row vector filter poles in the zdomain Description Computes iir filter approximation The result is given as a set of second order transfer functions Hib0ib1izb2iz2c0ic1izz2 and also as a poles zeros gain representation The filter obtained is hfactH1Hn syredi 1732 Remark This builtin function is mainly intended to be used by the eqiir function References The syredi code is derived from doredi package written by Guenter F Dehner Institut fuer Nachrich tentechnik Universitaet ErlangenNuernberg Germany DehnerGF 1979 DOREDI Program for Design and Optimization of REcursive DIgital filtersPro grams for Digital Signal Processing edDigital Signal Processing committee of IEEE Acoustics Speech and Signal Processing Society For DOREDIf source code see httpmichaelgellistripodcomdsppgm25html Examples factb2b1b0c1c0zzeroszpolessyredi142pi104pi10000020001 hfactb0b1zb2z2c0c1zz2 See Also eqiir 1733 Name system observation update x1ysystemx0fghqr Parameters x0 input state vector f system matrix g input matrix h Output matrix q input noise covariance matrix r output noise covariance matrix x1 output state vector y output observation Description define system function which generates the next observation given the old state System recursively calculated x1fx0gu yhx0v where u is distributed N0q and v is distribute N0r Authors C B 1734 Name trans lowpass to other filter transform hzttranshztrtypefrq hzttranspdzdgdtrtypefrq Parameters hz a single input single output discrete transfer function the low pass filter pd Vector of given filter poles zd Vector of given filter zeros gd scalar the given filter gain trtype string the type of transformation see description for possible values frq 2vector of discrete cutoff frequencies ie0frq5 see description for details hzt transformed filter transfert function Description function for transforming standardized lowpass filter given its poleszerosgain representation into one of the following filters trtypelp low pass filter the cutoff frequency is given by the first entry of frq the second one is ignored trtypehp high pass filter the cutoff frequency is given by the first entry of frq the second one is ignored trtypebp band pass filter the frequency range is given by frq1 and frq2 trtypesb stop band filter the frequency range is given by frq1 and frq2 Used functions bilt Examples clf Hlpiir3lpellip01 008 03 trans 1735 HbptransHlpbp001 01 HsbtransHlpsb001 01 clfgainplotHlpHbpHsb1d3048 llegendoriginal low passband passstop band llegendlocationinlowerleft Authors Carey Bunks See Also iir bilt 1736 Name wfir linearphase FIR filters wftwfmfrwfirftypefordercfreqwtypefpar Parameters ftype string lphpbpsb filter type forder Filter order pos integerodd for ftypehp or sb cfreq 2vector of cutoff frequencies 0cfreq1cfreq25 only cfreq1 is used when ftypelp or hp wtype Window type retrhmhnkrch fpar 2vector of window parameters Kaiser window fpar10 fpar20 Chebyshev window fpar10 fpar20 or fpar10 0fpar25 wft time domain filter coefficients wfm frequency domain filter response on the grid fr fr Frequency grid Description Function which makes linearphase FIR lowpass bandpass highpass and stopband filters using the windowing technique Works interactively if called with no arguments Authors C Bunks 1737 Name wiener Wiener estimate xspsxfpfwieneryx0p0fghqr Parameters f g h system matrices in the interval t0tf f f0f1ff and fk is a nxn matrix g g0g1gf and gk is a nxn matrix h h0h1hf and hk is a mxn matrix q r covariance matrices of dynamics and observation noise q q0q1qf and qk is a nxn matrix r r0r1rf and gk is a mxm matrix x0 p0 initial state estimate and error variance y observations in the interval t0tf yy0y1yf and yk is a column mvector xs Smoothed state estimate xs xs0xs1xsf and xsk is a column nvector ps Error covariance of smoothed estimate psp0p1pf and pk is a nxn matrix xf Filtered state estimate xf xf0xf1xff and xfk is a column nvector pf Error covariance of filtered estimate pfp0p1pf and pk is a nxn matrix Description function which gives the Wiener estimate using the forwardbackward Kalman filter formulation Authors C B 1738 Name wigner timefrequency wigner spectrum tabwignerxhdeltatzp Parameters tab wigner spectrum lines correspond to the time variable x analyzed signal h data window deltat analysis time increment in samples zp length of FFTs pizp gives the frequency increment Description function which computes the timefrequency wigner spectrum of a signal 1739 Name window compute symmetric window of various type winlwindowren winlwindowtrn winlwindowhnn winlwindowhmn winlwindowkrnalpha winlcwpwindowchnpar Parameters n window length par parameter 2vector pardpdf where dp 0dp5 rules the main lobe width and df rules the side lobe height df0 Only one of these two value should be specified the other one should set equal to 1 alpha kaiser window parameter alpha 0 win window cwp unspecified Chebyshev window parameter Description function which calculates various symmetric window for Disgital signal processing The Kaiser window is a nearly optimal window function alpha is an arbitrary positive real number that determines the shape of the window and the integer n is the length of the window By construction this function peaks at unity for k n2 ie at the center of the window and decays exponentially towards the window edges The larger the value of alpha the narrower the window becomes alpha 0 corresponds to a rectangular window Conversely for larger alpha the width of the main lobe increases in the Fourier transform while the side lobes decrease in amplitude Thus this parameter controls the tradeoff between mainlobe width and sidelobe area alpha window shape 0 Rectangular shape 5 Similar to the Hamming window 6 Similar to the Hanning window 86 Similar to the Blackman window The Chebyshev window minimizes the mainlobe width given a particular sidelobe height It is char acterized by an equiripple behavior that is its sidelobes all have the same height The Hanning and Hamming windows are quite similar they only differ in the choice of one parameter alpha walpha1 alphacos2pixn1 alpha is equal to 12 in Hanning window and to 054 in Hamming window window 1740 Examples Hamming window clf N64 wwindowhmN subplot121plot2d1Nwstylecolorblue setgcagrid1 1colorgray subplot122 n256Wfrfrmagwn plot2dfr20log10Wstylecolorblue setgcagrid1 1colorgray Kaiser window clf N64 wwindowkrN6 subplot121plot2d1Nwstylecolorblue setgcagrid1 1colorgray subplot122 n256Wfrfrmagwn plot2dfr20log10Wstylecolorblue setgcagrid1 1colorgray Chebyshev window clf N64 wdfwindowchN00051 subplot121plot2d1Nwstylecolorblue setgcagrid1 1colorgray subplot122 n256Wfrfrmagwn plot2dfr20log10Wstylecolorblue setgcagrid1 1colorgray See Also wfir frmag ffilt Authors Carey Bunks Bibliography IEEE Programs for Digital Signal Processing IEEE Press New York John Wiley and Sons 1979 Program 52 1741 Name yulewalk leastsquare filter design Hz yulewalkNfrqmag Parameters N integer order of desired filter frq real row vector nondecreasing order frequencies mag non negative real row vector same size as frq desired magnitudes Hz filter BzAz Description Hz yulewalkNfrqmag finds the Nth order iir filter n1 n2 Bz b1z b2z bn Hz n1 n2 Az z a2z an which matches the magnitude frequency response given by vectors frq and mag Vectors frq and mag specify the frequency and magnitude of the desired frequency response The frequencies in frq must be between 00 and 10 with 10 corresponding to half the sample rate They must be in increasing order and start with 00 and end with 10 Examples f0040406061H001100Hzyulewalk8fH fs1000fhz ffs2 clf0xsetwindow0plot2dfhzH xtitleDesired Frequency Response Magnitude frqrepfrepfreqHz0000105 clf1xsetwindow1plot2dfsfrqabsrepf xtitleObtained Frequency Response Magnitude 1742 Name zpbutt Butterworth analog filter polsgainzpbuttnomegac Parameters n integer filter order omegac real cutoff frequency in Hertz pols resulting poles of filter gain resulting gain of filter Description computes the poles of a Butterworth analog filter of order n and cutoff frequency omegac transfer function Hs is calculated by Hsgainrealpolypolss Authors F Delebecque INRIA 1743 Name zpch1 Chebyshev analog filter polesgainzpch1nepsilonomegac Parameters n integer filter order epsilon real ripple in the pass band 0epsilon1 omegac real cutoff frequency in Hertz poles resulting filter poles gain resulting filter gain Description Poles of a Type 1 Chebyshev analog filter The transfer function is given by Hsgainpolypoless Authors FD 1744 Name zpch2 Chebyshev analog filter zerospolesgainzpch2nAomegar Parameters n integer filter order A real attenuation in stop band A1 omegar real cutoff frequency in Hertz zeros resulting filter zeros poles resulting filter poles gain Resulting filter gain Description Poles and zeros of a type 2 Chebyshev analog filter gain is the gain of the filter Hsgainpolyzerosspolypoless Authors FD 1745 Name zpell lowpass elliptic filter zerospolesgainzpellepsilonAomegacomegar Parameters epsilon real ripple of filter in pass band 0epsilon1 A real attenuation of filter in stop band A1 omegac real pass band cutoff frequency in Hertz omegar real stop band cutoff frequency in Hertz zeros resulting zeros of filter poles resulting poles of filter gain resulting gain of filter Description Poles and zeros of prototype lowpass elliptic filter gain is the gain of the filter See Also ell1mag eqiir Authors FD Parte XXIX Matrizes Esparsas 1747 Name full conversão de matriz esparsa para cheia completa Xfullsp Parâmetros sp matriz esparsa ou cheia de reais ou complexos X matriz cheia completa Descrição Xfullsp converte a matriz esparsa sp em sua representação cheia completa Se sp já é cheia então X é igual a sp Exemplos spsparse125431123 Afullsp Ver Também sparse sprand speye 1748 Name ludel função utilitária usada com lufact ludelhand Parâmetros hand manipulador para fatores lu esparsos saída de lufact Descrição Esta função é usada de modo conjunto com lufact Ela limpa o espaço de memória interna usado para guardar o resultado de lufact A seqüência de comandos prlufactAxlusolvepbludelp resolve o sis tema linear esparso Ax b e limpa p Ver Também sparse lufact luget 1749 Name lufact fatoração LU esparsa handrklufactAprec Parâmetros A matriz quadrada esparsa hand manipulador para fatores LU esparsos rk inteiro posto de A prec vetor de tamanho 2 precepsreps fornecendo os limiares absoluto e relativo Descrição handrklufactA realiza a fatoração LU da matriz esparsa A hand sem exibição é usado por lusolve para resolver sistemas lineares e luget para retirar os fatores hand deve ser limpo pelo comando ludelhand A matriz A não precisa ser de posto cheio mas deve ser quadrada desde que A é assumida como sendo esparsa podese adicionar 0 se necessário para quadrála eps a magnitude absoluta que um elemento deve ter para ser considerado um candidato a pivô exceto como último recurso Este número deve ser posto de modo a ser significantemente menor que o menor elemento da diagonal que se espera estar localizado na matriz O valor padrão é eps reps Este número determina qual será o limiar relativo do pivô Deve estar entre 0 e 1 Se for 1 então o método de pivoteamento tornase pivotação completa que é muito lento e tende a completar a matriz Se o número acertado é próximo de 0 o método de pivoteamento tornase estritamente de Markowitz sem limiar O limiar de pivô é usado para eliminar candidatos a pivô que poderiam causar crescimento excessivo de elementos se fossem usados Crescimento de elementos é a causa dos erros de arredondamento Crescimento de elementos ocorre mesmo em matrizes bem condi cionadas Definir o reps como um número grande reduzirá o crescimento de elementos e os erros de arredondamento mas colocálo muito grande aumentará muito o tempo de execução e resul tará num grande número de preenchimentos Se isto ocorrer a precisão pode ficar prejudicada por causa do grande número de operações requeridas na matriz devido ao grande número de preenchi mentos 0001 parece um bom valor e é o valor default O default é escolhido fornecendose um valor maior que 1 ou menor que ou igual a 0 Este valor deve ser aumentado e a matriz resolvida se o crescimento for excessivo Mudar o limiar do pivô não melhora o desempenho em matrizes onde o crescimento é baixo como é geralmente o caso de matrizes malcondicionadas reps foi escolhido para uso com matrizes quase diagonalmente dominantes como uma matriz de admissão de nó e nó modificado Para estas matrizes geralmente o melhor é usar pivotação diagonal Para matrizes sem uma diagonal forte geralmente é melhor usar um limiar maior como 001 ou 01 Exemplos arand55brand51Asparsea hrklufactA lufact 1750 xlusolvehbaxb ludelh Ver Também sparse lusolve luget 1751 Name luget extração dos fatores LU esparsos PLUQlugethand Parâmetros hand manipulador saída de lufact P matriz de permutação esparsa L matriz esparsa triangular infeiror se hand é obtida de uma matriz nãosingular U matriz quadrada triangular superior esparsa nãosnigular preenchida com 1 ao longo da diagonal principal Q matriz de permutação esparsa Descrição PLUQlugethand com hand obtida pelo comando handrklufactA com A uma matriz esparsa retorna quatro matrizes esparsas tais que PLUQA A matriz A não precisa ser de posto cheio mas deve ser quadrada desde que A é assumida esparsa podese adicionar 0 se necessário para quadrar A Se A é singular a matriz L é de colunas comprimidas com rk colunas independentes nãonulas a matriz nãosingular esparsa QinvU comprime em colunas A Exemplos arand52rand25Asparsea handrklufactAPLUQlugethand fullL PLUQA cleanPLUQA ludelhand Ver Também sparse lusolve luget clean 1752 Name lusolve solucionador de sistemas lineares esparsos lusolvehandb lusolveAb Parâmetros b matriz de reais completa A matriz quadrada de reais esparsa e invertível hand manipulador para fatores de lu esparsos previamente computados saída de lufact Descrição xlusolvehandb resolve o sistema linear esparso Ax b handrklufactA é a saída de lufact xlusolveAb resolve o sistema linear esparso Ax b Exemplos nonzeros1234rowscols11223344 spsparserowscolsnonzeros hrklufactspxlusolveh1111ludelh rkspx nonzeros1234rowscols11223344 spsparserowscolsnonzeros xlusolvespones41 spx Ver Também sparse lufact slash backslash 1753 Name mtlbsparse converte matriz esparsa YmtlbsparseX Parâmetros X matriz esparsa Y matriz esparsa em formato Matlab Descrição YmtlbsparseX é usado para converter X uma matriz esparsa Scilab para formato Matlab Y é uma variável de tipo 7 ie typeY é igual a 7 Esta função deve ser usada em mexfiles um mexfile Matlab contendo matrizes esparsas pode ser usado apenas se as matrizes esparsas do Scilab forem convertidas para este formato As funções full e spget funcionam com este formato Outras operações e funções usando este formato podem ficar sobrecarregadas com funções do Scilab usando o prefixo msp Por exemplo a função msppx ver diretório SCIDIRmacrospercent é usada para exibir tais objetos tipo 7 Exemplos Xsparserand22 YmtlbsparseX Y fullY ijvmnspgetY Ver Também full spget 1754 Name nnz número de entradas nãonulas de uma matriz nnnzX Parâmetros X matriz de reais ou complexos esparsa ou cheia n inteiro número de elementos nãonulos de X Descrição nnz conta o número de entradas nãonulas de uma matriz esparsa ou cheia Exemplos spsparse1245310123 nnzsp a1 0 0 0 2 nnza Ver Também spget 1755 Name sparse definição de matriz esparsa spsparseX spsparseijv mn Parâmetros X matriz completa ou esparsa de reais ou complexos ij matriz de inteiros de duas colunas índices das entradas não nulas v vetor mn vetor de inteiros com duas entradas dimensão de linha dimensão de coluna sp matriz esparsa Descrição sparse é usado para construir uma matriz esparsa Apenas entradas nãonulas são armazenadas sp sparseX converte uma matriz completa para sua forma esparsa retirando qualquer ele mento nulo Se X já é esparsa sp é X spsparseijv mn constrói uma matriz esparsa mn1pormn2 sparse matrix com spijk1ijk2vk ij e v devem ter a mesma dimensão de coluna Se o parâmetro opcional mn não for dado as dimensões da matriz sp são os valores máximos de ij1 e ij2 respectivamente Operações concatenação adição etc com matrizes esparsas são feitas usando a mesma sintaxe para matrizes completas Funções elementares também estão disponíveis absmaxisumdiag para matrizes es parsas Operações mistas completasesparsas são permitidas Os resultados são completos ou esparsos de pendendo das operações Exemplos spsparse1245310123 sizesp xrand22absxfullabssparsex Ver Também full spget sprand speye lufact 1756 Name spchol fatoração esparsa de Cholesky RP spcholX Parâmetros X matriz simétrica esparsa e positiva definida de reais P matriz de permutação R fator de Cholesky Descrição RP spcholX produz uma matriz triângular inferior R tal que PRRP X Exemplos X 3 0 0 2 0 0 2 0 2 0 0 0 5 4 0 0 0 0 0 0 0 0 0 4 5 0 0 0 0 0 0 0 0 2 0 0 3 0 0 2 0 2 0 0 0 0 0 0 5 0 0 0 0 0 4 0 0 0 0 0 4 0 3 0 3 0 2 0 0 2 0 0 3 0 2 0 0 0 0 0 0 0 3 0 4 0 3 0 2 0 0 2 0 0 2 0 3 0 0 0 0 0 0 0 3 0 3 0 4 0 0 0 0 0 4 0 0 0 0 0 5 XsparseXRP spcholX maxPRRPX Ver Também sparse lusolve luget chol 1757 Name spcompack converte uma representação de adjacência comprimida em representação de adjacência padrão Parâmetros xadj vetor de inteiros de comprimento n1 xlindx vetor de inteiros de comprimento n1 ponteiros lindx vetor de inteiros adjncy vetor de inteiros Descrição A função utilitária spcompak é usada para converter uma representação de adjacência comprimida em uma representação de adjacência padrão Exemplos A é a matriz esparsa A1000000 0100000 0010000 0011000 0011100 0011010 0011011 AsparseA Para esta matriz a representação padrão de adjacência é dada por xadj123812131516 adjncy1 2 34567 4567 5 67 7 ver sp2adj Incrementos no vetor xadj dão o número de entradas não nulas em cada coluna ie há 211 entrada na coluna 1 há 321 entrada na coluna 2 há 835 entradas na coluna 3 1284 4 etc O índice de linha dessas entradas é dado pelo vetor adjncy por exemplo adjncy 37adjncyxadj3xadj4134567 diz que as 5xadj4xadj3 entradas na coluna 3 têm índices de linha 34567 Na representação compacta as seqüências repetidas em adjncy são eliminadas Aqui em adjncy as seqüências 4567 e 7 são eliminadas A estrutura padrão xadjadjncy toma a forma comprimida lindxxlindx lindx1 2 34567 5 67 spcompack 1758 xlindx1238911 colunas 4 e 7 de A são eliminadas A pode ser reconstruída de xadjxlindxlindx xadjadjncyanz sp2adjA adjncyspcompackxadjxlindxlindx Ver Também sp2adj adj2sp spget 1759 Name spget recupera entradas de matriz esparsa ijvmnspgetsp Parâmetros sp matriz esparsa de reais ou complexos ij matriz de inteiros de duas colunas índices das entradas nãonulas mn vetor de inteiros com duas entradas dimensão de linha dimensão de coluna v vetor coluna Descrição spget é usado para converter a representação interna de matrizes esparsas na representação padrão ij v Entradas nãonulas de sp estão localizadas em linhas e colunas com índices em ij Exemplos spsparse1245310123 ijvmnspgetsp Ver Também sparse sprand speye lufact 1760 Name gmres Generalized Minimum RESidual method xflagerriterres gmresAbrstrtolmaxiMx0 Parameters A nbyn matrix or function returning Ax b right hand side vector x0 initial guess vector default zerosn1 M preconditioner matrix or function returning Mx In the first case default eyenn rstr number of iterations between restarts default 10 maxi maximum number of iterations default n tol error tolerance default 1e6 x solution vector err final residual norm iter number of iterations performed flag 0 gmres converged to the desired tolerance within maxi iterations 1 no convergence given maxi res residual vector Description GMRES solves the linear system Axb using the Generalized Minimal residual method with restarts Details of this algorithm are described in Templates for the Solution of Linear Systems Building Blocks for Iterative Methods Barrett Berry Chan Demmel Donato Dongarra Eijkhout Pozo Romine and Van der Vorst SIAM Publications 1993 ftp netlib2csutkedu cd linalg get templatesps gmres 1761 Iterative Methods for Sparse Linear Systems Second Edition Saad SIAM Publications 2003 ftp ftpcsumnedu cd deptuserssaadPS get allpszip Examples GMRES call xgmresAb See Also pcg qmr Authors Sage Group IRISA 2005 1762 Name pcg precondioned conjugate gradient x flag err iter res pcgA b tol maxIter M M2 x0 verbose x flag err iter res pcgA b keyvalue Parameters A a matrix or a function or a list computing Ax for each given x The following is a description of the computation of Ax depending on the type of A matrixIf A is a matrix it can be dense or sparse functionIf A is a function it must have the following header function y A x listIf A is a list the first element of the list is expected to be a function and the other ele ments in the list are the arguments of the function from index 2 to the end When the function is called the current value of x is passed to the function as the first argument The other argu ments passed are the one given in the list b right hand side vector size nx1 tol error relative tolerance default 1e8 The termination criteria is based on the 2norm of the residual rbAx divided by the 2norm of the right hand side b maxIter maximum number of iterations default n M preconditioner full or sparse matrix or function returning Mx default none M2 preconditioner full or sparse matrix or function returning M2x for each x default none x0 initial guess vector default zerosn1 verbose set to 1 to enable verbose logging default 0 x solution vector flag 0 if pcg converged to the desired tolerance within maxi iterations 1 else err final relative norm of the residual the 2norm of the righthand side b is used iter number of iterations performed pcg 1763 res vector of the residual relative norms Description Solves the linear system Axb using the conjugate gradient method with or without preconditioning The preconditionning should be defined by a symmetric positive definite matrix M or two matrices M1 and M2 such that MM1M2 in the case the function solves invMAx invMb for x M M1 and M2 can be Scilab functions with calling sequence yMilxx which computes the corresponding left division yMix The A matrix must be a symmetric positive definite matrix full or sparse or a function with calling sequence yAxx which computes yAx Example with well conditionned and ill conditionned problems In the following example two linear systems are solved The first maxtrix has a condition number equals to 002 which makes the algorithm converge in exactly 10 iterations Since this is the size of the matrix it is an expected behaviour for a gradient conjugate method The second one has a low condition number equals to 1d6 which makes the algorithm converge in a larger 22 iterations This is why the parameter maxIter is set to 30 See below for other examples of the keyvalue syntax Well conditionned problem A 94 0 0 0 0 28 0 0 32 0 0 59 13 5 0 0 0 10 0 0 0 13 72 34 2 0 0 0 0 65 0 5 34 114 0 0 0 0 0 55 0 0 2 0 70 0 28 32 12 0 28 0 0 0 0 87 20 0 33 0 0 0 0 0 28 20 71 39 0 0 0 10 0 0 32 0 39 46 8 0 32 0 0 0 12 33 0 8 82 11 0 0 65 55 0 0 0 0 11 100 bones101 x fail err iter respcgAb1d1215 mprintf faild iterd errrele failitererr Ill contionned one A 894 0 0 0 0 28 0 0 1000 70000 0 5 13 5 0 0 0 0 0 0 0 13 72 34 0 0 0 0 0 6500 0 5 34 1 0 0 0 0 0 55 0 0 0 0 70 0 28 32 12 0 28 0 0 0 0 87 20 0 33 0 0 0 0 0 28 20 71 39 0 0 0 0 0 0 32 0 39 46 8 0 1000 0 0 0 12 33 0 8 82 11 70000 0 6500 55 0 0 0 0 11 100 x fail err iter respcgAbmaxIter30tol1d12 mprintf faild iterd errrele failitererr pcg 1764 Examples with A given as a sparse matrix or function or list The following example shows that the method can handle sparse matrices as well It also shows the case where a function computing the righthand side is given to the pcg primitive The final case shown by this example is when a list is passed to the primitive Well conditionned problem A 94 0 0 0 0 28 0 0 32 0 0 59 13 5 0 0 0 10 0 0 0 13 72 34 2 0 0 0 0 65 0 5 34 114 0 0 0 0 0 55 0 0 2 0 70 0 28 32 12 0 28 0 0 0 0 87 20 0 33 0 0 0 0 0 28 20 71 39 0 0 0 10 0 0 32 0 39 46 8 0 32 0 0 0 12 33 0 8 82 11 0 0 65 55 0 0 0 0 11 100 bones101 Convert A into a sparse matrix AsparsesparseA x fail err iter respcgAsparsebmaxIter30tol1d12 mprintf faild iterd errrele failitererr Define a function which computes the righthand side function yAtimesxx A 94 0 0 0 0 28 0 0 32 0 0 59 13 5 0 0 0 10 0 0 0 13 72 34 2 0 0 0 0 65 0 5 34 114 0 0 0 0 0 55 0 0 2 0 70 0 28 32 12 0 28 0 0 0 0 87 20 0 33 0 0 0 0 0 28 20 71 39 0 0 0 10 0 0 32 0 39 46 8 0 32 0 0 0 12 33 0 8 82 11 0 0 65 55 0 0 0 0 11 100 yAx endfunction Pass the script Atimesx to the primitive x fail err iter respcgAtimesxbmaxIter30tol1d12 mprintf faild iterd errrele failitererr Define a function which computes the righthand side function yAtimesxbisxA yAx endfunction Pass a list to the primitive Alist listAtimesxbisAsparse x fail err iter respcgAlistbmaxIter30tol1d12 mprintf faild iterd errrele failitererr pcg 1765 Examples with keyvalue syntax The following example shows how to pass arguments with the keyvalue syntax This allows to set nonpositionnal arguments that is to set arguments which are not depending on their order in the list of arguments The available keys are the names of the optional arguments that is tol maxIter M M2 x0 verbose Notice that in the following example the verbose option is given before the maxIter option Without the keyvalue syntax the positionnal arguments would require that maxIter come first and verbose after Example of an argument passed with keyvalue syntax A1001110 b10111 xcomputed flag err iter respcgAbverbose1 With keyvalue syntax the order does not matter xcomputed flag err iter respcgAbverbose1maxIter0 See Also backslash qmr gmres Authors Sage Group IRISA 2004 Serge Steer INRIA 2006 Michael Baudin INRIA 20082009 References Templates for the Solution of Linear Systems Building Blocks for Iterative Methods Barrett Berry Chan Demmel Donato Dongarra Eijkhout Pozo Romine and Van der Vorst SIAM Publications 1993 ftp netlib2csutkedulinalgtemplatesps Iterative Methods for Sparse Linear Systems Second Edition Saad SIAM Publications 2003 ftp ftpcsumnedudeptuserssaadPSallpszip 1766 Name qmr quasi minimal resiqual method with preconditioning xflagerriterres qmrAbx0M1M1pM2M2pmaxitol Parameters A matrix of size nbyn or function returning Ax b right hand side vector x0 initial guess vector default zerosn1 M1 left preconditioner matrix or function returning M1x In the first case default eyenn M1p must only be provided when M1 is a function In this case M1p is the function which returns M1x M2 right preconditioner matrix or function returning M2x In the first case default eyenn M2p must only be provided when M2 is a function In this case M2p is the function which returns M2x maxi maximum number of iterations default n tol error tolerance default 1000eps x solution vector flag 0 gmres converged to the desired tolerance within maxi iterations 1 no convergence given maxi res residual vector err final residual norm iter number of iterations performed Description Solves the linear system Axb using the Quasi Minimal Residual Method with preconditioning qmr 1767 See Also gmres Authors SAGE Group IRISA 2005 Parte XXX Funções Especiais 1769 Name besseli funções modificadas de Bessel do primeiro tipo I sub alfa besselj funções de Bessel do primeiro tipo J sub alpha besselk funções modificadas de Bessel do segundo tipo K sub alpha bessely funções de Bessel do segundo tipo Y sub alpha besselh funções de Bessel do terceiro tipo também conhecidas como funções de Hankel y besselialphax ice y besseljalphax ice y besselkalphax ice y besselyalphax ice y besselhalphax y besselhalphaKx ice Parâmetros x vetor de reais ou complexos alpha vetor de reais ice flag sinalizador inteiro com valor padrão 0 K inteiro com valores possíveis 1 ou 2 a função do tipo de Hankel Descrição Aviso a semântica destas funções varia entre o Scilab30 e Scilab31 A semântica antiga está disponível para compatibilidade usando as funções oldbesseli oldbesselj oldbesselk oldbessely besselialphax computa as funções de Bessel modificadas do primeiro tipo I sub alfa para ordem real alpha e argumento x besselialphax1 computa besselialphaxexpabsrealx besseljalphax computa as funções de Bessel do primeiro tipo J sub alfa para ordem real alpha e argumento x besseljalphax1 computa besseljalphaxexp absimagx besselkalphax computa as funções de Bessel modificadas do segundo tipo K sub alfa para ordem real alpha e argumento x besselkalphax1 computa besselkalphaxexpx besselyalphax computa as funções de Bessel do segundo tipo Y sub alfa para ordem real alpha e argumento x besselyalphax1 computa besselyalphaxexp absimagx besselhalpha K x computa as funções de Bessel do terceiro tipo função de Hankel H1 ou H2 dependendo do K para ordem real alpha e argumentot x Se omitido K é suposto co mo sendo 1 besselhalpha1x1 computa besselhalpha1xexpix e besselhalpha2x1 computa besselhalpha2xexpix Observações Se alpha e x são arrays de mesmo tamanho o resultado y também terá este tamanho Se uma entrada é um escalar ela é expandida para o tamanho da outra entrada Se uma entrada é um vetor linha e a outra é um vetor coluna o resultado y é um table 2dimensional tabela de valores de funções besseli 1770 As funções de Bessel Yalfa e Jalfa são duas soluções independentes da equação diferencial de Bessel 2 2 2 x y x y x alfa y 0 alfa 0 As funções modificadas de Bessel Kalfa e Ialfa são duas soluções independentes para a equação diferencial de Bessel 2 2 2 x y x y x alfa y 0 alfa 0 As funções de Hankel de primeiro e segundo tipos H1alfa e H2alfa são combinações lineares das funções de Bessel de primeiro e segundo tipos H1alfaz Jalfaz i Yalfaz H2alfaz Jalfaz i Yalfaz Exemplos Funções I de Bessel x linspace001105000 xbasc subplot211 plot2dxbesseli04x style26 legendIstring042 xtitleAlgumas funções modificadas de Bessel do primeiro tipo subplot212 plot2dxbesseli04x1 style26 legendIstring041 xtitleAlgumas funções modificadas de Bessel do primeiro tipo escaladas Funções J de Bessel x linspace0405000 xbasc plot2dxbesselj04x style26 legJ0J1J2J3J4 legendIstring041 xtitleAlgumas funções de Bessel do primeiro tipo Usando o fato de que J12x sqrt2x pi sinx Para comparar o algoritmo de besselj05x com uma fórmula mais direta x linspace01405000 y1 besselj05 x y2 sqrt2 pixsinx er absy1y2y2 ind finder 0 y2 0 xbasc subplot211 plot2dxy1style2 xtitlebesselj05x subplot212 plot2dxind erind style2 logflagnl xtitleErro relativo entre as duas fórmulas para besselj05x besseli 1771 Funções K de Bessel x linspace001105000 xbasc subplot211 plot2dxbesselk04x style04 rect00610 legendKstring041 xtitleAlgumas funções modificadas de Bessel do segundo tipo subplot212 plot2dxbesselk04x1 style04 rect00610 legendKstring041 xtitleAlgumas funções modificadas de Bessel do segundo tipo escaladas Funções Y de Bessel x linspace01405000 funções Y de Bessel não possuem limite para x 0 xbasc plot2dxbessely04x style04 rect0154006 legendYstring044 xtitleAlgumas funções de Bessel do segundo tipo Funções H de Bessel x400252 y15002515 XY ndgridxy H besselh01XiY clffgcf xsetfpf fcolormapjetcolormap16 contour2dxyabsH020232strf034rect415315 legendsstring020232116ur xtitleCurvas de nível de H10z Autores Amos D E SNLA Daniel S L SNLA Weston M K SNLA Função Usada Os códigosfontes podem ser achados em SCImodulesspecialfunctionssrcfortranslatec e SCI modulesspecialfunctionssrcfortran Slatec dbesif zbesif dbesjf zbesjf dbeskf zbeskf dbesyf zbesyf zbeshf Drivers para estender a área de definição Serge Steer INRIA dbesigf zbesigf dbesjgf zbesjgf dbeskgf zbeskgf dbesygf zbesygf zbeshgf 1772 Name beta função beta z betaxy Parâmetros x y dois reais positivos ou duas matrizes ou vetores de reais positivos de mesmo tamanho z um real ou uma matriz de reais com mesmo tamanho que x com zij betaxijyij Descrição Computa a função beta completa 1 x1 y1 gammax gammay betaxy t 1t dt 0 gammaxy Para x e y pequenos o algoritmo usa a expressão em função da função gama de outro modo ele aplica a função exponencial no resutado da função betaln function fornecido no DCDFLIB Biblioteca de Rotinas FORTRAN para Funções Inversas e Outros Parâmetros de Distribuição Cumulativa ver cdfbet para maiores informações sobre DCDFLIB Exemplos exemplo 1 beta52 beta25 simetria deve ser exatamente 0 beta0505 o valor exato é pi exemplo 2 um estudo de erros baseado na relação B1x 1x a computação de 1x deve levar apenas a um erro relativo de epsm então pode ser usada como referência para avaliar o erro em B1x x logspace8820000 e betaonesxx 1x er abse x ind finder 0 eps onesxindnumberpropertieseps xbasc plot2dxinderind eps 2epsstyle1 2 3logflaglllegerepsm2 epsm xtitleerro relativo aproximado na computação de beta1x xselect exemplo 3 plotando a função beta t linspace021060 X tonest Y onestt Z betaXY xbasc plot3dt t Z flag2 4 4 legxyz alpha75 theta30 beta 1773 xtitleA função beta em 0210x0210 xselect Ver Também gamma cdfbet 1774 Name calerf computa funções de erro Parâmetros x matriz ou vetor de reais flag indicador inteiro y matriz ou vetor de reais de mesmo tamanho que x Descrição calerfx0 computa a função de erro erfx calerfx1 computa a função de erro complementar erfcx calerfx2 computa a função de erro complementar escalada erfcxx Exemplos deffyftyexpt2 calerf10 2sqrtpiintg01f Ver Também erf erfc erfcx Autor W J Cody código de Netlib specfun 1775 Name dlgamma derivada da função gammaln função psi y dlgammax Parâmetros x vetor de reais y vetor de reais com o mesmo tamanho Descrição dlgammax avalia em todos os elementos de x a derivada logarítmica da função gama gamma que corresponde também à derivada da função lngama gammaln ddx gammax gammax ddx ln gammax x deve ser real Também é conhecida como a função psi Exemplos dlgamma05 Ver Também gamma gammaln Autor W J Cody code from Netlib specfun 1776 Name erf função de erro y erfx Parâmetros x vetor ou matriz de reais y vetor ou matriz de reais de mesmo tamanho que x Descrição erf computa a função de erro x 2 2 t y e dt sqrtpi 0 Exemplos deffyftyexpt2 erf052sqrtpiintg005f Ver Também erfc erfcx calerf cdfnor Autor W J Cody código de Netlib specfun 1777 Name erfc função de erro complementar y erfcx Parâmetros x real vector or matrix y real vector or matrix of same size than x Descrição erfc computa a função de erro complementar oo 2 2 t y e dt sqrtpi x y 1 erfx Exemplos erf0502erfc0502 Ver Também erf erfcx calerf Autor W J Cody código de Netlib specfun 1778 Name erfcx função de erro complementar escalada y erfcxx Parameters x vetor ou matriz de reais y vetor ou matriz de reais de mesmo tamanho que x Descrição erfcx computa a função de erro complementar escalada 2 y expx erfcx 1 y quando x oo x sqrtpi Ver Também erf erfc calerf Autor W J Cody código de Netlib specfun 1779 Name erfinv função inversa à função de erro y erfinvx Parâmetros x vetor ou matriz de reais y vetor ou matriz de reais de mesmo tamanho que x Descrição erfinv computa a função inversa à função de erro erf x erfinvy satisfaz y erfx 1 y 1 inf x inf Exemplos xlinspace099099100 yerfinvx plot2dxy normxerfyinf Ver Também erfc cdfnor Referências Milton Abramowitz e Irene A Stegun eds Handbook of Mathematical Functions with Formulas Graphs and Mathematical Tables New York Dover 1972 1780 Name gamma função gama y gammax Parâmetros x vetor ou matriz de reais ou complexos y vetor ou matriz de reais ou complexos de mesmo tamanho que x Descrição gammax avalia a função gama em todos os elementos de x A função gama é defininda por oo x1 t gammax t e dt 0 e generaliza a função fatorial para os números reais gamman1 n Exemplos exemplos simples gamma05 gamma6prod15 o gráfico da função gama em ab a 3 b 5 x linspaceab40000 y gammax xbasc cxgetcolor xsetcolor2 plot2dx y style0 axesflag5 recta 10 b 10 xsetcolorc xtitleA função gama em stringastringb xselect Ver Também gammaln dlgamma Autores W J Cody e L Stoltz código de Netlib specfun 1781 Name gammaln o logaritmo natural da função gama y gammalnx Parameters x vetor de reais y vetor de reais com o mesmo tamanho Description gammalnx avalia o logaritmo natural da função gama em todos os elementos de x evitando underflow e overflow x deve ser de reais Exemplos gammaln05 Ver Também gamma dlgamma Autores W J Cody e L Stoltz código de Netlib specfun 1782 Name legendre funções associadas de Legendre y legendrenmx normflag Parâmetros n inteiro nãonegativo ou vetor de inteiros nãonegativos igualmente espaçados com incremento igual a 1 m inteiro nãonegativo ou vetor de inteiros nãonegativos igualmente espaçados com incremento igual a 1 x vetor linha de reais os elementos de x devem estar no intervalo 11 normflag opcional escalar string Descrição Quando n e m são escalares legendrenmx avalia a função de Legendre associada Pnmx em todos os elementos de x A definição usada é m m m2 d Pnmx 1 1x2 Pnx m dx onde Pn é o polinômio de Legendre de grau n Então legendren0x avalia o polinômio de Legendre Pnx em todos os elementos de x Quando normflag é igual a norm o resultado é uma versão normalizada sem o fator 1m precisamente m 2n1nm m2 d Pnmxnorm 1x2 Pnx 2 nm m dx que é útil para computar funções harmônicas esféricas ver exemplo 3 Por eficiência um dos primeiros dois argumentos pode ser um vetor por exemplo legendren1n20x avalia todos os polinômios de Legendre de graus n1 n11 n2 nos elementos de x e legendrenm1m2x avalia todas as funções de Legendre associadas Pnm para mm1 m11 m2 em x Formato de Saída Em qualquer caso o formato é y legendre 1783 maxlengthnlengthm x lengthx e yij Pnimxj se n é um vetor yij Pnmixj se m é um vetor y1j Pnmxj se ambos n e m são escalares de tal modo que x é preferivelmente um vetor linha mas qualquer matriz mx x nx é excetuada e considerada como uma matriz 1 x mx nx matrix reformada segundo a ordem das colunas Exemplos exemplo 1 plot dos primeiros 6 polinômios de Legendre em 11 l nearfloatpred1 x linspacell200 y legendre05 0 x xbasc plot2dxy legp0p1p2p3p4p5p6 xtitleOs 6 primeiros polinômios de Legendre exemplo 2 plot das funções associadas de Legendre de grau 5 l nearfloatpred1 x linspacell200 y legendre5 05 x norm xbasc plot2dxy legp50p51p52p53p54p55 xtitleAs funções associadas de Legendre normalizadas de grau 5 exemplo 3 definindo e plotando uma função harmônica esférica 31 definindo a função Ylm function y Ylmthetaphi teta pode ser um escalar ou um vetor linha phi pode ser um escalar ou um vetor coluna if m 0 then y 1msqrt2piexpimphilegendrel m costheta norm else y 1sqrt2piexpimphilegendrel m costheta norm end endfunction 32 definindo outra função útil function xyz sph2cartthetaphir vetor linha teta 1 x nt vetor coluna phi np x 1 r escalar ou matriz np x nt rij o comprimento em phii thetaj x rcosphisintheta y rsinphisintheta z ronesphicostheta endfunction 33 plot de Y31thetaphi l 3 m 1 legendre 1784 theta linspace01pi0160 phi linspace02pi120 f Ylmthetaphi x1y1z1 sph2cartthetaphiabsf xf1yf1zf1 nf3dx1y1z1 x2y2z2 sph2cartthetaphiabsrealf xf2yf2zf2 nf3dx2y2z2 x3y3z3 sph2cartthetaphiabsimagf xf3yf3zf3 nf3dx3y3z3 xbasc subplot131 plot3dxf1yf1zf1flag2 4 4 xtitleY31thetaphi subplot132 plot3dxf2yf2zf2flag2 4 4 xtitleRealY31thetaphi subplot133 plot3dxf3yf3zf3flag2 4 4 xtitleImagY31thetaphi Autores Smith John M código dxlegff de Slatec B Pincon interface Scilab 1785 Name oldbesseli funções de Bessel modificadas do primeiro tipo I sub alfa oldbesselj funções de Bessel do primeiro tipo J sub alfa oldbesselk funções de Bessel modificadas do segundo tipo K sub alfa oldbessely funções de Bessel do segundo tipo Y sub alfa y oldbesselialphax y oldbesselialphaxice y oldbesseljalphax y oldbesselkalphax y oldbesselkalphaxice y oldbesselyalphax Parâmetros x vetor de reais com entradas nãonegativas alpha vetor de reais com entradas nãonegativas igualmente espaçadas com incremento igual a 1alphaalpha0n1n2 ice flag inteiro com valor padrão 1 Descrição Funções obsoletas use besseli besselj besselk bessely no lugar Note contudo que a semântica destes dois grupos de funções é diferente oldbesselialphax computa funções modificadas de Bessel do primeiro tipo I sub alfa para ordem real nãonegativa alpha e argumento real nãonegativo x besselialphax2 computa besselialphaxexpx oldbesseljalphax computa funções de Bessel do primeiro tipo J sub alfa para ordem real nãonegativa alpha e argumento real nãonegativo x oldbesselkalphax computa as funções modificadas de Bessel do segundo tipo K sub alfa para ordem real nãonegativa alpha e argumento real nãonegativo x besselkalphax2 computa besselkalphaxexpx oldbesselyalphax computa funções de Bessel do segundo tipo Y sub alfa para ordem real nãonegativa alpha e argumento real nãonegativo x alpha e x podem ser vetores A saída é mporn com m sizex n sizealpha whose ij cuja entrada oldbesselalphajxi Observações As funções Yalfa e Jalfa de Bessel são duas soluções independentes da equação diferencial de Bessel 2 2 2 x y x y x alfa y 0 alfa 0 As funções modificadas Kalfa e Ialfa de Bessel são duas soluções independentes da equação difer encial modificada de Bessel oldbesseli 1786 2 2 2 x y x y x alfa y 0 alfa 0 Exemplos exemplo 1 exibindo algumas funções I de Bessel x linspace001105000 y oldbesseli04x ys oldbesseli04x2 xbasc subplot211 plot2dxy style26 legI0I1I2I3I4 rect00610 xtitleAlgumas funções modificadas de Bessel do primeiro tipo subplot212 plot2dxys style26 legI0sI1sI2sI3sI4s rect0061 xtitleAlgumas funções modificadas de Bessel do primeiro tipo escaladas exemplo 2 exibindo algumas funções J de Bessel x linspace0405000 y besselj04x xbasc plot2dxy style26 legJ0J1J2J3J4 xtitleAlgumas funções de Bessel do primeiro tipo example 3 usando o fato de que J12x sqrt2x pi sinx para comparar o algoritmo de besselj05x com uma fórmula mais direta x linspace01405000 y1 besselj05 x y2 sqrt2 pixsinx er absy1y2y2 ind finder 0 y2 0 xbasc subplot211 plot2dxy1style2 xtitlebesselj05x subplot212 plot2dxind erind style2 logflagnl xtitleerro relativo entre as duas fórmulas para besselj05x exemplo 4 exibindo algumas funções K de Bessel x linspace001105000 y besselk04x ys besselk04x1 xbasc subplot211 plot2dxy style04 legK0K1K2K3K4 rect00610 xtitleAlgumas funções modificadas de Bessel do segundo tipo subplot212 plot2dxys style04 legK0sK1sK2sK3sK4s rect00610 xtitleAlgumas funções modificadas de Bessel do segundo tipo escaladas exemplo 5 plot de várias funções Y de Bessel x linspace01405000 funções Y de Bessel não possuem limite para x 0 y bessely04x xbasc oldbesseli 1787 plot2dxy style04 legY0Y1Y2Y3Y4 rect0154006 xtitleAlgumas funções de Bessel do segundo tipo Autores W J Cody L Stoltz código de Netlib specfun Parte XXXI Cadeias de Caracteres Strings 1789 Name ascii conversão ASCII de strings aasciitxt txtasciia Parâmetros txt um string ou matriz de strings a um vetor de códigos ASCII inteiros Descrição Esta função converte um string Scilab para um vetor de códigos ASCII ou um vetor de códigos ASCII em strings Scilab Se txt é uma matriz de strings asciitxt é equivalente a asciistrcattxt Exemplos asciiolámundo asciiscilab ascii115 99 105 108 97 98 Ver Também code2str str2code 1790 Name blanks cria strings de caracteres em branco txtblanksn Parâmetros txt um único string n número de caracteres em branco Descrição blanksn é um string de n caracteres em branco Exemplos dispxxx blanks20 yyy 1791 Name code2str retorna o string associado ao código Scilab inteiro strcode2strc Parâmetros str string c vetor de códigos de caracteres inteiros Descrição Retorna o string associado ao código Scilab inteiro str é tal que ci é o código Scilab inteiro de partstri Exemplos code2str28 12 18 21 10 11 str2codeScilab Ver também str2code ascii 1792 Name convstr conversão maiúsculasminúsculas minúsculasmaiúsculas yconvstrstr flag Parâmetros str y uma matriz de strings flag um caractere de opção com dois possíveis valores u para maiúsculas l para minúsculas Descrição converts a matriz de strings strmatrix para caracteres minúsculos l valor padrão ou para maiúsculos u Exemplos Aestaéa minhamatriz convstrAu 1793 Name emptystr string de comprimento zero semptystr semptystra semptystrmn Parâmetros a qualquer tipo de matriz s matriz de strings mn inteiros Descrição Retorna uma matriz de strings de comprimento zero Sem argumentos de entrada retorna um string de comprimento zero Com uma matriz como argumento de entrada retorna uma matriz de strings de comprimento zero de mesmo tamanho Com dois argumentos inteiros retorna uma matriz mxn de strings de comprimento zero Exemplos xemptystrfor k110 xxstringkend Ver Também part length string 1794 Name grep acha correspondências de um string em um vetor de strings rowgrephaystackneedle rowwhichgrephaystackneedle rowgrephaystackneedle flag rowwhichgrephaystackneedle flag Parâmetros haystack vetor linha de strings needle string ou vetor linha de strings Os strings a serem procurados em haystack row vetor de índices linha onde uma correspondência foi encontrada ou matriz vazia se nenhuma ocorrência tiver sido encontrada which vetor de índices índice do string needle encontrado ou uma matriz vazia se nenhuma correspondência tiver sido encontrada flag caractere r para expressão regular Descrição Para cada entradada de haystack grep procura se pelo menos um string em needle corresponde a um substring Os índices das entradas de haystack onde pelo menos uma entrada foi encontrada são retor nados no argumento row O argumento opcional which fornece o índice do primeiro string de needle encontrado Quando se usa o terceiro parâmetro r needle deve ser substituído por uma expressão regular Então grep vai corresponder a haystack de acordo com as regras regulares expressas Exemplos txtacha correspondência em um string ou em um vetor de strings procura posição de um string em outro string Compara Strings greptxtstrings greptxtstrings Strings rwgreptxtstrings Strings str hatcathhatchathcatccchatatdog grepstrhcatr grepstrhcatr grepstrcatdogr Ver Também strindex 1795 Name isalphanum verifica se os caracteres de um string são alfanuméricos res isalphanumstr Parâmetros str string res matriz de valores booleanos Descrição res isalphanumstr retorna um array de mesmo tamanho que str contendo valores lógicos t true onde os elementos de str são alfanuméricos e f false onde eles não são Exemplos s A1B2C3 isalphanums Ver Também isletter isdigit 1796 Name isascii verifica se um caractere é do tipo 7bit USASCII res isasciistr Parâmetros str string res uma matriz de booleanos Descrição res isasciistr retorna verdadeiro T se c é um código 7bit USASCII entre 0 e 0177 octal inclusive Caso contrário retorna falso F Exemplos isasciicode2str300 isasciicode2str11 letters 115 99 105 108 97 98 isasciiletters asciiletters isasciiscilab Ver Também isalphanum 1797 Name isdigit checa se os caracteres de um string são números entre 0 e 9 res isdigitstr Parâmetros str string res matriz de valores booleanos Descrição res isdigitstr retorna um array com mesmo tamanho que str com valores T verdadeiro onde os elementos de str são dígitos de 0 a 9 e F falso onde eles não são Exemplos s A1B2C3 isdigits Ver Também isalphanum isletter 1798 Name isletter verifica se os caracteres de um string são letras do alfabeto res isletterstr Parâmetros str string res matriz de booleanos Descrição res isletterstr retorna um array de mesmo tamanho que str com t verdadeiro onde os elementos de str são letras do alfabeto e f false onde eles não são Exemplos s A1B2C3 isletters Ver Também isalphanum isdigit 1799 Name isnum testa se um string representa um número res isnumstr Parâmetros str um string ou matriz de strings res matriz de booleanos Descrição res isnumstrretorna T se str representa um número Exemplos isnum1 123 1e23 1d23 pi Ver Também isletter isdigit isalphanum Autores PM 1800 Name justify justifica um array de caracteres TjjustifyTopt Parâmetros T matriz de strings Tj matriz de strings O resultado justificado opt opção com possíveis valores r ou right para justificação direita l ou left para justificação esquerda c ou center justificação centrada Descrição justify justifica a coluna de uma matriz de strings de acordo com a opção dada Exemplos t1234xadfdfgdfghfgj 1354556dgf sdfgdsdfsf justifytl justifytc justifytr Ver Também length part 1801 Name length comprimento de um objeto nlengthM Parâmetros M matriz usual ou de polinômios ou de strings ou lista n inteiro ou matriz de inteiros Descrição Para uma matriz usual ou de polinômios n é o inteiro igual ao número de linhas vezes o número de colunas de M Também válido para M uma matriz de booleanos Para matrizes de strings e em particular para um string length retorna em n os comprimentos das entradas da matriz de strings M O comprimento de uma lista é o número de elementos da lista também dado por size length123 é 3 length1234 is 4 AVISO length para matrizes esparsas retorna o máximo das dimensões não o produto das dimensões exemplo lengthsparseeye122 retorna max122 não 24 Utilize size para matrizes esparsas Exemplos length123 456 lengtholá mundoSCI Ver Também size 1802 Name part extração de strings stringsout partstringsin v Parâmetros stringsin stringsout matriz de strings v vetor linha de inteiros Descrição Seja sk o caractere k do string s ou o espaço em branco se k lengths part retorna stringsout uma matriz de strings tal que stringsoutij é o string sv1svn sstringsinij Exemplos retorna caracteres da posição 8 a 11 partComo usar part 811 retorna caracteres da posição 2 a 4 para cada elemento caractere inexistente substituído por c partaabcabcd24 retorna o caractere da posição 1 para cada elemento e adiciona caracteres da posição 4 a 7 de cada elemento c partabcdefghijklmnopqrstu147 retorna o caractere 4 para cada elemento adiciona caracteres da posição 1 a 7 e adiciona o caractere da posição 4 para cada elemento c partabcdefghijklmnopqrstu4174 retorna o caractere da posição 1 adiciona de novo o caractere da posição 1 e o caractere da posição 2 cpartaabcabcd112 a a a partaabcabcd1 aa aa aa partaabcabcd11 aa aab aab partaabcabcd112 Ver Também string length 1803 Name regexp acha um string que corresponde ao string de expressão regular startregexpinputpatternflag startendmatchregexpinputpatternflag startendregexpinputpatternflag startendmatchregexpinputpatternflag Parâmetros input string pattern string sob regras de expressão regular start o índice de início de cada substring de str que corresponde ao padrão do string de expressão regular end o índice de fim de cada substring de str que corresponde ao padrão do string de expressão regular match o texto de cada substring de que corresponde a pattern flag o para correspondência com padrão uma vez Descrição As regras de expressão regular são similares às da linguagem Perl Para uma introdução rápido veja httpperldocperlorgperlrequickhtml Para um tutorial mais profundo veja httpperldocperlorg perlretuthtml e para página de referência veja httpperldocperlorgperlrehtml Uma diferença para Perl é que correspondência entre posições mas não entre caracteres por exemplo com ou o é uma correspondência válida em Perl mas não em Scilab Exemplos regexpxabyabbbzabo regexpaa041 regexpABCCabci regexpABCabcdi a b cregexpXABYABBBZabi Ver Também strindex 1804 Name sci2exp converte uma expressão para um string tsci2expa nam lmax Parâmetros a expressão Scilab Pode ser constante polinomial matriz de strings lista matriz de booleanos nam string t vetor de strings contém a expressão ou a instrução de simulação lmax inteiro contém o comprimento de linha máximo O valor padrão é 90 lmax0 indica ausência de controle de comprimento de linha um único string é retornado Descrição sci2exp converte expressão para um string de instrução se nam for fornecido ou para um string de expressão Exemplos a1 23 4 sci2expaaa sci2expaaa0 sci2expssrand222 sci2exppoly1 0 3 4sfi 1805 Name str2code retorna códigos scilab inteiros associados aos caracteres do string cstr2codestr Parâmetros str um string c um vetor de códigos de caracteres inteiros Descrição Retorna c tal que ci é o código scilab inteiro de partstri Exemplos str2codeScilab code2str28 12 18 21 10 11 Ver Também code2str ascii 1806 Name strcat concatena strings txtstrcatvectorofstrings stringadded txtstrcatvectorofstrings stringaddedflag Parâmetros vectorofstrings vetor de strings stringadded string adicionado o valor padrão é emptystr txt string flag string r para retornar uma matriz coluna c para retornar uma matriz linha Descrição txtstrcatvectorofstrings concatena strings txtvectorofstrings1vectorofstringsn txtstrcatvectorofstringsstringadded retorna txtvectorofstrings1stringaddedstringadded vectorofstringsn O símbolo de mais faz o mesmo ab é o mesmo que strcatab Se o tamanho de vectorofstrings for um retorna txtvectorofstrings1 strcatAB retorna A não AB como strcatAB Exemplos strcatstring110 strcatab strcatab strcatA strcatAB strcatAB strcatAB Ver Também string strings 1807 Name strchr acha a primeira ocorrência de um caractere em um string res strchrhaystackchar Parâmetros haystack string ou matriz de strings char caractere res string ou matriz de strings Descrição res strchrhaystackchar retorna a primeira ocorrência do caractere no string str num deve ter as mesmas dimensões que haystack ou apenas um caractere Exemplos strchrEste é um string de amostras strchrEste é um string de amostrano scilabs strchrEste é um string de amostrano scilabsa Ver Também strrchr strstr 1808 Name strcmp compara strings res strcmpstringonestringtwoi Parâmetros stringone string ou matriz de strings stringtwo string ou matriz de strings i parâmetro para realização de stricmp caso independente o valor padrão é s res matrix Descrição res strcmpstringonestringtwo retorna um valor inteiro indicando a relação entre os strings Um valor maior que zero indica que o primeiro caractere não correspondente possui valor maior em stringone que em stringtwo Um valor abaixo de zero indica o contrário Exemplos TXT1 scilabSciLabStrcmpSTRcmp TXT2 ScIlAbsciLabsTrCmPStrCMP strcmpTXT1TXT2 strcmpTXT1scilab strcmpTXT1SciLab strcmpTXT1TXT2i Ver Também strcat strcmpi 1809 Name strcmpi compara strings caso independente res strcmpistringonestringtwo Parâmetros stringone string ou matriz de strings stringtwo string ou matriz de strings res matriz Descrição res strcmpistringonestringtwo retorna um valor inteiro indicando a relação entre os strings Um valor inteiro maior que zero indica que o primeiro caractere que não corresponde possui valor maior em stringone que em stringtwo Um valor negativo indica o contrário Exemplos TXT1 scilabSciLabStrcmpSTRcmp TXT2 ScIlAbsciLabsTrCmPStrCMP strcmpiTXT1TXT2 strcmpiTXT1scilab Ver Também strcat strcmp 1810 Name strcspn retorna extensão até um caractere em um string res strcspnstringonestringtwo Parâmetros stringone string ou matriz de strings stringtwo string ou matriz de strings res matriz Descrição res strcspnstringonestringtwo lê stringone para a primeira ocorrência de qualquer caractere que esteja em stringtwo retornando o número de caracteres de stringone lidos antes da primeira ocorrência stringone deve ter as mesmas dimensões que stringtwo ou stringone deve ser um string Exemplos strcspnfcba731234567890 strcspnfcba73f7cba731234567890 strcspnfcba73f7cba7331234567890 Ver Também strspn 1811 Name strindex procura posição de um string em outro indstrindexhaystackneedleflag indwhichstrindexhaystackneedleflag Parâmetros haystack string O string onde se procurará por ocorrências de needle needle string ou vetor de strings Os strings a serem procurados em haystack ind vetor de índices which vetor de índices flag string r para expressão regular Descrição strindex procura índices onde needle i é encontrado em haystack Para cada k existe um i tal que parthaystackindk0lengthneedlei1 é o mesmo string que needlei Se o argumento which for requerido ele contém esses i Quando se usa o terceiro parâmetro r needle deve ser um string de expressão regular Então strindex irá corresponder a haystack de acordo com as regras regulares expressas strindex sem expressão regular é baseado no algoritmo de KnuthMorrisPratt Este algoritmo é mais poderoso que aquele usado no Scilab 4x Em alguns casos especiais o resultado pode ser diferente Exemplo Scilab 5x kwstrindexaabaab w 1 1 2 k 1 2 2 scilab 4x kwstrindexaabaab w 1 1 k 1 2 As regras de expressão regular são similares às da linguagem Perl Para uma introdução rápida ver httpperldocperlorgperlrequickhtml Para um tutorial mais profundo ver httpperldocperlorg perlretuthtml e para a página de referência ver httpperldocperlorgperlrehtml Exemplos strindex 1812 kstrindexSCIdemosscicos kstrindexSCIdemosscicosSCI kstrindexSCIdemosscicos kstrindexaaaaaaa kstrindexSCIdemosscicosSCIsci kwstrindex13abc233 kstrindex2 21 r Ver Também string strings regexp strsubst 1813 Name string conversão para string cadeia de caracteres stringx outintextstringx Parâmetros x matriz de reais ou função Descrição Converte uma matriz em uma matriz de strings Se x é uma função outintextstringx retorna três vetores de strings out é o vetor de variáveis de saída in é o vetor de variáveis de entrada e text é o vetor coluna do código fonte da função Se x é uma variável lib bibiloteca text é um vetor coluna de strings O primeiro elemento contém o endereço do arquivo biblioteca e o outro o nome da função que ela define Strings são definidos como string entre aspas simples ou string entre aspas duplas matrizes de strings são definidas como matrizes de constantes Concatenação de strings é feita pela operação Exemplos stringrand22 deffymymacroxyx1 outintextstringmymacro x123356 Result is stringx dispstringt dispstringi1 dispstringint16123 dispstring1ss3 Ver Também part length quote evstr execstr strsubst strcat strindex sci2exp 1814 Name strings objeto Scilab strings cadeias de caracteres Descrição Strings são definidos como string entre aspas simples ou string entre aspas duplas matrizes de strings são definidascomo matrizes constantes como de uso A concatenação de dois strings é feita por string1string2 Exemplos estaé uma matriz2x2 matrixmatrix Ver Também part length strcat 1815 Name stripblanks retira espaços em branco e tabulações no início ou no fim de strings txtstripblankstxttabs Parâmetros txt um string ou uma matriz de strings tabs se TRUE retira também tabulações o valor padrão é FALSE Descrição stripblanks retira espaços em branco e tabulações no início ou no fim de strings Exemplos a 123 a stripblanksa a 123 xyz strcatstripblanksa 1816 Name strncpy copia caracteres de strings res strncpystr1num Parâmetros str1 string ou matriz de strings num matriz Números máximos de caracteres a serem copiados da fonte res string ou matriz de strings Descrição res strncpystr1num copia os primeiros num caracteres da fonte para o destino num deve ter as mesmas dimensões que str1 ou deve ser um número Exemplos strncpyscilab3 strncpyscilabSciLabstrncpystrstr3 strncpyscilabSciLabstrncpystrstr1234 Ver Também strcat strcmp 1817 Name strrchr acha a última ocorrência de um caractere em um string res strrchrstr1char Parâmetros str1 string ou matriz de strings char caractere res string ou matriz de strings Descrição res strrchrstr1char retorna a última ocorrência de caractere no string str num deve ter as mesmas dimensões que str1 ou apenas um caracteres char Exemplos strrchrEste e um string de amostras strrchrEste e um string de amostrano scilabs strrchrEste e um string de amostrano scilabsa Ver Também strchr strstr 1818 Name strrev retorna um string invertido res strrevstr1 Parâmetros str1 um string ou uma matriz de strings res um string ou uma matriz de strings Descrição res strrevstr1 retorna o string em ordem inversa Exemplos rev strrevThis is a simple string strrevrev strrevThis is a simple stringscilab 1819 Name strsplit divide um string em um vetor de strings v strsplitstrind Parâmetros str string ind um vetor de índices estritamente crescentes no intervalo 1 lengthstr1 v o vetor coluna resultante de strings dimensão sizeind1 Descrição v strsplitstrind divide o string str em um vetor de strings nos pontos dados pelos índices em ind após cada caractere apontado pelo índice em ind Exemplos Sstrsplit divide um string em um vetor de strings strsplitS15 25 30 indstrindexS Ver Também strcat tokens Autor S Steer INRIA 1820 Name strspn retorna a extensão do conjunto de caracteres no string res strspnstr1str2 Parâmetros str1 string ou matriz de strings str2 string ou matriz de strings res matriz Descrição res strspnstr1str2 retorna o comprimento da porção inicial de str1 que consiste apenas de caracteres que fazem parte de str2 str2 deve ter as mesmas dimensões que str2 ou str1 pode ser um string Exemplos i strspn129o1234567890 printf O comprimento do numero inicial e d i i strspn129o130o1234567890130o Ver Também strcspn 1821 Name strstr localiza substrings res strstrhaystackneedle Parâmetros haystack string ou matriz de strings needle string ou matriz de strings res string ou matriz de strings Descrição res strstrhaystackneedle retorna uma matriz de strings começando onde da primeira ocorrência de needle em haystack até o fim de haystack ou se needle não é parte de haystack Exemplos strstrEste é um string simplessimples strstrEste é um string simplessamples strstrEste é um string simplesno scilabé strstrEste é um string simplesno scilabumscilab Ver Também strrchr strchr 1822 Name strsubst substitui um string por outro dentro de um string stringoutstrsubststringinsearchStrreplaceStr stringoutstrsubststringinsearchStrreplaceStrflag Parâmetros stringin matriz de strings Os strings nos quais serão procuradas ocorrências de searchStr searchStr string a se procurar em string replaceStr string O string de reposição strout matriz de strings O resultado da substituição em searchStr por replaceStr em string flag string r para expressão regular Descrição strsubst substitui todas as ocorrências de searchStr em string por replaceStr Quando se utiliza o quarto argumento r searchStr deve ser um string de uma expressão regular Então strsubst o fará corresponder com string e substituirá de acordo com a regra expressas regulares Exemplos strsubstSCIdemosscicosSCI strsubstSCIdemosscicos strsubst2 21 0r Ver Também string strings 1823 Name strtod converte um string para um double d strtodstr dendstr strtodstr Parâmetros str string ou matriz de strings d escalar real ou matriz de reais endstr string ou matriz de strings próximo caractere em str após o valor numérico Descrição dendstr strtodstr analisa o string str interpretando o seu conteúdo como um número de ponto flutuante e retorna o seu valor como um real Exemplos strtod123556Este 233 um real de amostra dendstr strtod123556Este 233 um real de amostra strtod123556Este 233 um real de amostra888666 aqui dendstr strtod123556Este 233 um real de amostra888666 aqui 1824 Name strtok divide um string em fichas tokens res strtokstrdelimiters Parâmetros str string delimiters string res string Descrição res strtokstrdelimiters divide str em fichas que são seqüências de caracteres contíguos separados por qualquer um dos caracteres que fazem parte do string delimiters delimiters delimitadores Exemplos TOKENS token strtokUm string de fichas e algumas fichas mais TOKENS TOKENStoken while token token strtok TOKENS TOKENStoken end dispTOKENS Ver Também strrchr strchr 1825 Name tokenpos retorna as posições das fichas token em um string kdftokenposstr delimiter Parâmetros str string O string onde se deve procurar fichas delimiter opcional um caractere ou vetor de caracteres Os delimitadores de fichas kdf matriz de duas colunas a primeira coluna fornece os índices dos primeiros caracteres das fichas a segunda fornece os índices dos últimos caracteres das fichas Descrição kdftokenposstr delimiter busca as fichas inclusas no string str O valor padrão de delimiter é Tab onde Tab é ascii9 Retorna os índices dos primeiros e últimos caracteres de cada ficha encontrada Exemplos strIsto é um string kdftokenposstr firstpartstrkdf11kdf12 Ver Também strindex tokens 1826 Name tokens retorna as fichas tokens de um string Ttokensstr delimiter Parâmetros str string o local de procura dos tokens delimiter opcional um caractere ou um vetor de caracteres Os delimitadores de fichas T vetor coluna de fichas encontradas Descrição Ttokensstr delimiter procura pelos tokens inclusos no string str O padrão de delimiter é Tab onde Tab é ascii9 Exemplos tokensIsto é um string tokensSCIdemosscicos tokensyab2 Ver Também strindex tokenpos 1827 Name tree2code gera a definição ASCII de uma função Scilab txttree2codetreeprettyprint Parâmetros tree uma árvore macro vinda de macr2tree prettyprint valor opcional booleano T o código gerado é identado e embelezado F o código gerado não é embelezado padrão txt um vetor coluna de strings o texto fornecendo as instruções Scilab Descrição Dada uma função Scilab carregada tree retornada por macr2tree tree2code permite gerar nova mente o código Exemplos treemacr2treecosh txttree2codetreeT writeio2txta Ver Também macr2tree Autor VC Parte XXXII Cálculos Formais 1829 Name addf adição simbólica addfab Parâmetros ab strings Descrição addfab retorna a cadeia de caracteres ab Simplificações triviais tais como addf0a ou addf12 são realizadas Exemplos addf01 addf1a addf12 ab Ver Também mulf subf ldivf rdivf eval evstr 1830 Name ldivf divisão simbólica esquerda invertida ldivfdc Descrição Retorna o string cd Simplificações triviais como 1c c são realizadas Exemplos ldivf11 ldivfa0 ldivfax ldivf24 Ver Também rdivf addf mulf evstr 1831 Name mulf multiplicação simbólica mulfdc Descrição Retorna o string cd Simplificações triviais tais como 1c c são realizadas Exemplos mulf1a mulf0a ab Cuidado Ver Também rdivf addf subf 1832 Name rdivf divisão simbólica direitaesquerda rldivfdc Parâmetros dcr strings Descrição Retorna o string cd Simplificações triviais tais como c1 c são realizadas Exemplos ldivfcd ldivf12 ldivfa0 Ver Também ldivf 1833 Name subf subtração simbólica csubfab Parâmetros abc strings Descrição Retorna o string cab Simplificações triviais como subf0a ou subf12 são realizadas Exemplos subf0a subf21 subfa0 Ver Também mulf ldivf rdivf eval evstr Parte XXXIII Data e Hora 1835 Name date retorna string contendo a data corrente dtdate Parâmetros dt a string Descrição dtdate retorna um string contendo a data no formato ddmmmyyyy Exemplos date Ver Também getdate toc tic timer etime 1836 Name etime tempo decorrido e etimet2t1 Parâmetros t2 um vetor com 6 ou 10 valores t1 um vetor com 6 ou 10 valores e número de segundos entre t2 e t1 Descrição t1 e t2 com 10 valores t2 e t1 devem ter o mesmo formato retornado por getdate Neste caso seus terceiro quarto e quinto valores serão ignorados t1 e t2 com 6 valores t2 e t1 devem ter o mesmo formato T Ano Mês Dia Hora Minuto Segundo com Segundo o número de segundos com milisegundos ex 12345 t2 e t1 devem ter o mesmo tamanho t2 e t1 podem ser matrizes com cada linha contendo o formato descrito acima todas as linhas tendo o mesmo formato Exemplos t12004 06 10 17 00 12345 t22004 06 10 17 01 13965 E1etimet2t1 t12004 06 24 162 5 10 17 00 12 345 t22004 06 24 162 5 10 17 01 13 965 E2etimet2t1 Ver Também tic toc getdate datenum datevec Autor VC 1837 Name getdate retorna informação sobre data e hora dtgetdate xgetdates dtgetdatex Parâmetros dt um vetor de inteiros com 10 entradas ver abaixo x um inteiro contendo uma data codificada em segundos a partir de 01011970 Descrição dtgetdate retorna a dada corrente no formato dado abaixo dt1 o ano como um número com o século entre 0000 e 9999 dt2 o mês do ano como um número entre 01 e 12 dt3 o número da semana ISO 8601 como um número entre 01 e 53 dt4 o dia Juliano do ano como um número entre 001 e 366 dt5 especifica o dia da semana como um número decimal entre 1 e 7 com 1 representando domingo dt6 o dia do mês como um número entre 01 e 31 dt7 a hora do dia como um número entre 00 e 23 dt8 o minuto da hora como um número entre 00 e 59 dt9 o segundo do minuto como um número entre 00 e 59 dt10 o milissegundo do segundo como um número entre 000 e 999 xgetdates retorna um escalar com o número de segundos desde 01011970 0000 UTC Convenção de Tempo Unix dtgetdatex põe a data dada por x número de segundos desde 01011970 0000 UTC no formato acima Neste caso dt10 é sempre igual a 0 getdate 1838 Exemplos wgetdate mprintfAnodMêsdDiadw1w2w6 xgetdates getdatex Ver Também date timer Autor VC 1839 Name tic inicia um cronômetro tic Descrição A seqüência de comando tic operation toc imprime o número de segundos requeri dos para a operação Exemplos tic realtimeinit1 realtime0 realtime10 toc Ver Também toc timer etime Autores VC AC 1840 Name toc lê o cronômetro toc t toc Parâmetros t número de segundos desde a última chamada a tic precisão em ordem de milissegundos Descrição A seqüência de comandos tic operation toc imprime o número de segundos re queridos para a operação Exemplos tic realtimeinit1 realtime0 realtime10 toc Ver Também tic timer etime Autores VC AC 1841 Name calendar Calendar ccalendar c calendarym Description c calendar returns a list containing a calendar for the current month The calendar runs Sunday to Saturday c calendarym where y and m are integers returns a calendar for the specified month of the spec ified year Examples calendar calendar19738 See Also datevec datenum Authors Allan CORNET 1842 Name clock Return current time as date vector c clock Description c clock returns a 6element date vector containing the current date and time in decimal form c year month day hour minute seconds the first five elements are integers The seconds element is accurate to several digits beyond the decimal point Examples clock See Also datenum datevec timer etime tic toc Authors PM 1843 Name datenum Convert to serial date number N datenum N datenumDT N datenumY M D N datenumY M D H MI S Description The datenum function converts date vectors defined by datevec into serial date numbers Date num bers are serial days elapsed from some reference date By default the serial day 1 corresponds to 1 Jan0000 N datenum returns the serial date numbers corresponding to current date N datenumDT converts one or more date vectors to serial date number N DT can be an mby6 or mby3 matrix containing m full or partial date vector respectively N datenumY M D returns the serial date numbers for corresponding elements of the Y M and D year month day arrays Y M and D must be arrays of the same size or any can be a scalar N datenumY M D H MI S returns the serial date numbers for corresponding elements of the Y M D H MI and S year month day hour minute and second array valuesY M D H MI and S must be arrays of the same size or any can be a scalar Examples N datenum datenum N datenumDT A 0 1 1 0 0 0 2005 2 8 21 37 30 datenumA N datenumY M D Years 0 1973 2006 Months 1 8 2 Days 1 4 8 datenumYearsMonthsDays Years 0 0 0 0 0 0 Months 1 1 1 1 1 1 Days 1 2 3 4 5 6 datenumYearsMonthsDays N datenumY M D H MI S Years grand510uin02006 Months grand510uin112 Days grand510uin128 Hours grand510uin023 Minutes grand510uin059 Seconds grand510uin059 datenumYearsMonthsDaysHoursMinutesSeconds datenum 1844 See Also datevec calendar Authors AC 1845 Name datevec Date components VdatevecDT YMDHMISdatevecDT Description V datevecDT converts a serial date number defined by datenum to a date vector V having ele ments year month day hour minute second The first five vector elements are integers DT can be an array Y M D H MI S datevecDT returns the components of the date vector as individual variables DT can be an array Examples First example datevec720840 Second example datevecdatenum Third example With integers values A grand1012uin11000000 datevecA Fourth example With real values A grand1012unf11000000 datevecA See Also datenum calendar Authors AC 1846 Name eomday Return last day of month E eomdayY M Description E eomdayY M returns the last day of the year and month given by corresponding elements of arrays Y and M Examples eomday20063 See Also datenum datevec weekday Authors PM 1847 Name now Return current date and time t now Description t now returns date and time as a serial date number See datenum Examples realtimeinit1 realtime0 t1 now datevect1 realtime10 t1 now datevect1 See Also clock datenum datevec Authors PM 1848 Name realtimeinit set time unit realtime set dates origin or waits until date realtimeinittimeunit realtimet Parameters timeunit a real number The number of seconds associated to the realtime argument t a real number A date Description These two functions can be used to handle real time into Scilab realtimeinittimeunit defines the time unit associated to the realtime argument t first call to realtimet0 sets current date to t0 subsequent calls to realtimet wait till date t is reached Examples realtimeinit12sets time unit to half a second realtime0sets current date to 0 for k110realtimekmprintfcurrent time is stringk2sec end next instruction outputs a dot each 2 seconds realtimeinit2 realtime0for k110realtimekmprintf end realtimeinit1realtime0 dtgetdates realtime10 getdatesdt See Also getdate 1849 Name sleep suspend Scilab sleepmilliseconds Description sleep Sleep process for specified number of miliseconds specified by the argument The actual suspension time may be longer because of other activities in the system or because of the time spent in processing the call Examples ticsleep6000toc See Also xpause pause Authors Allan CORNET 1850 Name timer cpu time timer Description Returns the CPU time since the preceding call to timer timer has a time precision of 100 nanoseconds NOTE CPU time is the number of processor cycles used for a computation This is not at all equivalent to realworld time CPU time can be used to compare CPU usage between different programs or functions irrespective of background processes that might slow down the computer Examples timerArand100100timer See Also getdate toc tic etime 1851 Name weekday Return day of week NS weekdayD NS weekdayD form Description NS weekdayD returns the day of the week in numericN and stringS form for a given serial date number or date string D Input argument D can represent more than one date in an array of serial date number NS weekdayD form returns the week in numericN and stringS form where the content of S depends on the form argument If form is long then S countains the full name of the weekday eg Thuesday If form is short then S contains an abbreviated name eg Tue from this table Examples today datenum NS weekdaytoday NS weekdaytodayshort NS weekdaytodaylong See Also datenum datevec weekday Authors PM Parte XXXIV Estatística 1853 Name cdfbet cumulative distribution function Beta distribution PQcdfbetPQXYAB XYcdfbetXYABPQ AcdfbetABPQXY BcdfbetBPQXYA Parameters PQXYAB five real vectors of the same size PQ Q1P The integral from 0 to X of the beta distribution Input range 0 1 Q 1P XY Y1X Upper limit of integration of beta density Input range 01 Search range 01 AB The two parameters of the beta density input range 0 infinity Search range 1D3001D300 Description Calculates any one parameter of the beta distribution given values for the others The beta density is proportional to tA1 1tB1 Cumulative distribution function P is calculated directly by code associated with the following ref erence DiDinato A R and Morris A H Algorithm 708 Significant Digit Computation of the Incomplete Beta Function Ratios ACM Trans Math Softw 18 1993 360373 Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1854 Name cdfbin cumulative distribution function Binomial distribution PQcdfbinPQSXnPrOmpr ScdfbinSXnPrOmprPQ XncdfbinXnPrOmprPQS PrOmprcdfbinPrOmprPQSXn Parameters PQSXnPrOmpr six real vectors of the same size PQ Q1P The cumulation from 0 to S of the binomial distribution Probablility of S or fewer successes in XN trials each with probability of success PR Input range 01 S The number of successes observed Input range 0 XN Search range 0 XN Xn The number of binomial trials Input range 0 infinity Search range 1E300 1E300 PrOmpr Ompr1Pr The probability of success in each binomial trial Input range 01 Search range 01 Description Calculates any one parameter of the binomial distribution given values for the others Formula 26524 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the binomial distribution to the cumulative incomplete beta distribution Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1855 Name cdfchi cumulative distribution function chisquare distribution PQcdfchiPQXDf XcdfchiXDfPQ DfcdfchiDfPQX Parameters PQXnDf four real vectors of the same size PQ Q1P The integral from 0 to X of the chisquare distribution Input range 0 1 X Upper limit of integration of the noncentral chisquare distribution Input range 0 infinity Search range 01E300 Df Degrees of freedom of the chisquare distribution Input range 0 infinity Search range 1E300 1E300 Description Calculates any one parameter of the chisquare distribution given values for the others Formula 26419 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the chisquare distribution to the incomplete distribution Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1856 Name cdfchn cumulative distribution function noncentral chisquare distribution PQcdfchnPQXDfPnonc XcdfchnXDfPnoncPQ DfcdfchnDfPnoncPQX PnonccdfchnPnoncPQXDf Parameters PQXDfPnonc five real vectors of the same size PQ Q1P The integral from 0 to X of the noncentral chisquare distribution Input range 0 11E16 X Upper limit of integration of the noncentral chisquare distribution Input range 0 infinity Search range 01E300 Df Degrees of freedom of the noncentral chisquare distribution Input range 0 infinity Search range 1E300 1E300 Pnonc Noncentrality parameter of the noncentral chisquare distribution Input range 0 infinity Search range 01E4 Description Calculates any one parameter of the noncentral chisquare distribution given values for the others Formula 26425 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to compute the cumulative distribution function Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter The computation time required for this routine is proportional to the noncentrality parameter PNONC Very large values of this parameter can consume immense computer resources This is why the search range is bounded by 10000 From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1857 Name cdff cumulative distribution function F distribution PQcdffPQFDfnDfd FcdffFDfnDfdPQ DfncdffDfnDfdPQF DfdcdffDfdPQFDfn Parameters PQFDfnDfd five real vectors of the same size PQ Q1P The integral from 0 to F of the fdensity Input range 01 F Upper limit of integration of the fdensity Input range 0 infinity Search range 01E300 Dfn Degrees of freedom of the numerator sum of squares Input range 0 infinity Search range 1E300 1E300 Dfd Degrees of freedom of the denominator sum of squares Input range 0 infinity Search range 1E300 1E300 Description Calculates any one parameter of the F distribution given values for the others Formula 2662 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the computation of the cumulative distribution function for the F variate to that of an incomplete beta Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter The value of the cumulative F distribution is not necessarily monotone in either degrees of freedom There thus may be two values that provide a given CDF value This routine assumes monotonicity and will find an arbitrary one of the two values From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1858 Name cdffnc cumulative distribution function noncentral fdistribution PQcdffncPQFDfnDfdPnonc FcdffncFDfnDfdPnoncPQ DfncdffncDfnDfdPnoncPQF DfdcdffncDfdPnoncPQFDfn PnonccdffncPnoncPQFDfnDfd Parameters PQFDfnDfdPnonc six real vectors of the same size PQ Q1P The integral from 0 to F of the noncentral fdensity Input range 011E16 F Upper limit of integration of the noncentral fdensity Input range 0 infinity Search range 01E300 Dfn Degrees of freedom of the numerator sum of squares Input range 0 infinity Search range 1E300 1E300 Dfd Degrees of freedom of the denominator sum of squares Must be in range 0 infinity Input range 0 infinity Search range 1E300 1E300 Pnonc The noncentrality parameter Input range 0infinity Search range 01E4 Description Calculates any one parameter of the Noncentral F distribution given values for the others Formula 26620 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to compute the cumulative distribution function Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter The computation time required for this routine is proportional to the noncentrality parameter PNONC Very large values of this parameter can consume immense computer resources This is why the search range is bounded by 10000 The value of the cumulative noncentral F distribution is not necessarily monotone in either degrees of freedom There thus may be two values that provide a given CDF value This routine assumes monotonicity and will find an arbitrary one of the two values From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1859 Name cdfgam cumulative distribution function gamma distribution PQcdfgamPQXShapeScale XcdfgamXShapeScalePQ ShapecdfgamShapeScalePQX ScalecdfgamScalePQXShape Parameters PQXShapeScale five real vectors of the same size PQ Q1P The integral from 0 to X of the gamma density Input range 01 X The upper limit of integration of the gamma density Input range 0 infinity Search range 01E300 Shape The shape parameter of the gamma density Input range 0 infinity Search range 1E3001E300 Scale The scale parameter of the gamma density Input range 0 infinity Search range 1E3001E300 Description Calculates any one parameter of the gamma distribution given values for the others Cumulative distribution function P is calculated directly by the code associated with DiDinato A R and Morris A H Computation of the incomplete gamma function ratios and their inverse ACM Trans Math Softw 12 1986 377393 Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter The gamma density is proportional to TSHAPE 1 EXP SCALE T From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1860 Name cdfnbn cumulative distribution function negative binomial distribution PQcdfnbnPQSXnPrOmpr ScdfnbnSXnPrOmprPQ XncdfnbnXnPrOmprPQS PrOmprcdfnbnPrOmprPQSXn Parameters PQSXnPrOmpr six real vectors of the same size PQ Q1P The cumulation from 0 to S of the negative binomial distribution Input range 01 S The upper limit of cumulation of the binomial distribution There are F or fewer failures before the XNth success Input range 0 infinity Search range 0 1E300 Xn The number of successes Input range 0 infinity Search range 0 1E300 Pr The probability of success in each binomial trial Input range 01 Search range 01 Ompr 1PR Input range 01 Search range 01 PR OMPR 10 Description Calculates any one parameter of the negative binomial distribution given values for the others The cumulative negative binomial distribution returns the probability that there will be F or fewer failures before the XNth success in binomial trials each of which has probability of success PR The individual term of the negative binomial is the probability of S failures before XN successes and is Choose S XNS1 PRXN 1PRS Formula 26526 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce calculation of the cumulative distribution function to that of an incomplete beta Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1861 Name cdfnor cumulative distribution function normal distribution PQcdfnorPQXMeanStd XcdfnorXMeanStdPQ MeancdfnorMeanStdPQX StdcdfnorStdPQXMean Parameters PQXMeanStd six real vectors of the same size PQ Q1P The integral from infinity to X of the normal density Input range 01 X Upper limit of integration of the normaldensity Input range infinity infinity Mean The mean of the normal density Input range infinity infinity Sd Standard Deviation of the normal density Input range 0 infinity Description Calculates any one parameter of the normal distribution given values for the others A slightly modified version of ANORM from Cody WD 1993 ALGORITHM 715 SPECFUN A Portabel FORTRAN Package of Special Function Routines and Test Drivers acm Transactions on Mathematical Software 19 2232 is used to calulate the cumulative standard normal distribution The rational functions from pages 9095 of Kennedy and Gentle Statistical Computing Marcel Dekker NY 1980 are used as starting values to Newtons Iterations which compute the inverse stan dard normal Therefore no searches are necessary for any parameter For X 15 the asymptotic expansion for the normal is used as the starting value in finding the inverse standard normal This is formula 26212 of Abramowitz and Stegun The normal density is proportional to exp 05 X MEANSD2 From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1862 Name cdfpoi cumulative distribution function poisson distribution PQcdfpoiPQSXlam ScdfpoiSXlamPQ XlamcdfpoiXlamPQS Parameters PQSXlam four real vectors of the same size PQ Q1P The cumulation from 0 to S of the poisson density Input range 01 S Upper limit of cumulation of the Poisson Input range 0 infinity Search range 01E300 Xlam Mean of the Poisson distribution Input range 0 infinity Search range 01E300 Description Calculates any one parameter of the Poisson distribution given values for the others Formula 26421 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the computation of the cumulative distribution function to that of computing a chisquare hence an incomplete gamma function Cumulative distribution function P is calculated directly Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter From DCDFLIB Library of Fortran Routines for Cumulative Distribution Functions Inverses and Other Parameters February 1994 Barry W Brown James Lovato and Kathy Russell The University of Texas 1863 Name cdft cumulative distribution function Students T distribution PQcdftPQTDf TcdftTDfPQ DfcdftDfPQT Parameters PQTDf six real vectors of the same size PQ Q1P The integral from infinity to t of the tdensity Input range 01 T Upper limit of integration of the tdensity Input range infinity infinity Search range 1E150 1E150 DF Degrees of freedom of the tdistribution Input range 0 infinity Search range 1e300 1E10 Description Calculates any one parameter of the T distribution given values for the others Formula 26527 of Abramowitz and Stegun Handbook of Mathematical Functions 1966 is used to reduce the computation of the cumulative distribution function to that of an incomplete beta Computation of other parameters involve a seach for a value that produces the desired value of P The search relies on the monotinicity of P with the other parameter 1864 Name center center scenterx scenterxr or scenterx1 scenterxc or scenterx2 Parameters x real or complex vector or matrix Description This function computes s the centred version of the numerical matrix x For a vector or a matrix x scenterx returns in the ij coefficient of the matrix s the value xijxbar where xbar is the mean of the values of the coefficients of x scenterxr or equivalently scenterx1 is the rowwise center reduction of the values of x It returns in the entry sij the value xijxbarvjj with xbarvj the mean of the values of the j column scenterxc or equivalently scenterx2 is the columnwise center reduction of the values of x It returns in the entry sij the value xijxbarhi with xbarhi the mean of the values of the i row Examples x02113249 00002211 06653811 07560439 03303271 06283918 scenterx scenterxr scenterxc See Also wcenter Authors Carlos Klimann 1865 Name wcenter center and weight swcenterx swcenterxr or swcenterx1 swcenterxc or swcenterx2 Parameters x real or complex vector or matrix Description This function computes s the weigthed and centred version of the numerical matrix x For a vector or a matrix x swcenterx returns in the ij coefficient of the matrix s the value xijxbarsigma where xbar is the mean of the values of the coefficients of x and sigma his standard deviation swcenterxr or equivalently swcenterx1 is the rowwise centre reduction of the values of x It returns in the entry sij the value xijxbarvjsigmavj with xbarvj the mean of the values of the j column and sigmavj the standard deviation of the j column of x swcenterxc or equivalently swcenterx2 is the columnwise centre reduction of the values of x It returns in the entry sij the value xijxbarhisigmahi with xbarhi the mean of the values of the i row and sigmahi the standard deviation of the i row of x Examples x02113249 00002211 06653811 07560439 03303271 06283918 swcenterx swcenterxr swcenterxc See Also center Authors Carlos Klimann 1866 Name cmoment central moments of all orders momcmomentxord momcmomentxordr or momcmomentxord1 momcmomentxordc or momcmomentxord2 Parameters x real or complex vector or matrix ord positive integer Description cmomentxord is the central moment or order ord of the elements of x If a third argument of type string r or 1 or c or 2 is used we get in the first case a row vector mom such that momj contains the central moment of order ord of the j column of x cmomentxordc is used in the same way for the central moments in the rows References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples x02113249 00002211 06653811 07560439 03303271 06283918 momcmomentx3 momcmomentx2r momcmomentx3c See Also sum median stdeviation mean meanf moment nanmean nanmeanf stdev stdevf variance variancef nanstdev Authors Carlos Klimann 1867 Name correl correlation of two variables rhocorrelxyfre Parameters x real or complex vector y real or complex vector fre matrix of type lengthx x lengthy Description correlxyfre computes the correlation of two variables x and y fre is a matrix of dimen sions lengthx x lengthy In fre the element of indices ij corresponds to the value or number or frequences of xiyj References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples x25 75 125 175 h0 1 2 fre03 12 0702 13 1101 13 1401 09 14 rhocorrelxhfre See Also covar Authors Carlos Klimann 1868 Name covar covariance of two variables scovarxyfre Parameters x real or complex vector y real or complex vector fre matrix of type lengthx x lengthy Description covarxyfre computes the covariance of two variables x and y fre is a matrix of dimensions lengthx x lengthy In fre the element of indices ij corresponds to the value or number or fre quences of xiyj References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples x10 20 30 40 y10 20 30 40 fre20 04 01 0 10 36 09 0 0 05 10 0 0 0 0 05 scovarxyfre Authors Carlos Klimann 1869 Name ftest Fischer ratio fftestsamples fpftestsamples Parameters samples real or complex matrix of type nr X nc Description fftestsamples computes the Fischer ratio of the nc samples whose values are in the columns of the matrix samples Each one of these samples is composed of nr values The Fischer ratio is the ratio between nr times the variance of the means of samples and the mean of variances of each sample fpftestsamples gives in p the pvalue of the computed Fischer ratio f References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples samples46 55 54 53 54 50 49 58 51 50 61 51 46 52 49 fpftestsamples See Also ftuneq Authors Carlos Klimann 1870 Name ftuneq Fischer ratio for samples of unequal size fftuneqsample1sample2sample3 fpftuneqsample1sample2sample3 Parameters sample1 sample2 sample3 real or complex matrix of any type Description This function computes the F ratio for samples of unequal size The most efficient design is to make all samples the same size n However when this is nor feasible it still is possible to modify the ANOVA calculations Note that the definition of xbarbar is no longer meanxbar but rather a weighted average with weights ni Additionnally it gives in p the pvalue of the computed Fischer ratio Given a number a of samples each of them composed of ni i from 1 to a observations this fonction computes in f the Fischer ratio it is the ratio between nr times the variance of the means of samples and the mean of the variances of each sample fftestsamples computes the Fischer ratio of the nc samples whose values are in the columns of the matrix samples Each one of these samples is composed of nr values The Fischer ratio is the ratio between nr times the variance of the means of samples and the mean of variances of each sample fpftestsamples gives in p the pvalue of the computed Fischer ratio f References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples samples46 55 5453 54 50 49 58 5150 61 5146 52 49 fpftestsamples See Also ftuneq Authors Carlos Klimann 1871 Name geomean geometric mean gmgeomeanx gmgeomeanxror equivalently gmgeomeanx1 gmgeomeanxcor equivalently gmgeomeanx2 Parameters x real or complex vector or matrix Description This function computes the geometric mean of a vector or matrix x For a vector or matrix x gmgeomeanx returns in scalar gm the geometric mean of all the entries of x gmgeomeanxr or equivalently gmgmeanx1 returns in each entry of the row vector gm the geometric mean of each column of x gmgeomeanxc or equivalently gmgmeanx2 returns in each entry of the column vector gm the geometric mean of each row of x Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1872 Name harmean harmonic mean hmharmeanx hmharmeanxror equivalently hmharmeanx1 hmharmeanxcor equivalently hmharmeanx2 Parameters x real or complex vector or matrix Description This function computes the harmonic mean of a vector or matrix x For a vector or matrix x hmharmeanx returns in scalar hm the harmonic mean of all the entries of x hmharmeanxr or equivalently hmharmeanx1 returns in each entry of the row vector hm the harmonic mean of each column of x hmharmeanxc or equivalently hmharmeanx2 returns in each entry of the column vector hm the harmonic mean of each row of x Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1873 Name iqr interquartile range qiqrx qiqrxr or equivalently qiqrx1 qiqrxc or equivalently qiqrx2 Parameters x real or complex vector or matrix Description This function computes the interquartile range IQR upper quartile lower quartile of a vector or a matrix x For a vector or a matrix x qiqrx returns in the scalar q the interquartile range of all the entries of x qiqrxr or equivalently qiqrx1 is the rowwise interquartile range It returns in each entry of the row vector q the interquartile range of each column of x qiqrxc or equivalently qiqrx2 is the columnwise interquartile range It returns in each entry of the column vector q the interquartile range of each row of x Authors Carlos Klimann Bibliography Wonacott THWonacott RJ Introductory Statistics JWileySons 1990 1874 Name labostat Statistical toolbox for Scilab Contents centre centering variables centrered centering and reducing variables cmoment central moments of all orders correl correlation covar covariance ftest fischer test and his pvalue geomean geometric mean harmean harmonic mean iqr interquartile range mad mean absolute deviation meanf arithmetic mean of a vector or matrix with a table of frequences median 50th percentile of a sample mn arithmetic mean of a vector or matrix moment moments of all orders msd mean squared deviation mvvacov multivariable matrix of variancecovariance nand2mean estimate of the difference of means of two independent samples nanmax maximum ignoring NaNs nanmean mean ignoring NaNs nanmeanf mean with frequency table ignoring NaNs nanmedian 50th percentile of a sample ignoring NaNs nanmin minimum ignoring NANs nanstdev standard deviation ignoring NaNs nanstdevf standard deviation with frequency table ignoring NaNs nansum sum ignoring NaNs nfreq frequency of the values of a sample pca principal component analysys pctl vector of percentiles of a sample in decreasing order perctl vector of percentiles of a sample in decreasing order quart quartils stdev standard deviation stdevf standard deviation with frequences strange distance between largest and smallest value tabul frequences of values var variance varf variance with frequence table References Wonacott TH Wonacott RJ Introductory Statistics 5th edition JWiley Sons 1990 Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 1875 Name mad mean absolute deviation s2madx s2madxr or s2madx1 s2madxc or s2madx2 Parameters x real or complex vector or matrix Description This function computes the mean absolute deviation of a real or complex vector or matrix x For a vector or matrix x s2madx returns in scalar s2 the mean absolute deviation of all the entries of x s2madxr or equivalently s2madx1 returns in each entry of the column vector s2 the mean absolute deviation of each column of x s2madxc or equivalently s2madx2 returns in each entry of the column vector s2 the mean absolute deviation of each row of x Bibliography Reference Wonacott TH Wonacott RJ Introductory Statistics 5th edition John Wiley 1990 1876 Name mean mean row mean column mean of vectormatrix entries ymeanx ymeanxr ymeanxc ymeanxm Parameters x real vector or matrix y scalar or vector Description For a vector or a matrix x ymeanx returns in the scalar y the mean of all the entries of x ymeanxr or equivalently ymeanx1 is the rowwise mean It returns a row vector yj meanxj ymeanxc or equivalently ymeanx2 is the columnwise mean It returns a column vector yi meanxi ymeanxm is the mean along the first non singleton dimension of x for compatibility with Matlab Examples A1210771701 meanA meanAr meanAc Amatrix11211232 in this case meanAm is equivalent to meanA3 the first non singleton dimension of A ymeanAm See Also sum median stdeviation 1877 Name meanf weighted mean of a vector or a matrix mmeanfvalfre mmeanfvalfrer or mmeanfvalfre1 mmeanfvalfrec or mmeanfvalfre2 Parameters Description This function computes the mean of a vector or matrix x For a vector or matrix x mmnx re turns in scalar m the mean of all the entries of x mmnxr or equivalently mmnx1 returns in each entry of the row vector m the mean of each column of x mmnxc or equivalently mmnx2 returns in each entry of the column vector m the mean of each row of x Examples x02113249 00002211 0665381107560439 03303271 06283918 mmeanfxrandx mmeanfx10 10 101 1 1r mmeanfx10 10 101 1 1c Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1878 Name median median row median column median of vectormatrixarray entries ymedianx ymedianxr ymedianxc ymedianxm ymedianxdim Parameters x real vector matrix or an array y scalarvector matrix or an array dim positive integer Description For a vector or a matrix x ymedianx returns in the scalar y the median of all the entries of x ymedianxr or equivalently ymedianx1 is the median along the row index It returns in each entry of the column vector y the median of each column of x ymedianxc or equivalently ymedianx2 is the median along the column index It returns in each entry of the row vector y the median of each row of x ymedianxm is the median along the first non singleton dimension of x for compatibility with matlab ymedianxdim is the median along the dimension dim of x for compatibility with matlab Examples A1210771701 medianA medianAr medianAc Amatrix9 3 8 6 74 39 12 6 89 23 65 34232 medianA3 medianAm See Also sum mean 1879 Name moment non central moments of all orders mommomentxord mommomentxordr or mommomentxord1 mommomentxordc or mommomentxord2 Parameters x real or complex vector or matrix ord positive integer Description momentxord is the non central moment or order ord of the elements of x If a third argument of type string r or 1 or c or 2 is used we get in the first case a row vector mom such that momj contains the non central moment of order ord of the j column of x momentxordc is used in the same way for the non central moments in the rows Examples x02113249 00002211 0665381107560439 03303271 06283918 mommomentx3 mommomentx2r mommomentx3c Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1880 Name msd mean squared deviation ymsdx ymsdxr or mmsdx1 ymsdxc or mmsdx2 Parameters x real or complex vector or matrix Description This function computes the mean squared deviation of the values of a vector or matrix x For a vector or a matrix x ymsdx returns in the scalar y the mean squared deviation of all the entries of x ymsdxr or equivalently ymsdx1 is the rowwise mean squared deviation It returns in each entry of the row vector y the mean squared deviation of each column of x ymsdxc or equivalently mmsdx2 is the columnwise mean squared deviation It returns in each entry of the column vector y the mean squared deviation of each row of x Examples x02113249 00002211 0665381107560439 03303271 06283918 mmsdx mmsdxr mmsdxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1881 Name mvvacov computes variancecovariance matrix vmvvacovx Parameters x real or complex vector or matrix Description This function computes v the matrix of variancecovariance of the tableau x x is a numerical matrix nxp who gives the values of p variables for n individuals the ij coefficient of v is vijExixibar xjxjbar where E is the first moment of a variable xi is the ith variable and xibar the mean of the xi variable Examples x02113249 00002211 0665381107560439 04453586 06283918 vmvvacovx Authors Carlos Klimann Bibliography Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 Mar dia KV Kent JT Bibby JM Multivariate Analysis Academic Press 1979 1882 Name nancumsum Thos function returns the cumulative sum of the values of a matrix s nancumsumxorient Parameters x x is a numerical vector or matrix orient is an optional parameter The possible values are 1 2 r or c s numerical scalar or vector It contains the cumulative sum of the values of x ignoring the NANs Description This function returns in scalar or vector s the cumulative sum of the values ignoring the NANs of a vector or matrix real or complex x This function for a vector or a matrix x snancumsumx or equivalently snancumsumx returns in scalar s the cumulative sum ignoring the NANs of all the entries of x taken columnwise snancumsumxr or equivalently snancumsumx1 returns in the colsx sized vector s the cumulative sum ignoring the NANs of the rows of x sinancumsumxi snancumsumxc or equivalently snancumsumx2 returns in the rowsx sized vector s the cumulative sum ignoring NANs of the columns of x sinancumsumxi For the last two cases if a row or column is in whole composed of NAN the corresponding place of s will contain a NAN Examples a1 2 34 5 6 snancumsuma snancumsumar snancumsumac See Also nansum cumsum Authors Carlos Klimann 1883 Name nand2mean difference of the means of two independent samples difnand2meansample1sample2 difnand2meansample1sample2conf Parameters sample1 real or complex vector or matrix sample2 real or complex vector or matrix conf real scalar between 0 and 1 Description This function computes an estimate dif1 for the difference of the means of two independent sam ples arrays sample1 and sample2 and gives the half amplitude of the range of variability of dif with an indicated confidence level dif2 The choice of the normal or t fonctions as the probability fonc tion depends on the sizes of sample1 and sample2 We suppose that the underlying variances of both populations are equal NAN values are not counted In Labostat NAN values stand for missing values in tables In absence of the confidence parameter a confidence level of 95 is assumed References Wonacott TH Wonacott RJ Introductory Statistics 5th edition JWiley Sons 1990 1884 Name nanmax max ignoring Nans mindexnanmaxx mindexnanmaxxr mindexnanmaxxc Parameters x real or complex vector or matrix Description This function gives for a real or a numerical matrix x his largest element m but ignoring the NANs For x a numerical vector or matrix mnanmaxx returns in scalar m the largest element of x ignoring the NANs The form mindex nanmaxxorient gives in addition of the value of the largest element of x ignoring the NANs in scalar m the index of this element in x as a 2vector mnanmaxxr gives in the 1xsizex2 matrix m the largest elements ignoring the NANs of each column of x If the form mindexnanmaxxr is used the elements of the 1xsizex2 matrix index are the indexes of the largest elements ignoring the NANs of each column of x in the corresponding column mnanmaxxc gives in the sizex2x1 matrix m the largest elements ignoring the NANs of each row of x If the form mindexnanmaxxc is used the elements of the sizex2x1 matrix index are the indexes of the largest elements ignoring the NANs of each row of x in the corresponding row In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 mnanmaxx mnanmaxxr mnanmaxxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1885 Name nanmean mean ignoring Nans mnanmeanval mnanmeanvalr or mnanmeanval1 mnanmeanvalc or mnanmeanval2 Parameters val real or complex vector or matrix Description This function returns in scalar m the mean of the values ignoring the NANs of a vector or matrix val For a vector or matrix val mnanmeanval or mnanmeanval returns in scalar m the mean of all the entries ignoring the NANs of val mnanmeanvalr or equivalently mnanmeanval1 returns in each entry of the row vector m of type 1xsizevalc the mean of each column of val ignoring the NANs mnanmeanfvalc or equivalently mnanmeanval2 returns in each entry of the column vector m of type sizevalcx1 the mean of each row of val ignoring the NANs In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 mnanmeanx mnanmeanx1 mnanmeanx2 Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1886 Name nanmeanf mean ignoring Nans with a given frequency mnanmeanvalfre mnanmeanvalfrer or mnanmeanvalfre1 mnanmeanvalfrec or mnanmeanvalfre2 Parameters val real or complex vector or matrix fre integer vector or matrix with same dimensions than val Description This function returns in scalar m the mean of the values ignoring the NANs of a vector or matrix val each counted with a frequency signaled by the corresponding values of the integer vector or matrix fre with the same type of val For a vector or matrix val mnanmeanfvalfre or mnanmeanfvalfre returns in scalar m the mean of all the entries ignoring the NANs of val each value counted with the multiplicity indicated by the corresponding value of fre mnanmeanfvalfrer or equivalently mnanmeanfvalfre1 returns in each entry of the row vector m of type 1xsizevalc the mean of each column of val ignoring the NANs each value counted with the multiplicity indicated by the corresponding value of fre mnanmeanfvalfrec or equivalently mnanmeanfvalfre2 returns in each entry of the column vector m of type sizevalcx1 the mean of each row of val ignoring the NANs each value counted with the multiplicity indicated by the corresponding value of fre In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 fre34 12 2512 23 5 mnanmeanfxfre mnanmeanfxfre1 mnanmeanfxfre2 Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1887 Name nanmedian median of the values of a numerical vector or matrix mnanmedianx mnanmedianxr or mnanmedianx1 mnanmedianxc or mnanmedianx2 Parameters x real or complex vector or matrix Description For a vector or a matrix x mnanmedianx returns in the vector m the median of the values ignoring the NANs of vector x mnanmedianxr or equivalently mnanmedianx1 are the rowwise medians It returns in each position of the row vector m the medians of data ignoring the NANs in the corresponding column of x mnanmedianxc or equivalently mnanmedianx2 are the columnwise ma dians It returns in each position of the column vector m the medians of data ignoring the NANs in the corresponding row of x In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 mnanmedianx mnanmedianx1 mnanmedianx2 Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1888 Name nanmin min ignoring Nans mindexnanminx mindexnanminxr mindexnanminxc Parameters x real or complex vector or matrix Description This function gives for a real or a numerical matrix x his largest element m but ignoring the NANs For x a numerical vector or matrix mnanminx returns in scalar m the largest element of x ignoring the NANs The form mindex nanminxorient gives in addition of the value of the largest element of x ignoring the NANs in scalar m the index of this element in x as a 2vector mnanminxr gives in the 1xsizex2 matrix m the largest elements ignoring the NANs of each column of x If the form mindexnanminxr is used the elements of the 1xsizex2 matrix index are the indexes of the largest elements ignoring the NANs of each column of x in the corresponding column mnanminxc gives in the sizex2x1 matrix m the largest elements ignoring the NANs of each row of x If the form mindexnanminxc is used the elements of the sizex2x1 matrix index are the indexes of the largest elements ignoring the NANs of each row of x in the corresponding row In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 mnanminx mnanminxr mnanminxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1889 Name nanstdev standard deviation ignoring the NANs snanstdevx snanstdevxr or mnanstdevx1 snanstdevxc or mnanstdevx2 Parameters x real or complex vector or matrix Description This function computes the standard deviation of the values of a vector or matrix x ignoring the NANs For a vector or a matrix x snanstdevx returns in the scalar s the standard deviation of all the entries of x ignoring the NANs snanstdevxr or equivalently snanstdevx1 is the rowwise standard devi ation It returns in each entry of the row vector s the standard deviation of each column of x ignoring the NANs snanstdevxc or equivalently snanstdevx2 is the columnwise standard devi ation It returns in each entry of the column vector s the standard deviation of each row of x ignoring the NANs In Labostat NAN values stand for missing values in tables Examples x02113249 00002211 06653811 07560439 nan 06283918 03 02 05 snanstdevx snanstdevxr snanstdevxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1890 Name nansum Sum of values ignoring NANs s nansumxorient Parameters x numerical vector or matrix orient nothing or r or 1 c or 2 s Numerical scalar or vector containig the value of the adding operation Description This function returns in s the sum of the values ignoring the NANs of a numerical vector or matrix x For a vector or matrix x snansumx or snansumx returns in scalar s the sum of values of all entries ignoring the NANs of a vector or matrix x snansumxror equivalently snansumx1 returns in each entry of the row vector s of type 1xsizexc the sum of each column of x ignoring the NANs snansumxcor equivalently snansumx2 returns in each entry of the column vector s of type sizexcx1 the sum of each row of x ignoring the NANs For the last two cases if a row or column is in whole composed of NAN the corresponding place of s will contain a NAN Examples x02113249 nan 0665381107560439 03303271 06283918 mnansumx mnansumx1 mnansumx2 See Also nancumsum sum Authors Carlos Klimann Bibliography Wonacott TH and Wonacott RJ Introductory Statistics 5th edition JWiley and Sons 1990 1891 Name nfreq frequence of the values in a vector or matrix mnfreqx Parameters x real or complex vector or matrix Description Frequence of the values in a real or complex vector or a real or complex matrix x For a real or complex vector or a real or complex matrix x mfreqx returns in the first column of the sizexx2 matrix m the values of x and in the second column of this matrix the frequences of the corresponding values Note that the tabul function is more efficient applies also to vector of strings and returns a sorted m Examples x2 8 0 3 7 6 8 7 9 1 mnfreqx See Also tabul dsearch histplot Authors Carlos Klimann 1892 Name pca Computes principal components analysis with standardized variables lambdafacprcomprinc pcax Parameters x is a nxp n individuals p variables real matrix Note that pca center and normalize the columns of x to produce principal components analysis with standardized variables lambda is a p x 2 numerical matrix In the first column we find the eigenvalues of V where V is the correlation p x p matrix and in the second column are the ratios of the corresponding eigenvalue over the sum of eigenvalues facpr are the principal factors eigenvectors of V Each column is an eigenvector element of the dual of Rp comprinc are the principal components Each column ciXui of this n x n matrix is the Morthogonal projection of individuals onto principal axis Each one of this columns is a linear combination of the variables x1 xp with maximum variance under condition ui M1 ui1 Description This function performs several computations known as principal component analysis The idea behind this method is to represent in an approximative manner a cluster of n individuals in a smaller dimensional subspace In order to do that it projects the cluster onto a subspace The choice of the kdimensional projection subspace is made in such a way that the distances in the projection have a minimal deformation we are looking for a kdimensional subspace such that the squares of the distances in the projection is as big as possible in fact in a projection distances can only stretch In other words inertia of the projection onto the k dimensional subspace must be maximal Warning the graphical part of the old version of pca as been removed It can now be performed using the showpca function Examples arand10010n lambdafacprcomprinc pcaa showpcalambdafacpr See Also showpca princomp Authors Carlos Klimann Bibliography Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 1893 Name perctl computation of percentils pperctlxy Parameters x real or complex vector or matrix y vector of positif integer values between 0 and 100 Description Compute the matrix p of percentils in increasing order column first of the real vector or matrix x The percentils are indicated by the entries of y the values of entries of y must be positive integers between 0 and 100 p is a matrix whose type is lengthy x 2 and the content of its first column are the percentils values The contents of its second column are the places of the computed percentiles in the input matrix x The minimum or maximum values in x are assigned to percentiles for percent values outside that range Examples x6 7 0 7 10 4 2 2 7 1 6 0 5 5 5 2 0 6 8 10 8 6 4 3 5 9 8 3 4 7 1 3 2 7 6 1 1 4 8 2 6 3 5 1 6 5 9 9 5 5 1 6 4 4 5 4 0 8 1 8 7 1 3 7 8 0 2 8 10 8 3 6 1 9 8 5 5 3 2 1 5 7 6 2 10 8 7 4 0 8 10 3 3 4 8 6 9 4 8 3 y10 20 30 pperctlxy Authors Carlos Klimann Bibliography HYNDMANRob J and FAN Yanan Sample Quantiles in Statistical Packages The American Statis tician Nov1996 Vol 50 No4 1894 Name princomp Principal components analysis facprcomprinclambdatsquare princompxeco Parameters x is a nbyp n individuals p variables real matrix eco a boolean use to allow economy size singular value decomposition facpr A pbyp matrix It contains the principal factors eigenvectors of the correlation matrix V comprinc a nbyp matrix It contains the principal components Each column of this matrix is the M orthogonal projection of individuals onto principal axis Each one of this columns is a linear combination of the variables x1 xp with maximum variance under condition ui M1 ui1 lambda is a p column vector It contains the eigenvalues of V where V is the correlation matrix tsquare a n column vector It contains the Hotellings T2 statistic for each data point Description This function performs principal component analysis on the nbyp data matrix x The idea behind this method is to represent in an approximative manner a cluster of n individuals in a smaller dimensional subspace In order to do that it projects the cluster onto a subspace The choice of the kdimensional projection subspace is made in such a way that the distances in the projection have a minimal deformation we are looking for a kdimensional subspace such that the squares of the distances in the projection is as big as possible in fact in a projection distances can only stretch In other words inertia of the projection onto the k dimensional subspace must be maximal To compute principal component analysis with standardized variables may use princompwcenterx1 or use the pca function Examples arand10010n facprcomprinclambdatsquare princompa See Also wcenter pca Authors Carlos Klimann princomp 1895 Bibliography Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 1896 Name quart computation of quartiles squartx squartxr or mquartx1 squartxc or mquartx2 Parameters x real or complex vector or matrix Description For a vector or a matrix x qquartxy returns in the vector q the quartiles of x qquartxr or equivalently qquartx1 are the rowwise percentiles It returns in each column of the matrix q the quartiles of data in the corresponding column of x qquartxc or equivalently qquartx2 are the columnwise quartiles It returns in each row of the matrix q the quartiles of data in the corresponding row of x Examples x6 7 0 7 10 4 2 2 7 1 6 0 5 5 5 2 0 6 8 10 8 6 4 3 5 9 8 3 4 7 1 3 2 7 6 1 1 4 8 2 6 3 5 1 6 5 9 9 5 5 1 6 4 4 5 4 0 8 1 8 7 1 3 7 8 0 2 8 10 8 3 6 1 9 8 5 5 3 2 1 5 7 6 2 10 8 7 4 0 8 10 3 3 4 8 6 9 4 8 3 qquartx qquartxr qquartxc Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1897 Name regress regression coefficients of two variables coefsregressxy Parameters xy real or complex vector Description This function computes the regresion coefficients of two variables x and y both numerical vectors of same number of elements n coefsa b be a 1x2 matrix such that YabX will be the equation of the ordinary least square approximation to our data References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Examples x05608486 06623569 07263507 01985144 05442573 02320748 02312237 y03616361 02922267 05664249 04826472 03321719 05935095 05015342 coefsregressxy See Also covar Authors Carlos Klimann 1898 Name sample Sampling with replacement s samplenXorient Parameters n positive integer size of sample X matrix Samples will be extracted from this matrix orient Optional parameter Admissible values are 1 2 r or c s vector or matrix containing sample Description This function gives a vector or matrix nx1 It contains a random sample of n extractions with re placement from the matrix X ssamplenX or ssamplenX returns a vector s whose values are a random sample of n values from X extracted with replacement from X ssamplenXr or equivalently ssamplenX1 returns a matrix of type sizeXrxn It contains a random sample of n rows extracted with replacement from the rows of X ssamplenXc or equivalently ssamplenX2 returns a matrix of type nxsizeXc It contains a random sample of n columns extracted with replacement from the columns of X Examples Xa dd arreu ber car zon ssample25X ssample25Xr ssample25Xc See Also samplef samwr Authors Carlos Klimann 1899 Name samplef sample with replacement from a population and frequences of his values s samplefnXforient Parameters n positive integer size of sample X matrix Samples will be extracted from this matrix f positive integer matrix with same type than X It indicates frequences of corresponding values of X orient Optional parameter Admissible values are 1 2 r or c s vector or matrix containing sample Description This function gives s a vector of lenght n It contains a sample of n extractions with replacement from the vector or matrix X each element counted with the frequence given by the corresponding value in vector f ssamplefnXf or ssamplefnXf returns a vector s whose values are a random sample of n values from X each value with a probability to be sampled proportional to the corresponding value of f extracted with replacement from X f must have same lenght than X ssamplefnXfr or equivalently ssamplefnXf1 returns a matrix of type sizeXrxn It con tains a random sample of n rows from X each row with a probability to be sampled proportional to the corresponding value of f extracted with replacement from the rows of X The lenght of f must be equal to the number of rows of X ssamplefnXfc or equivalently ssamplefnXf2 returns a matrix of type nxsizeXc It contains a random sample of n columns from X each column with a probability to be sampled pro portional to the corresponding value of f extracted with replacement from the columns of X The lenght of f must be equal to the number of columns of X Examples a3 7 922 4 2 f110 1 1 1 1 1 f21 15 f310 1 1 ssamplef15af1 ssamplef15af2r ssamplef15af3c See Also sample samwr Authors Carlos Klimann 1901 Name samwr Sampling without replacement s samwrsizamnumsampX Parameters sizam integer Size of a sample It must be less or equal than size of X numsamp integer Number of samples to be extracted X column vector It contains the population s matrix of type sizsam x numsamp It contains numsamp random samples the columns each of sizam sizeX extractions without replacement from the column vector X Description Gives samples without replacement from a column vector Examples a033 124 21 103 ssamwr412a See Also sample samplef Authors Carlos Klimann 1902 Name showpca Visualization of principal components analysis results showpcalambdafacprN Parameters lambda is a p x 2 numerical matrix In the first column we find the eigenvalues of V where V is the correlation p x p matrix and in the second column are the ratios of the corresponding eigenvalue over the sum of eigenvalues facpr are the principal factors eigenvectors of V Each column is an eigenvector element of the dual of Rp N Is a 2x1 integer vector Its coefficients point to the eigenvectors corresponding to the eigenvalues of the correlation matrix p by p ordered by decreasing values of eigenvalues If N is missing we suppose N1 2 Description This function visualize the pca results Examples arand10010n lambdafacprcomprinc pcaa showpcalambdafacpr See Also pca princomp Authors Carlos Klimann Bibliography Saporta Gilbert Probabilites Analyse des Donnees et Statistique Editions Technip Paris 1990 1903 Name stdeviation standard deviation row or columnwise of vectormatrix entries stdev standard deviation row or columnwise of vectormatrix entries ystdeviationx ystdeviationxr ystdeviationxc ystdevx ystdevxr ystdevxc Parameters x real vector or matrix y scalar or vector Description stdeviation computes the sample standard deviation that is it is normalized by N1 where N is the sequence length For a vector or a matrix x ystdeviationx returns in the scalar y the standard deviation of all the entries of x ystdeviationxr or equivalently ystdeviationx1 is the rowwise stan dard deviation It returns in each entry of the column vector y the standard deviation of each row of x ystdeviationxc or equivalently ystdeviationx2 is the columnwise stdeviation It returns in each entry of the row vector y the standard deviation of each column of x Examples A1210771701 stdeviationA stdeviationAr stdeviationAc See Also sum median mean nanstdev stdevf 1904 Name stdevf standard deviation sstdevfxfre sstdevfxfrer or sstdevfxfre1 sstdevfxfrec or sstdevfxfre2 Parameters x real or complex vector or matrix Description This function computes the standard deviation of the values of a vector or matrix x each of them counted with a frequency given by the corresponding values of the integer vector or matrix fre who has the same type of x For a vector or matrix x sstdevfxfre or sstdevfxfre returns in scalar s the standard deviation of all the entries of x each value counted with the multiplicity indicated by the corresponding value of fre sstdevfxfrer or equivalently sstdevfxfre1 returns in each entry of the row vector s of type 1xsizexc the standard deviation of each column of x each value counted with the multiplicity indicated by the corresponding value of fre sstdevfxfrec or equivalently sstdevfxfre2 returns in each entry of the column vector s of type sizexcx1 the standard deviation of each row of x each value counted with the multiplicity indicated by the corresponding value of fre Examples x02113249 00002211 0665381107560439 09546254 06283918 fre1 2 33 4 3 mstdevfxfre mstdevfxfrer mstdevfxfrec Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1905 Name strange range rstrangex rstrangexr or equivalently rstrangex1 rstrangexc or equivalently rstrangex2 Parameters x real or complex vector or matrix Description The range is the distance between the largest and smaller value rstrangex computes the range of vector or matrix x rstrangexr or equivalently rstrangex1 give a row vector with the range of each column rstrangexc or equivalently rstrangex2 give a column vector with the range of each row References Wonacott TH Wonacott RJ Introductory Statistics JWiley Sons 1990 Authors Carlos klimann 1906 Name tabul frequency of values of a matrix or vector mtabulX order Parameters X vector or matrix of real or complex numbers or strings order optionnal a character equal to d or i default value d m a 2 columns matrix if X is a numerical vector or matrix or a list with 2 members if X is a string vector or matrix Description This function computes the frequency of values of the components of a vector or matrix X of numbers or string characters if X is a numerical vector or matrix then m is a two column matrix who contains in the first column the distinct values of X and in the other column the number of occurrences of those values mi2 is the number of occurrences of mi1 if X is a string vector or matrix then m is a list whose first member is a string column vector composed with the distinct values of X and the second member is a column vector whose components are the number of occurrences of those values mi2 is the number of occurrences of the string mi1 The optional parameter order must be d or i by default orderd and gives the order decreas ing or increasing the distinct values of X will be sorted Examples first example X 2 8 0 3 7 6 8 7 9 1 6 7 7 2 5 2 2 2 9 7 m1 tabulX m2 tabulX i second example X ba baba a A AA a aa aa aa A ba m tabulXi third example n 50000 X grandn1bin7005 m tabulXi clf plot2d3m1 m2n xtitleempirical probabilities of B7005 last example computes the occurrences of words of the scilab license tabul 1907 text readSCIlicensetxt11A read the scilab license bigstr strcattext put all the lines in a big string sep words separators words tokensbigstr sep cut the big string into words m tabulwords computes occurrences of each word occ p gsortm2 sort by decreasing frequencies results m1p stringocc display result See Also dsearch histplot Authors Carlos Klimann original author JS Giet and B Pincon new version Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1908 Name thrownan eliminates nan values nonannumbthrownanx Parameters x real or complex vector or matrix Description This function returns in vector nonan the values ignoring the NANs of a vector or matrix x and in the corresponding places of vector numb the indexes of the value For a vector or matrix x nonannumbthrownanx considers x whatever his dimensions are like a vector columns first In Labostat NAN values stand for missing values in tables Examples x02113249 nan 0665381107560439 03303271 06283918 nonan numbthrownanx Authors Carlos Klimann 1909 Name trimmean trimmed mean of a vector or a matrix mtrimmeanxdiscard flag verbose Parameters x real or complex vector or matrix discard Optional real value between 0 and 100 representing the part of the data to discard It discard is not in the 0100 range an error is generated Default value for discard50 flag Optional string or real parameter which controls the behaviour when x is a matrix Available values for flag are all 1 2 r or c default is flagall The two values flagr and flag1 are equivalent The two values flagc and flag2 are equivalent verbose Optional integer If set to 1 then enables verbose logging Default is 0 Description A trimmed mean is calculated by discarding a certain percentage of the lowest and the highest scores and then computing the mean of the remaining scores For example a mean trimmed 50 is computed by discarding the lower and higher 25 of the scores and taking the mean of the remaining scores The median is the mean trimmed 100 and the arithmetic mean is the mean trimmed 0 A trimmed mean is obviously less susceptible to the effects of extreme scores than is the arithmetic mean It is therefore less susceptible to sampling fluctuation than the mean for extremely skewed distributions The efficiency of a statistic is the degree to which the statistic is stable from sample to sample That is the less subject to sampling fluctuation a statistic is the more efficient it is The efficiency of statistics is measured relative to the efficiency of other statistics and is therefore often called the relative efficiency If statistic A has a smaller standard error than statistic B then statistic A is more efficient than statistic B The relative efficiency of two statistics may depend on the distribution involved For instance the mean is more efficient than the median for normal distributions but not for some extremely skewed distributions The efficiency of a statistic can also be thought of as the precision of the estimate The more efficient the statistic the more precise the statistic is as an estimator of the parameter The trimmed mean is less efficient than the mean for normal distributions For a vector or matrix x ttrimmeanxdiscard returns in scalar t the mean of all the entries of x after discarding discard2 highest values and discard2 lowest values ttrimmeanxdiscardr or equivalently ttrimmeanxdiscard1 returns in each entry of the row vector t the trimmed mean of each column of x ttrimmeanxdiscardc or equivalently ttrimmeanxdiscard2 returns in each entry of the column vector t the trimmed mean of each row of x This function computes the trimmed mean of a vector or matrix x For a vector or matrix x mtrimmeanxdiscard returns in scalar m the trimmed mean of all the entries of x mtrimmeanxr or equivalently mtrimmeanx1 returns in each entry of the row vector m the trimmed mean of each column of x trimmean 1910 mtrimmeanxc or equivalently mtrimmeanx2 returns in each entry of the column vector m the trimmed mean of each row of x Example with x as vector In the following example one computes the trimmed mean of one data vector with the default discard value equals to 50 and verbose logging The data is made of 9 entries The algorithms sorts the vector and keeps only indices from 3 to 7 skipping indices 1 2 8 and 9 The value 4000 which is much larger than the others is not taken into account The computed trimmed mean is therefore 50 data 10 20 30 40 50 60 70 80 4000 computed trimmeandataverbose1 Example with x as matrix In the following example one computes the trimmed mean of one data matrix The chosen discard value is 50 The orientation is r which means that the data is sorted row by row For each column of the matrix one computes a trimmed mean The trimmed mean is the line vector 25 25 25 25 data 10 10 10 10 20 20 20 20 30 30 30 30 4000 4000 4000 4000 computed trimmeandata50orienr References Luis Angel GarciaEscudero and Alfonso Gordaliza Robustness Properties of Means and Trimmed Means JASA Volume 94 Number 447 Sept 1999 pp956969 Trimmed Mean httpdavidmlanecomhyperstatA11971html Authors Carlos Klimann 1911 Name variance variance of the values of a vector or matrix svariancexorienw svariancexr or mvariancex1 svariancexc or mvariancex2 Parameters x real or complex vector or matrix orien the orientation of the computation Valid values or the orien parameter are 1 r 2 and c w w type of normalization to use Valid values are 0 and 1 This depends on the number of columns of x if orien 1 is chosen the number of rows if orien 2 is chosen If w 0 normalizes with m1 provides the best unbiased estimator of the variance this is the default If w 1 normalizes with m this provides the second moment around the mean If no orien option is given the normalization is done with n m 1 where n m is the total number of elements in the matrix Description This function computes the variance of the values of a vector or matrix x For a vector or a matrix x svariancex returns in the scalar s the variance of all the entries of x svariancexr or equivalently svariancex1 is the rowwise variance It returns in each entry of the row vector s the variance of each column of x The generalized formulae is used which manages complex values svariancexc or equivalently svariancex2 is the columnwise standard devi ation It returns in each entry of the column vector s the variance of each row of x The generalized formulae is used which manages complex values Examples x02113249 00002211 0665381107560439 04453586 06283918 svariancex svariancexr svariancexc See Also mtlbvar Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 1912 Name variancef standard deviation of the values of a vector or matrix svariancefxfre svariancefxfrer or svariancefxfre1 svariancefxfrec or svariancefxfre2 Parameters x real or complex vector or matrix Description This function computes the variance of the values of a vector or matrix x each of them counted with a frequency signaled by the corresponding values of the integer vector or matrix fre with the same type of x For a vector or matrix x svariancefxfre or svariancefxfre returns in scalar s the variance of all the entries of x each value counted with the multiplicity indicated by the corresponding value of fre svariancefxfreror equivalently svariancefxfre1 returns in each en try of the row vector s of type 1xsizexc the variance of each column of x each value counted with the multiplicity indicated by the corresponding value of fre svariancefxfrecor equivalently svariancefxfre2 returns in each en try of the column vector s of type sizexc x1 the variance of each row of x each value counted with the multiplicity indicated by the corresponding value of fre Examples x02113249 00002211 0665381107560439 09546254 06283918 fre1 2 33 4 3 mvariancefxfre mvariancefxfrer mvariancefxfrec Authors Carlos Klimann Bibliography Wonacott TH Wonacott RJ Introductory Statistics fifth edition JWiley Sons 1990 Parte XXXV ARnoldi PACKage 1914 Name dnaupd Interface for the Implicitly Restarted Arnoldi Iteration to compute approximations to a few eigenpairs of a real linear operator IDORESIDVIPARAMIPNTRWORKDWORKLINFO dnaupdID0BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLINFO Parameters ID0 Integer INPUTOUTPUT Reverse communication flag IDO must be zero on the first call to dnaupd IDO will be set internally to indicate the type of operation to be performed Control is then given back to the calling routine which has the responsibility to carry out the requested operation and call dnaupd with the result The operand is given in WORKDIPNTR1 the result must be put in WORKDIPNTR2 IDO 0 first call to the reverse communication interface IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y This is for the initialization phase to force the starting vector into the range of OP IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y In mode 3 and 4 the vector B X is already available in WORKDipntr3 It does not need to be recomputed in forming OP X IDO 2 compute Y B X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y IDO 3 compute the IPARAM8 real and imaginary parts of the shifts where INPTR14 is the pointer into WORKL for placing the shifts See Remark 5 below IDO 99 done BMAT Character specifies the type of the matrix B that defines the semiinner product for the operator OP I standard eigenvalue problem Ax lambdax G generalized eigenvalue problem Ax lambdaBx N Integer dimension of the eigenproblem WHICH string of length 2 Specify which of the Ritz values of OP to compute LM want the NEV eigenvalues of largest magnitude SM want the NEV eigenvalues of smallest magnitude LR want the NEV eigenvalues of largest real part SR want the NEV eigenvalues of smallest real part LI want the NEV eigenvalues of largest imaginary part SI want the NEV eigenvalues of smallest imaginary part NEV Integer number of eigenvalues of OP to be computed 0 NEV N1 dnaupd 1915 TOL scalar Stopping criterion the relative accuracy of the Ritz value is considered acceptable if BOUNDSI TOLABSRITZI If TOL 0 is passed the machine precision is set RESID array of length N INPUTOUTPUT On INPUT If INFO0 a random initial residual vector is used else RESID contains the initial residual vector possibly from a previous run On OUTPUT RESID contains the final residual vector NCV Integer number of columns of the matrix V NCV must satisfy the two inequalities 2 NCV NEV and NCV N This will indicate how many Arnoldi vectors are generated at each iteration After the startup phase in which NEV Arnoldi vectors are generated the algorithm generates approximately NCVNEV Arnoldi vectors at each subsequent update iteration Most of the cost in generating each Arnoldi vector is in the matrixvector operation OPx NOTE 2 NCVNEV in order that complex conjugate pairs of Ritz values are kept together See remark 4 below V N by NCV array Contains the final set of Arnoldi basis vectors IPARAM array of length 11 INPUTOUTPUT IPARAM1 ISHIFT method for selecting the implicit shifts The shifts selected at each iteration are used to restart the Arnoldi iteration in an implicit fashion ISHIFT 0 the shifts are provided by the user via reverse communication The real and imaginary parts of the NCV eigenvalues of the Hessenberg matrix H are returned in the part of the WORKL array corresponding to RITZR and RITZI See remark 5 below ISHIFT 1 exact shifts with respect to the current Hessenberg matrix H This is equivalent to restarting the iteration with a starting vector that is a linear combination of approximate Schur vectors associated with the wanted Ritz values IPARAM2 LEVEC No longer referenced IPARAM3 MXITER On INPUT maximum number of Arnoldi update iterations allowed On OUTPUT actual number of Arnoldi update iterations taken IPARAM4 NB blocksize to be used in the recurrence The code currently works only for NB 1 IPARAM5 NCONV number of converged Ritz values This represents the number of Ritz values that satisfy the convergence criterion IPARAM6 IUPD No longer referenced Implicit restarting is ALWAYS used IPARAM7 MODE On INPUT determines what type of eigenproblem is being solved Must be 1234 See under Description of dnaupd for the five modes available IPARAM8 NP When ido 3 and the user provides shifts through reverse communication IPARAM10 dnaupd returns NP the number of shifts the user is to provide dnaupd 1916 0 NP NCVNEV See Remark 5 below IPARAM9 NUMOP IPARAM10 NUMOPB IPARAM11 NUMREO On OUTPUT NUMOP total number of OPx operations NUMOPB total number of Bx operations if BMATG NUMREO total number of steps of reorthogonalization IPNTR array of length 14 Pointer to mark the starting locations in the WORKD and WORKL arrays for matricesvectors used by the Arnoldi iteration IPNTR1 pointer to the current operand vector X in WORKD IPNTR2 pointer to the current result vector Y in WORKD IPNTR3 pointer to the vector B X in WORKD when used in the shiftandinvert mode IPNTR4 pointer to the next available location in WORKL that is untouched by the program IPNTR5 pointer to the NCV by NCV upper Hessenberg matrix H in WORKL IPNTR6 pointer to the real part of the ritz value array RITZR in WORKL IPNTR7 pointer to the imaginary part of the ritz value array RITZI in WORKL IPNTR8 pointer to the Ritz estimates in array WORKL associated with the Ritz values lo cated in RITZR and RITZI in WORKL IPNTR14 pointer to the NP shifts in WORKL See Remark 5 below Note IPNTR913 is only referenced by dneupd See Remark 2 IPNTR9 pointer to the real part of the NCV RITZ values of the original system IPNTR10 pointer to the imaginary part of the NCV RITZ values of the original system IPNTR11 pointer to the NCV corresponding error bounds IPNTR12pointer to the NCV by NCV upper quasitriangular Schur matrix for H IPNTR13 pointer to the NCV by NCV matrix of eigenvectors of the upper Hessenberg matrix H Only referenced by dneupd if RVEC 1 See Remark 2 below WORKD Double precision work array of length 3N REVERSE COMMUNICATION Distributed array to be used in the basic Arnoldi iteration for reverse communication The us er should not use WORKD as temporary workspace during the iteration Upon termination WORKD1N contains BRESID1N If an invariant subspace associated with the converged Ritz values is desired see remark 2 below subroutine dneupd uses this output See Data Distri bution Note below WORKL work array of length at least 3NCV2 6NCV OUTPUTWORKSPACE Private replicat ed array on each PE or array allocated on the front end See Data Distribution Note below INFO Integer INPUTOUTPUT If INFO 0 a randomly initial residual vector is used else RESID contains the initial residual vector possibly from a previous run dnaupd 1917 Error flag on output 0 Normal exit 1 Maximum number of iterations taken All possible eigenvalues of OP has been found IPARAM5 returns the number of wanted converged Ritz values 2 No longer an informational error Deprecated starting with release 2 of ARPACK 3 No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration One possibility is to increase the size of NCV relative to NEV See remark 4 below 1 N must be positive 2 NEV must be positive 3 NCVNEV 2 and less than or equal to N 4 The maximum number of Arnoldi update iterations allowed must be greater than zero 5 WHICH must be one of LM SM LR SR LI SI 6 BMAT must be one of I or G 7 Length of private work array WORKL is not sufficient 8 Error return from LAPACK eigenvalue calculation 9 Starting vector is zero 10 IPARAM7 must be 1234 11 IPARAM7 1 and BMAT G are incompatable 12 IPARAM1 must be equal to 0 or 1 9999 Could not build an Arnoldi factorization IPARAM5 returns the size of the current Arnoldi factorization The user is advised to check that enough workspace and array storage has been allocated Description Reverse communication interface for the Implicitly Restarted Arnoldi iteration This subroutine com putes approximations to a few eigenpairs of a linear operator OP with respect to a semiinner product defined by a symmetric positive semidefinite real matrix B B may be the identity matrix NOTE If the linear operator OP is real and symmetric with respect to the real positive semidefinite symmetric matrix B ie BOP OPB then subroutine dsaupd should be used instead The computed approximate eigenvalues are called Ritz values and the corresponding approximate eigenvectors are called Ritz vectors dnaupd is usually called iteratively to solve one of the following problems Mode 1 Ax lambdax OP A B I Mode 2 Ax lambdaMx M symmetric positive definite OP invMA B M If M can be factored see remark 3 below Mode 3 Ax lambdaMx M symmetric positive semidefinite OP RealPart invA sigmaMM B M shiftandinvert mode in real arithmetic If OPx amux then amu 12 1lambdasigma 1lambdaconjgsigma dnaupd 1918 Note If sigma is real ie imaginary part of sigma is zero RealPart invA sigmaMM invA sigmaMM amu 1lambdasigma Mode 4 Ax lambdaMx M symmetric semidefinite OP ImaginaryPart invA sigmaMM B M shiftandinvert mode in real arithmetic If OPx amux then amu 12i 1lambdasigma 1lamb daconjgsigma Both mode 3 and 4 give the same enhancement to eigenvalues close to the complex shift sigma However as lambda goes to infinity the operator OP in mode 4 dampens the eigenvalues more strong ly than does OP defined in mode 3 NOTE The action of w invA sigmaMv or w invMv should be accomplished either by a direct method using a sparse matrix factorization and solving A sigmaMw v or Mw v or through an iterative method for solving these systems If an iterative method is used the convergence test must be more stringent than the accuracy requirements for the eigenvalue approximations Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 v zerosnxncv workd zeros3nx11 workev zeros3ncv1 workl zeros3ncvncv6ncv1 Build the test matrix A diag10onesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts dnaupd 1919 iparam3 maxitr iparam7 mode1 sigmar 0 the real part of the shift sigmai 0 the imaginary part of the shift M A I N L O O P Reverse communication iter 0 whileitermaxiter infodnaupd 0 iter iter 1 Repeatedly call the routine DNAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfodnaupd dnaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklinfodnaupd if ido99 then BE CAREFUL DONT CALL dneupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call DNAUPD again continue end if infodnaupd 0 then printf Error with dnaupd info d infodnaupd printfCheck the documentation of dnaupd else PostProcess using DNEUPD rvec 1 howmany A infodneupd 0 dd12vresidviparamipntrworkdworklinfodneupd dneupdrvechowmanyselectdd12vsigmarsigmaiworkev bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfodneupd if infodneupd0 then printf Error with dneupd info d infodneupd printfCheck the documentation of dneupd end Print additional convergence information if infodneupd1 then printf Maximum number of iterations reached elseif infodneupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end dnaupd 1920 printf DNSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol Remarks 1 The computed Ritz values are approximate eigenvalues of OP The selection of WHICH should be made with this in mind when Mode 3 and 4 After convergence approximate eigenvalues of the original problem may be obtained with the ARPACK subroutine dneupd 2 If a basis for the invariant subspace corresponding to the converged Ritz values is needed the user must call dneupd immediately following completion of dnaupd This is new starting with release 2 of ARPACK 3 If M can be factored into a Cholesky factorization M LL then Mode 2 should not be selected Instead one should use Mode 1 with OP invLAinvL Appropriate triangular linear systems should be solved with L and L rather than computing inverses After convergence an approximate eigenvector z of the original problem is recovered by solving Lz x where x is a Ritz vector of OP 4 At present there is no apriori analysis to guide the selection of NCV relative to NEV The only formal requrement is that NCV NEV 2 However it is recommended that NCV 2NEV1 If many problems of the same type are to be solved one should experiment with increasing NCV while keeping NEV fixed for a given test problem This will usually decrease the required number of OPx operations but it also increases the work and storage required to maintain the orthogonal basis vectors The optimal crossover with respect to CPU time is problem dependent and must be determined empirically See Chapter 8 of Reference 2 for further information 5 When IPARAM1 0 and IDO 3 the user needs to provide the NP IPARAM8 real and imaginary parts of the shifts in locations real part imaginary part 1 WORKLIPNTR14 WORKLIPNTR14NP 2 WORKLIPNTR141 WORKLIPNTR14NP1 NP WORKLIPNTR14NP1 WORKLIPNTR142NP1 Only complex conjugate pairs of shifts may be applied and the pairs must be placed in con secutive locations The real part of the eigenvalues of the current upper Hessenberg matrix are located in WORKLIPNTR6 through WORKLIPNTR6NCV1 and the imaginary part in WORKLIPNTR7 through WORKLIPNTR7NCV1 They are ordered according to the order defined by WHICH The complex conjugate pairs are kept together and the associated Ritz estimates are located in WORKLIPNTR8 WORKLIPNTR81 WORKLIPNTR8NCV1 dnaupd 1921 See Also dsaupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett The Symmetric Eigenvalue Problem PrenticeHall 1980 4 BN Parlett B NourOmid Towards a Black Box Lanczos Program Computer Physics Com munications 53 1989 pp 169179 5 B NourOmid BN Parlett T Ericson PS Jensen How to Implement the Spectral Transforma tion Math Comp 48 1987 pp 663673 6 RG Grimes JG Lewis and HD Simon A Shifted Block Lanczos Algorithm for Solving Sparse Symmetric Generalized Eigenproblems SIAM J Matr Anal Apps January 1993 7 L Reichel WB Gragg Algorithm 686 FORTRAN Subroutines for Updating the QR decompo sition ACM TOMS December 1990 Volume 16 Number 4 pp 369377 8 RB Lehoucq DC Sorensen Implementation of Some Spectral Transformations in a kStep Arnoldi Method In Preparation Used Functions Based on ARPACK routine dnaupd 1922 Name dneupd Interface for the Implicitly Restarted Arnoldi Iteration to compute the converged approx imations to eigenvalues of Az lambdaBz approximations to a few eigenpairs of a real linear operator DrDiZRESIDVIPARAMIPNTRWORKDWORKLINFO dneupdRVECHOWMANYSELECTDrDiZSIGMArSIGMAiWORKev BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLINFO Parameters RVEC Integer INPUT Specifies whether a basis for the invariant subspace corresponding to the converged Ritz value approximations for the eigenproblem Az lambdaBz is computed RVEC 0 Compute Ritz values only RVEC 1 Compute the Ritz vectors or Schur vectors See Remarks below HOWMANY Character INPUT Specifies the form of the basis for the invariant subspace corresponding to the converged Ritz values that is to be computed A Compute NEV Ritz vectors P Compute NEV Schur vectors S compute some of the Ritz vectors specified by the integer array SELECT SELECT Integer array of dimension NCV INPUT If HOWMANY S SELECT specifies the Ritz vectors to be computed To select the Ritz vector corresponding to a Ritz value DRj DIj SELECTj must be set to 1 If HOWMANY A or P SELECT is used as internal workspace DR Double precision array of dimension NEV1 OUTPUT If IPARAM7 12 or 3 and SIGMAI00 then on exit DR contains the real part of the Ritz approximations to the eigenvalues of Az lambdaBz If IPARAM7 3 4 and SIGMAI is not equal to zero then on exit DR contains the real part of the Ritz values of OP computed by DNAUPD A further computation must be performed by the user to transform the Ritz values computed for OP by DNAUPD to those of the original system Az lambdaBz See remark 3 below DI Double precision array of dimension NEV1 OUTPUT On exit DI contains the imaginary part of the Ritz value approximations to the eigenvalues of Az lambdaBz associated with DR NOTE When Ritz values are complex they will come in complex conjugate pairs If eigenvectors are requested the corresponding Ritz vectors will also come in conjugate pairs and the real and imaginary parts of these are represented in two consecutive columns of the array Z see below dneupd 1923 Z Double precision N by NEV1 array if RVEC 1 and HOWMANY A OUTPUT On exit if RVEC 1 and HOWMANY A then the columns of Z represent approximate eigen vectors Ritz vectors corresponding to the NCONVIPARAM5 Ritz values for eigensystem Az lambdaBz The complex Ritz vector associated with the Ritz value with positive imag inary part is stored in two consecutive columns The first column holds the real part of the Ritz vector and the second column holds the imaginary part The Ritz vector associated with the Ritz value with negative imaginary part is simply the complex conjugate of the Ritz vector associated with the positive imaginary part If RVEC 0 or HOWMANY P then Z is not referenced NOTE If if RVEC 1 and a Schur basis is not required the array Z may be set equal to first NEV1 columns of the Arnoldi basis array V computed by DNAUPD In this case the Arnoldi basis will be destroyed and overwritten with the eigenvector basis SIGMAR Double precision INPUT If IPARAM7 3 or 4 represents the real part of the shift Not referenced if IPARAM7 1 or 2 SIGMAI Double precision INPUT If IPARAM7 3 or 4 represents the imaginary part of the shift Not referenced if IPARAM7 1 or 2 See remark 3 below WORKEV Double precision work array of dimension 3NCV WORKSPACE NOTE The remaining arguments BMAT N WHICH NEV TOL RESID NCV V IPARAM IP NTR WORKD WORKL LWORKL INFO must be passed directly to DNEUPD following the last call to DNAUPD These arguments MUST NOT BE MODIFIED between the the last call to DNAUPD and the call to DNEUPD Three of these parameters V WORKL INFO are also output parameters V Double precision N by NCV array INPUTOUTPUT Upon INPUT the NCV columns of V contain the Arnoldi basis vectors for OP as constructed by DNAUPD Upon OUTPUT If RVEC 1 the first NCONVIPARAM5 columns contain approximate Schur vectors that span the desired invariant subspace See Remark 2 below NOTE If the array Z has been set equal to first NEV1 columns of the array V and RVEC1 and HOWMANY A then the Arnoldi basis held by V has been overwritten by the desired Ritz vectors If a separate array Z has been passed then the first NCONVIPARAM5 columns of V will contain approximate Schur vectors that span the desired invariant subspace WORKL Double precision work array of length LWORKL OUTPUTWORKSPACE dneupd 1924 WORKL1ncvncv3ncv contains information obtained in dnaupd They are not changed by dneupd WORKLncvncv3ncv13ncvncv6ncv holds the real and imaginary part of the untrans formed Ritz values the upper quasitriangular matrix for H and the associated matrix represen tation of the invariant subspace for H Note IPNTR913 contains the pointer into WORKL for addresses of the above information computed by dneupd IPNTR9 pointer to the real part of the NCV RITZ values of the original system IPNTR10 pointer to the imaginary part of the NCV RITZ values of the original system IPNTR11 pointer to the NCV corresponding error bounds IPNTR12 pointer to the NCV by NCV upper quasitriangular Schur matrix for H IPNTR13 pointer to the NCV by NCV matrix of eigenvectors of the upper Hessenberg matrix H Only referenced by dneupd if RVEC 1 See Remark 2 below INFO Error flag on output 0 Normal exit 1 The Schur form computed by LAPACK routine dlahqr could not be reordered by LAPACK routine dtrsen Reenter subroutine dneupd with IPARAM5NCV and increase the size of the arrays DR and DI to have dimension at least dimension NCV and allocate at least NCV columns for Z NOTE Not necessary if Z and V share the same space Please notify the authors if this error occurs 1 N must be positive 2 NEV must be positive 3 NCVNEV 2 and less than or equal to N 5 WHICH must be one of LM SM LR SR LI SI 6 BMAT must be one of I or G 7 Length of private work WORKL array is not sufficient 8 Error return from calculation of a real Schur form Informational error from LAPACK rou tine dlahqr 9 Error return from calculation of eigenvectors Informational error from LAPACK routine dtrevc 10 IPARAM7 must be 1234 11 IPARAM7 1 and BMAT G are incompatible 12 HOWMANY S not yet implemented 13 HOWMANY must be one of A or P if RVEC 1 14 DNAUPD did not find any eigenvalues to sufficient accuracy 15 DNEUPD got a different count of the number of converged Ritz values than DNAUPD got This indicates the user probably made an error in passing data from DNAUPD to DNEUPD or that the data was modified before entering DNEUPD dneupd 1925 Description This subroutine returns the converged approximations to eigenvalues of Az lambdaBz and op tionally 1 The corresponding approximate eigenvectors 2 An orthonormal basis for the associated approximate invariant subspace 3 Both There is negligible additional cost to obtain eigenvectors An orthonormal basis is always computed There is an additional storage cost of nnev if both are requested in this case a separate array Z must be supplied The approximate eigenvalues and eigenvectors of Az lambdaBz are derived from approximate eigenvalues and eigenvectors of of the linear operator OP prescribed by the MODE selection in the call to DNAUPD DNAUPD must be called before this routine is called These approximate eigenvalues and vectors are commonly called Ritz values and Ritz vectors respec tively They are referred to as such in the comments that follow The computed orthonormal basis for the invariant subspace corresponding to these Ritz values is re ferred to as a Schur basis See documentation in the header of the subroutine DNAUPD for definition of OP as well as other terms and the relation of computed Ritz values and Ritz vectors of OP with respect to the given problem Az lambdaBz For a brief description see definitions of IPARAM7 MODE and WHICH in the documentation of DNAUPD Remarks 1 Currently only HOWMNY A and P are implemented Let transX denote the transpose of X 2 Schur vectors are an orthogonal representation for the basis of Ritz vectors Thus their numerical properties are often superior If RVEC 1 then the relationship A V1IPARAM5 V1IPARAM5 T and transV1IPARAM5 V1IPARAM5 I are approximately satisfied Here T is the leading submatrix of order IPARAM5 of the real upper quasitriangular matrix stored worklipntr12 That is T is block upper triangular with 1by1 and 2by2 diagonal blocks each 2by2 diagonal block has its diagonal elements equal and its offdiagonal elements of opposite sign Corresponding to each 2by2 diagonal block is a complex conjugate pair of Ritz values The real Ritz values are stored on the diagonal of T 3 If IPARAM7 3 or 4 and SIGMAI is not equal zero then the user must form the IPARAM5 Rayleigh quotients in order to transform the Ritz values computed by DNAUPD for OP to those of Az lambdaBz Set RVEC 1 and HOWMNY A and compute transZI A ZI if DII 0 If DII is not equal to zero and DII1 DI then the desired real and imaginary parts of the Ritz value are dneupd 1926 transZI A ZI transZI1 A ZI1 transZI A ZI1 transZI1 A ZI respectively Another possibility is to set RVEC 1 and HOWMANY P and compute transV1IPARAM5 A V1IPARAM5 and then an upper quasitriangular matrix of order IPARAM5 is computed See remark 2 above Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 v zerosnxncv workd zeros3nx11 workev zeros3ncv1 workl zeros3ncvncv6ncv1 Build the test matrix A diag10onesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts iparam3 maxitr iparam7 mode1 sigmar 0 the real part of the shift sigmai 0 the imaginary part of the shift dneupd 1927 M A I N L O O P Reverse communication iter 0 whileitermaxiter infodnaupd 0 iter iter 1 Repeatedly call the routine DNAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfodnaupd dnaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklinfodnaupd if ido99 then BE CAREFUL DONT CALL dneupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call DNAUPD again continue end if infodnaupd 0 then printf Error with dnaupd info d infodnaupd printfCheck the documentation of dnaupd else PostProcess using DNEUPD rvec 1 howmany A infodneupd 0 dd12vresidviparamipntrworkdworklinfodneupd dneupdrvechowmanyselectdd12vsigmarsigmaiworkev bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfodneupd if infodneupd0 then printf Error with dneupd info d infodneupd printfCheck the documentation of dneupd end Print additional convergence information if infodneupd1 then printf Maximum number of iterations reached elseif infodneupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end printf DNSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx dneupd 1928 printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also dsaupd dnaupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett The Symmetric Eigenvalue Problem PrenticeHall 1980 4 BN Parlett B NourOmid Towards a Black Box Lanczos Program Computer Physics Com munications 53 1989 pp 169179 5 B NourOmid BN Parlett T Ericson PS Jensen How to Implement the Spectral Transforma tion Math Comp 48 1987 pp 663673 6 RG Grimes JG Lewis and HD Simon A Shifted Block Lanczos Algorithm for Solving Sparse Symmetric Generalized Eigenproblems SIAM J Matr Anal Apps January 1993 7 L Reichel WB Gragg Algorithm 686 FORTRAN Subroutines for Updating the QR decompo sition ACM TOMS December 1990 Volume 16 Number 4 pp 369377 8 RB Lehoucq DC Sorensen Implementation of Some Spectral Transformations in a kStep Arnoldi Method In Preparation Used Functions Based on ARPACK routine dneupd 1929 Name dsaupd Interface for the Implicitly Restarted Arnoldi Iteration to compute approximations to a few eigenpairs of a real and symmetric linear operator IDORESIDVIPARAMIPNTRWORKDWORKLINFO dsaupdID0BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLINFO Parameters ID0 Integer INPUTOUTPUT Reverse communication flag IDO must be zero on the first call to dsaupd IDO will be set internally to indicate the type of operation to be performed Control is then given back to the calling routine which has the responsibility to carry out the requested operation and call dsaupd with the result T he operand is given in WORKDIPNTR1 the result must be put in WORKDIPNTR2 If Mode 2 see remark 5 below IDO 0 first call to the reverse communication interface IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y This is for the initialization phase to force the starting vector into the range of OP IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y In mode 34 and 5 the vector B X is already available in WORKDipntr3 It does not need to be recomputed in forming OP X IDO 2 compute Y B X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y IDO 3 compute the IPARAM8 shifts where IPNTR11 is the pointer into WORKL for placing the shifts See remark 6 below IDO 99 done BMAT Character INPUT Specifies the type of the matrix B that defines the semiinner product for the operator OP I standard eigenvalue problem Ax lambdax G generalized eigenvalue problem Ax lambdaBx N Integer Dimension of the eigenproblem WHICH String of length 2 Specify which of the Ritz values of OP to compute LA compute the NEV largest algebraic eigenvalues SA compute the NEV smallest algebraic eigenvalues dsaupd 1930 LM compute the NEV largest in magnitude eigenvalues SM compute the NEV smallest in magnitude eigenvalues BE compute NEV eigenvalues half from each end of the spectrum When NEV is odd compute one more from the high end than from the low end see remark 1 below NEV Integer Number of eigenvalues of OP to be computed 0 NEV N TOL scalar Stopping criterion the relative accuracy of the Ritz value is considered acceptable if BOUNDSI TOLABSRITZI If TOL 0 is passed the machine precision is set RESID Array of length N INPUTOUTPUT On INPUT If INFO0 a random initial residual vector is used else RESID contains the initial residual vector possibly from a previous run On OUTPUT RESID contains the final residual vector NCV Integer Number of columns of the matrix V less than or equal to N This will indicate how many Lanczos vectors are generated at each iteration After the startup phase in which NEV Lanczos vectors are generated the algorithm generates NCVNEV Lanczos vectors at each subsequent update iteration Most of the cost in generating each Lanczos vector is in the matrixvector product OPx See remark 4 below V N by NCV array The NCV columns of V contain the Lanczos basis vectors IPARAM array of length 11 INPUTOUTPUT IPARAM1 ISHIFT method for selecting the implicit shifts The shifts selected at each iteration are used to restart the Arnoldi iteration in an implicit fashion ISHIFT 0 the shifts are provided by the user via reverse communication The NCV eigen values of the current tridiagonal matrix T are returned in the part of WORKL array corre sponding to RITZ See remark 6 below ISHIFT 1 exact shifts with respect to the reduced tridiagonal matrix T This is equivalent to restarting the iteration with a starting vector that is a linear combination of Ritz vectors associated with the wanted Ritz values IPARAM2 LEVEC No longer referenced See remark 2 below IPARAM3 MXITER On INPUT maximum number of Arnoldi update iterations allowed On OUTPUT actual number of Arnoldi update iterations taken dsaupd 1931 IPARAM4 NB blocksize to be used in the recurrence The code currently works only for NB 1 IPARAM5 NCONV number of converged Ritz values This represents the number of Ritz values that satisfy the convergence criterion IPARAM6 IUPD No longer referenced Implicit restarting is ALWAYS used IPARAM7 MODE On INPUT determines what type of eigenproblem is being solved Must be 12345 See under Description of dsaupd for the five modes available IPARAM8 NP When ido 3 and the user provides shifts through reverse communication IPARAM10 dsaupd returns NP the number of shifts the user is to provide 0 NP NCVNEV See Remark 6 below IPARAM9 NUMOP IPARAM10 NUMOPB IPARAM11 NUMREO OUTPUT NUMOP total number of OPx operations NU MOPB total number of Bx operations if BMATG NUMREO total number of steps of reorthogonalization IPNTR array of length 11 Pointer to mark the starting locations in the WORKD and WORKL arrays for matricesvectors used by the Lanczos iteration IPNTR1 pointer to the current operand vector X in WORKD IPNTR2 pointer to the current result vector Y in WORKD IPNTR3 pointer to the vector B X in WORKD when used in the shiftandinvert mode IPNTR4 pointer to the next available location in WORKL that is untouched by the program IPNTR5 pointer to the NCV by 2 tridiagonal matrix T in WORKL IPNTR6 pointer to the NCV RITZ values array in WORKL IPNTR7 pointer to the Ritz estimates in array WORKL associated with the Ritz values lo cated in RITZ in WORKL IPNTR11 pointer to the NP shifts in WORKL See Remark 6 below Note IPNTR810 is only referenced by dseupd See Remark 2 IPNTR8 pointer to the NCV RITZ values of the original system IPNTR9 pointer to the NCV corresponding error bounds IPNTR10 pointer to the NCV by NCV matrix of eigenvectors of the tridiagonal matrix T Only referenced by dseupd if RVEC 1 See Remarks WORKD work array of length 3N REVERSE COMMUNICATION Distributed array to be used in the basic Arnoldi iteration for reverse communication The us er should not use WORKD as temporary workspace during the iteration Upon termination WORKD1N contains BRESID1N If the Ritz vectors are desired subroutine dseupd uses this output See Data Distribution Note below WORKL work array of length at least NCV2 8NCV OUTPUTWORKSPACE dsaupd 1932 Private replicated array on each PE or array allocated on the front end See Data Distribution Note below add here the parameter description INFO Integer INPUTOUTPUT If INFO 0 a randomly initial residual vector is used else RESID contains the initial residual vector possibly from a previous run Error flag on output 0 Normal exit 1 Maximum number of iterations taken All possible eigenvalues of OP has been found IPARAM5 returns the number of wanted converged Ritz values 2 No longer an informational error Deprecated starting with release 2 of ARPACK 3 No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration One possibility is to increase the size of NCV relative to NEV See remark 4 below 1 N must be positive 2 NEV must be positive 3 NCV must be greater than NEV and less than or equal to N 4 The maximum number of Arnoldi update iterations allowed must be greater than zero 5 WHICH must be one of LM SM LA SA or BE 6 BMAT must be one of I or G 7 Length of private work array WORKL is not sufficient 8 Error return from trid eigenvalue calculation Informatinal error from LAPACK routine dsteqr 9 Starting vector is zero 10 IPARAM7 must be 12345 11 IPARAM7 1 and BMAT G are incompatable 12 IPARAM1 must be equal to 0 or 1 13 NEV and WHICH BE are incompatable 9999 Could not build an Arnoldi factorization IPARAM5 returns the size of the current Arnoldi factorization The user is advised to check that enough workspace and array storage has been allocated Description Reverse communication interface for the Implicitly Restarted Arnoldi Iteration For symmetric prob lems this reduces to a variant of the Lanczos method This method has been designed to compute approximations to a few eigenpairs of a linear operator OP that is real and symmetric with respect to a real positive semidefinite symmetric matrix B ieBOP OPB Another way to express this condition is xOPy OPxy where zw zBw dsaupd 1933 In the standard eigenproblem B is the identity matrix A denotes transpose of A The computed approximate eigenvalues are called Ritz values and the corresponding approximate eigenvectors are called Ritz vectors dsaupd is usually called iteratively to solve one of the following problems Mode 1 Ax lambdax A symmetric OP A and B I Mode 2 Ax lambdaMx A symmetric M symmetric positive definite OP invMA and B M If M can be factored see remark 3 below Mode 3 Kx lambdaMx K symmetric M symmetric positive semidefinite OP invK sigmaMM and B M ShiftandInvert mode Mode 4 Kx lambdaKGx K symmetric positive semidefinite KG symmetric indefinite OP invK sigmaKGK and B K Buckling mode Mode 5 Ax lambdaMx A symmetric M symmetric positive semidefinite OP invA sigmaMA sigmaM and B M Cayley transformed mode NOTE The action of w invA sigmaMv or w invMv should be accomplished either by a direct method using a sparse matrix factorization and solving A sigmaMw v or Mw v or through an iterative method for solving these systems If an iterative method is used the convergence test must be more stringent than the accuracy requirements for the eigenvalue approximations Remarks 1 The converged Ritz values are always returned in ascending algebraic order The computed Ritz values are approximate eigenvalues of OP The selection of WHICH should be made with this in mind when Mode 345 After convergence approximate eigenvalues of the original problem may be obtained with the ARPACK subroutine dseupd 2 If the Ritz vectors corresponding to the converged Ritz values are needed the user must call dseupd immediately following completion of dsaupd This is new starting with version 21 of ARPACK 3 If M can be factored into a Cholesky factorization M LL then Mode 2 should not be selected Instead one should use Mode 1 with OP invLAinvL Appropriate triangular linear systems should be solved with L and L rather than computing inverses After convergence an approximate eigenvector z of the original problem is recovered by solving Lz x where x is a Ritz vector of OP 4 At present there is no apriori analysis to guide the selection of NCV relative to NEV The only formal requrement is that NCV NEV However it is recommended that NCV 2NEV If many problems of the same type are to be solved one should experiment with increasing NCV while keeping NEV fixed for a given test problem This will usually decrease the required number of OPx operations but it also increases the work and storage required to maintain the orthogonal basis vectors The optimal crossover with respect to CPU time is problem dependent and must be determined empirically 5 If IPARAM7 2 then in the Reverse commuication interface the user must do the following When IDO 1 Y OP X is to be computed When IPARAM7 2 OP invBA After computing AX the user must overwrite X with AX Y is then the solution to the linear set of equations BY AX 6 When IPARAM1 0 and IDO 3 the user needs to provide the NP IPARAM8 shifts in locations 1 WORKLIPNTR11 2 WORKLIPNTR111 NP WORKLIPNTR11NP1 The eigenvalues of the current tridiagonal matrix are located in WORKLIPNTR6 through WORKLIPNTR6NCV1 They are in the order defined by WHICH The associated Ritz estimates are located in WORKLIPNTR8 WORKLIPNTR81 WORKLIPNTR8NCV1 dsaupd 1934 Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 v zerosnxncv workd zeros3nx11 workl zerosncvncv8ncv1 Build the symmetric test matrix A diag10onesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts iparam3 maxitr iparam7 mode1 sigma 0 the real part of the shift M A I N L O O P Reverse communication iter 0 whileitermaxiter infodsaupd 0 iter iter 1 Repeatedly call the routine DSAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfodsaupd dsaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklinfodsaupd if ido99 then dsaupd 1935 BE CAREFUL DONT CALL dseupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call DSAUPD again continue end if infodsaupd 0 then printf Error with dsaupd info d infodsaupd printfCheck the documentation of dsaupd else PostProcess using DSEUPD rvec 1 howmany A infodseupd 0 dd12vresidviparamipntrworkdworklinfodseupd dseupdrvechowmanyselectdd12vsigma bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfodseupd if infodseupd0 then printf Error with dseupd info d infodseupd printfCheck the documentation of dseupd end if infodseupd1 then printf Maximum number of iterations reached elseif infodseupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end Done with program dssimp printf DSSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also dnaupd dsaupd 1936 Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett and Y Saad Complex Shift and Invert Strategies for Real Matrices Linear Algebra and its Applications vol 8889 pp 575595 1987 Used Functions Based on ARPACK routine dsaupd 1937 Name dsaupd Interface for the Implicitly Restarted Arnoldi Iteration to compute approximations to the converged approximations to eigenvalues of Az lambdaBz DZRESIDVIPARAMIPNTRWORKDWORKLINFO dseupdRVECHOWMANYSELECTDZSIGMABMATNWHICH NEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLINFO Parameters RVEC Integer INPUT Specifies whether Ritz vectors corresponding to the Ritz value approximations to the eigenprob lem Az lambdaBz are computed RVEC 0 Compute Ritz values only RVEC 1 Compute Ritz vectors HOWMNY Character1 INPUT Specifies how many Ritz vectors are wanted and the form of Z the matrix of Ritz vectors See remark 1 below A compute NEV Ritz vectors S compute some of the Ritz vectors specified by the integer array SELECT SELECT Integer array of dimension NCV INPUTWORKSPACE If HOWMANY S SELECT specifies the Ritz vectors to be computed To select the Ritz vector corresponding to a Ritz value Dj SELECTj must be set to 1 If HOWMANY A SELECT is used as a workspace for reordering the Ritz values D Double precision array of dimension NEV OUTPUT On exit D contains the Ritz value approximations to the eigenvalues of Az lambdaBz The values are returned in ascending order If IPARAM7 345 then D represents the Ritz values of OP computed by dsaupd transformed to those of the original eigensystem Az lambdaBz If IPARAM7 12 then the Ritz values of OP are the same as the those of Az lambdaBz Z Double precision N by NEV array If HOWMNY A OUTPUT On exit Z contains the Borthonormal Ritz vectors of the eigen system Az lambdaBz corresponding to the Ritz value approximations If RVEC 0 then Z is not referenced NOTE The array Z may be set equal to first NEV columns of the ArnoldiLanczos basis array V computed by DSAUPD SIGMA Double precision INPUT If IPARAM7 345 represents the shift Not referenced if IPARAM7 1 or 2 dsaupd 1938 NOTE The remaining arguments BMAT N WHICH NEV TOL RESID NCV V IPARAM IP NTR WORKD WORKL LWORKL INFO must be passed directly to DSEUPD following the last call to DSAUPD These arguments MUST NOT BE MODIFIED between the the last call to DSAUPD and the call to DSEUPD Two of these parameters WORKL INFO are also output parameters WORKL Double precision work array of length LWORKL OUTPUTWORKSPACE WORKL14ncv contains information obtained in dsaupd They are not changed by dseupd WORKL4ncv1ncvncv8ncv holds the untransformed Ritz values the computed error es timates and the associated eigenvector matrix of H Note IPNTR810 contains the pointer into WORKL for addresses of the above information computed by dseupd IPNTR8 pointer to the NCV RITZ values of the original system IPNTR9 pointer to the NCV corresponding error bounds IPNTR10 pointer to the NCV by NCV matrix of eigenvectors of the tridiagonal matrix T Only referenced by dseupd if RVEC 1 See Remarks INFO Integer OUTPUT Error flag on output 0 Normal exit 1 N must be positive 2 NEV must be positive 3 NCV must be greater than NEV and less than or equal to N 5 WHICH must be one of LM SM LA SA or BE 6 BMAT must be one of I or G 7 Length of private work WORKL array is not sufficient 8 Error return from trid eigenvalue calculation Information error from LAPACK routine dsteqr 9 Starting vector is zero 10 IPARAM7 must be 12345 11 IPARAM7 1 and BMAT G are incompatible 12 NEV and WHICH BE are incompatible 14 DSAUPD did not find any eigenvalues to sufficient accuracy 15 HOWMNY must be one of A or S if RVEC 1 16 HOWMNY S not yet implemented 17 DSEUPD got a different count of the number of converged Ritz values than DSAUPD got This indicates the user probably made an error in passing data from DSAUPD to DSEUPD or that the data was modified before entering DSEUPD dsaupd 1939 Description This subroutine returns the converged approximations to eigenvalues of Az lambdaBz and op tionally 1 the corresponding approximate eigenvectors 2 an orthonormal Lanczos basis for the associated approximate invariant subspace 3 Both There is negligible additional cost to obtain eigenvectors An orthonormal Lanczos basis is always computed There is an additional storage cost of nnev if both are requested in this case a separate array Z must be supplied These quantities are obtained from the Lanczos factorization computed by DSAUPD for the lin ear operator OP prescribed by the MODE selection see IPARAM7 in DSAUPD documentation DSAUPD must be called before this routine is called These approximate eigenvalues and vectors are commonly called Ritz values and Ritz vectors respec tively They are referred to as such in the comments that follow The computed orthonormal basis for the invariant subspace corresponding to these Ritz values is re ferred to as a Lanczos basis See documentation in the header of the subroutine DSAUPD for a definition of OP as well as other terms and the relation of computed Ritz values and vectors of OP with respect to the given problem Az lambdaBz The approximate eigenvalues of the original problem are returned in ascending algebraic order The user may elect to call this routine once for each desired Ritz vector and store it peripherally if desired There is also the option of computing a selected set of these vectors with a single call Remarks 1 The converged Ritz values are always returned in increasing algebraic order c 2 Currently only HOWMNY A is implemented It is included at this stage for the user who wants to incorporate it Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 dsaupd 1940 resid zerosnx1 v zerosnxncv workd zeros3nx11 workl zerosncvncv8ncv1 Build the symmetric test matrix A diag10onesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts iparam3 maxitr iparam7 mode1 sigma 0 the real part of the shift M A I N L O O P Reverse communication iter 0 whileitermaxiter infodsaupd 0 iter iter 1 Repeatedly call the routine DSAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfodsaupd dsaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklinfodsaupd if ido99 then BE CAREFUL DONT CALL dseupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call DSAUPD again continue end if infodsaupd 0 then printf Error with dsaupd info d infodsaupd printfCheck the documentation of dsaupd else PostProcess using DSEUPD rvec 1 howmany A infodseupd 0 dsaupd 1941 dd12vresidviparamipntrworkdworklinfodseupd dseupdrvechowmanyselectdd12vsigma bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfodseupd if infodseupd0 then printf Error with dseupd info d infodseupd printfCheck the documentation of dseupd end if infodseupd1 then printf Maximum number of iterations reached elseif infodseupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end Done with program dssimp printf DSSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also dsaupd dneupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett and Y Saad Complex Shift and Invert Strategies for Real Matrices Linear Algebra and its Applications vol 8889 pp 575595 1987 Used Functions Based on ARPACK routine dsaupd 1942 Name znaupd Interface for the Implicitly Restarted Arnoldi Iteration to compute a few eigenpairs of a complex linear operator OP with respect to a semiinner product defined by a hermitian positive semidefinite real matrix B IDORESIDVIPARAMIPNTRWORKDWORKLRWORKINFO znaupdID0BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLRWORKINFO Parameters IDO Integer INPUTOUTPUT Reverse communication flag IDO must be zero on the first call to znaupd IDO will be set inter nally to indicate the type of operation to be performed Control is then given back to the calling routine which has the responsibility to carry out the requested operation and call znaupd with the result The operand is given in WORKDIPNTR1 the result must be put in WORKDIPNTR2 IDO 0 first call to the reverse communication interface IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y This is for the initialization phase to force the starting vector into the range of OP IDO 1 compute Y OP X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y In mode 3 the vector B X is already available in WORKDipntr3 It does not need to be recomputed in forming OP X IDO 2 compute Y M X where IPNTR1 is the pointer into WORKD for X IPNTR2 is the pointer into WORKD for Y IDO 3 compute and return the shifts in the first NP locations of WORKL IDO 99 done After the initialization phase when the routine is used in the shiftandinvert mode the vector M X is already available and does not need to be recomputed in forming OPX BMAT Character INPUT BMAT specifies the type of the matrix B that defines the semiinner product for the operator OP I standard eigenvalue problem Ax lambdax G generalized eigenvalue problem Ax lambdaMx N Integer INPUT Dimension of the eigenproblem WHICH Characters INPUT LM want the NEV eigenvalues of largest magnitude SM want the NEV eigenvalues of smallest magnitude znaupd 1943 LR want the NEV eigenvalues of largest real part SR want the NEV eigenvalues of smallest real part LI want the NEV eigenvalues of largest imaginary part SI want the NEV eigenvalues of smallest imaginary part NEV Integer INPUT Number of eigenvalues of OP to be computed 0 NEV N1 TOL Double precision scalar INPUT Stopping criteria the relative accuracy of the Ritz value is considered acceptable if BOUNDSI LE TOLABSRITZI where ABSRITZI is the magnitude when RITZI is complex DEFAULT dlamchEPS machine precision as computed by the LAPACK auxiliary subroutine dlamch RESID Complex16 array of length N INPUTOUTPUT On INPUT If INFO EQ 0 a random initial residual vector is used If INFO NE 0 RESID contains the initial residual vector possibly from a previous run On OUTPUT RESID contains the final residual vector NCV Integer INPUT Number of columns of the matrix V NCV must satisfy the two inequalities 1 NCVNEV and NCV N This will indicate how many Arnoldi vectors are generated at each iteration After the startup phase in which NEV Arnoldi vectors are generated the algorithm generates approximately NCV NEV Arnoldi vectors at each subsequent update iteration Most of the cost in generating each Arnoldi vector is in the matrixvector operation OPx See remark 4 below V Complex16 array N by NCV OUTPUT Contains the final set of Arnoldi basis vectors IPARAM Integer array of length 11 INPUTOUTPUT IPARAM1 ISHIFT method for selecting the implicit shifts The shifts selected at each iteration are used to filter out the components of the unwanted eigenvector ISHIFT 0 the shifts are to be provided by the user via reverse communication The NCV eigenvalues of the Hessenberg matrix H are returned in the part of WORKL array corre sponding to RITZ ISHIFT 1 exact shifts with respect to the current Hessenberg matrix H This is equivalent to restarting the iteration from the beginning after updating the starting vector with a linear combination of Ritz vectors associated with the wanted eigenvalues ISHIFT 2 other choice of internal shift to be defined IPARAM2 No longer referenced znaupd 1944 IPARAM3 MXITER On INPUT maximum number of Arnoldi update iterations allowed On OUTPUT actual number of Arnoldi update iterations taken IPARAM4 NB blocksize to be used in the recurrence The code currently works only for NB 1 IPARAM5 NCONV number of converged Ritz values This represents the number of Ritz values that satisfy the convergence criterion IPARAM6 IUPD No longer referenced Implicit restarting is ALWAYS used IPARAM7 MODE On INPUT determines what type of eigenproblem is being solved Must be 123 See under Description of znaupd for the four modes available IPARAM8 NP When ido 3 and the user provides shifts through reverse communication IPARAM10 naupd returns NP the number of shifts the user is to provide 0 NP NCVNEV IPARAM9 NUMOP IPARAM10 NUMOPB IPARAM11 NUMREO OUTPUT NUMOP total number of OPx operations NU MOPB total number of Bx operations if BMATG NUMREO total number of steps of reorthogonalization IPNTR Integer array of length 14 OUTPUT Pointer to mark the starting locations in the WORKD and WORKL arrays for matricesvectors used by the Arnoldi iteration IPNTR1 pointer to the current operand vector X in WORKD IPNTR2 pointer to the current result vector Y in WORKD IPNTR3 pointer to the vector B X in WORKD when used in the shiftandinvert mode IPNTR4 pointer to the next available location in WORKL that is untouched by the program IPNTR5 pointer to the NCV by NCV upper Hessenberg matrix H in WORKL IPNTR6 pointer to the ritz value array RITZ IPNTR7 pointer to the projected ritz vector array Q IPNTR8 pointer to the error BOUNDS array in WORKL IPNTR14 pointer to the NP shifts in WORKL See Remark 5 below Note IPNTR913 is only referenced by zneupd See Remark 2 below IPNTR9 pointer to the NCV RITZ values of the original system IPNTR10 Not Used IPNTR11 pointer to the NCV corresponding error bounds IPNTR12 pointer to the NCV by NCV upper triangular Schur matrix for H IPNTR13 pointer to the NCV by NCV matrix of eigenvectors of the upper Hessenberg matrix H Only referenced by zneupd if RVEC 1 See Remark 2 below znaupd 1945 WORKD Complex16 work array of length 3N REVERSE COMMUNICATION Distributed array to be used in the basic Arnoldi iteration for reverse communication The user should not use WORKD as temporary workspace during the iteration See Data Distribution Note below WORKL Complex16 work array of length 3NCV2 5NCV OUTPUTWORKSPACE Private replicated array on each PE or array allocated on the front end See Data Distribution Note below RWORK Double precision work array of length NCV WORKSPACE Private replicated array on each PE or array allocated on the front end INFO Integer INPUTOUTPUT If INFO 0 a randomly initial residual vector is used If INFO 0 RESID contains the initial residual vector possibly from a previous run Error flag on output 0 Normal exit 1 Maximum number of iterations taken All possible eigenvalues of OP has been found IPARAM5 returns the number of wanted converged Ritz values 2 No longer an informational error Deprecated starting with release 2 of ARPACK 3 No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration One possibility is to increase the size of NCV relative to NEV See remark 4 below 1 N must be positive 2 NEV must be positive 3 NCVNEV 1 and less than or equal to N 4 The maximum number of Arnoldi update iteration must be greater than zero 5 WHICH must be one of LM SM LR SR LI SI 6 BMAT must be one of I or G 7 Length of private work array is not sufficient 8 Error return from LAPACK eigenvalue calculation 9 Starting vector is zero 10 IPARAM7 must be 123 11 IPARAM7 1 and BMAT G are incompatible 12 IPARAM1 must be equal to 0 or 1 9999 Could not build an Arnoldi factorization User input error highly likely Please check actual array dimensions and layout IPARAM5 returns the size of the current Arnoldi factor ization znaupd 1946 Description Reverse communication interface for the Implicitly Restarted Arnoldi iteration This is intended to be used to find a few eigenpairs of a complex linear operator OP with respect to a semiinner product defined by a hermitian positive semidefinite real matrix B B may be the identity matrix NOTE if both OP and B are real then dsaupd or dnaupd should be used The computed approximate eigenvalues are called Ritz values and the corresponding approximate eigenvectors are called Ritz vectors znaupd is usually called iteratively to solve one of the following problems Mode 1 Ax lambdax OP A and B I Mode 2 Ax lambdaMx M hermitian positive definite OP invMA and B M If M can be factored see remark 3 below Mode 3 Ax lambdaMx M hermitian semidefinite OP invA sigmaMM and B M shiftandinvert mode If OPx amux then lambda sigma 1amu NOTE The action of w invA sigmaMv or w invMv should be accomplished either by a direct method using a sparse matrix factorization and solving A sigmaMw v or Mw v or through an iterative method for solving these systems If an iterative method is used the convergence test must be more stringent than the accuracy requirements for the eigenvalue approximations Remarks 1 The computed Ritz values are approximate eigenvalues of OP The selection of WHICH should be made with this in mind when using Mode 3 When operating in Mode 3 setting WHICH LM will compute the NEV eigenvalues of the original problem that are closest to the shift SIGMA After convergence approximate eigenvalues of the original problem may be obtained with the ARPACK subroutine zneupd 2 If a basis for the invariant subspace corresponding to the converged Ritz values is needed the user must call zneupd immediately following completion of znaupd This is new starting with release 2 of ARPACK 3 If M can be factored into a Cholesky factorization M LL then Mode 2 should not be select ed Instead one should use Mode 1 with OP invLAinvL Appropriate triangular linear systems should be solved with L and L rather than computing inverses After convergence an approximate eigenvector z of the original problem is recovered by solving Lz x where x is a Ritz vector of OP 4 At present there is no apriori analysis to guide the selection of NCV relative to NEV The only formal requirement is that NCV NEV 1 However it is recommended that NCV ge 2NEV If many problems of the same type are to be solved one should experiment with increasing NCV while keeping NEV fixed for a given test problem This will usually decrease the required number of OPx operations but it also increases the work and storage required to maintain the orthogonal basis vectors The optimal crossover with respect to CPU time is problem dependent and must be determined empirically See Chapter 8 of Reference 2 for further information znaupd 1947 5 When IPARAM1 0 and IDO 3 the user needs to provide the NP IPARAM8 complex shifts in locations WORKLIPNTR14 WORKLIPNTR141 WORKLIPNTR14NP Eigenvalues of the current upper Hessenberg matrix are located in WORKLIPNTR6 through WORKLIPNTR6NCV1 They are ordered according to the order defined by WHICH The associated Ritz estimates are located in WORKLIPNTR8 WORKLIPNTR81 WORKLIPNTR8NCV1 Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 0i v zerosnxncv 0i workd zeros3nx11 0i workev zeros3ncv1 rwork zerosncv1 workl zeros3ncvncv5ncv1 0i Build the complex test matrix A diag10onesnx1ionesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts iparam3 maxitr iparam7 mode1 sigma 0 the real part of the shift M A I N L O O P Reverse communication znaupd 1948 iter 0 whileitermaxiter infoznaupd 0 iter iter 1 Repeatedly call the routine ZNAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfoznaupd znaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklrworkinfoznaupd if ido99 then BE CAREFUL DONT CALL zneupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call ZNAUPD again continue end if infoznaupd 0 then printf Error with znaupd info d infoznaupd printfCheck the documentation of znaupd else PostProcess using ZNEUPD rvec 1 howmany A infozneupd 0 dd12vresidviparamipntrworkdworklinfozneupd zneupdrvechowmanyselectdd12vsigmaworkev bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfozneupd if infozneupd0 then printf Error with zneupd info d infozneupd printfCheck the documentation of zneupd end if infozneupd1 then printf Maximum number of iterations reached elseif infozneupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end Done with program znsimp printf ZNSIMP printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which znaupd 1949 printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also dnaupd dneupd zneupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett and Y Saad Complex Shift and Invert Strategies for Real Matrices Linear Algebra and its Applications vol 8889 pp 575595 1987 Used Functions Based on ARPACK routine znaupd 1950 Name zneupd Interface for the Implicitly Restarted Arnoldi Iteration to compute approximations to the converged approximations to eigenvalues of Az lambdaBz DZRESIDIPARAMIPNTRWORKDWORKLRWORKINFO zneupdRVECHOWMANYSELECTDZSIGMAWORKev BMATNWHICHNEVTOLRESIDNCVVIPARAMIPNTRWORKDWORKLRWORKINFO Parameters RVEC Integer INPUT Specifies whether a basis for the invariant subspace corresponding to the converged Ritz value approximations for the eigenproblem Az lambdaBz is computed RVEC 0 Compute Ritz values only RVEC 1 Compute Ritz vectors or Schur vectors See Remarks below HOWMANY Character INPUT Specifies the form of the basis for the invariant subspace corresponding to the converged Ritz values that is to be computed A Compute NEV Ritz vectors P Compute NEV Schur vectors S compute some of the Ritz vectors specified by the integer array SELECT SELECT Integer array of dimension NCV INPUT If HOWMANY S SELECT specifies the Ritz vectors to be computed To select the Ritz vector corresponding to a Ritz value Dj SELECTj must be set to 1 If HOWMANY A or P SELECT need not be initialized but it is used as internal workspace D Complex16 array of dimension NEV1 OUTPUT On exit D contains the Ritz approximations to the eigenvalues lambda for Az lambdaBz Z Complex16 N by NEV array OUTPUT On exit If RVEC 1 and HOWMANY A then the columns of Z represents approximate eigenvectors Ritz vectors corresponding to the NCONVIPARAM5 Ritz values for eigensystem Az lambdaBz If RVEC 0 or HOWMANY P then Z is NOT REFERENCED NOTE If if RVEC 1 and a Schur basis is not required the array Z may be set equal to first NEV1 columns of the Arnoldi basis array V computed by ZNAUPD In this case the Arnoldi basis will be destroyed and overwritten with the eigenvector basis SIGMA Complex16 INPUT If IPARAM7 3 then SIGMA represents the shift zneupd 1951 Not referenced if IPARAM7 1 or 2 WORKev Complex16 work array of dimension 2NCV WORKSPACE NOTE The remaining arguments BMAT N WHICH NEV TOL RESID NCV V IPARAM IPN TR WORKD WORKL LWORKL RWORK INFO must be passed directly to ZNEUPD following the last call to ZNAUPD These arguments MUST NOT BE MODIFIED between the the last call to ZNAUPD and the call to ZNEUPD Three of these parameters V WORKL and INFO are also output parameters V Complex16 N by NCV array INPUTOUTPUT Upon INPUT the NCV columns of V contain the Arnoldi basis vectors for OP as constructed by ZNAUPD Upon OUTPUT If RVEC 1 the first NCONVIPARAM5 columns contain approximate Schur vectors that span the desired invariant subspace NOTE If the array Z has been set equal to first NEV1 columns of the array V and RVEC1 and HOWMANY A then the Arnoldi basis held by V has been overwritten by the desired Ritz vectors If a separate array Z has been passed then the first NCONVIPARAM5 columns of V will contain approximate Schur vectors that span the desired invariant subspace WORKL Double precision work array of length LWORKL OUTPUTWORKSPACE WORKL1ncvncv2ncv contains information obtained in znaupd They are not changed by zneupd WORKLncvncv2ncv13ncvncv4ncv holds the untransformed Ritz values the un transformed error estimates of the Ritz values the upper triangular matrix for H and the associ ated matrix representation of the invariant subspace for H Note IPNTR913 contains the pointer into WORKL for addresses of the above information computed by zneupd IPNTR9 pointer to the NCV RITZ values of the original system IPNTR10 Not used IPNTR11 pointer to the NCV corresponding error estimates IPNTR12 pointer to the NCV by NCV upper triangular Schur matrix for H IPNTR13 pointer to the NCV by NCV matrix of eigenvectors of the upper Hessenberg matrix H Only referenced by zneupd if RVEC 1 See Remark 2 below INFO Integer OUTPUT Error flag on output 0 Normal exit 1 The Schur form computed by LAPACK routine csheqr could not be reordered by LAPACK routine ztrsen Reenter subroutine zneupd with IPARAM5NCV and increase the size of the array D to have dimension at least dimension NCV and allocate at least NCV columns for Z NOTE Not necessary if Z and V share the same space Please notify the authors if this error occurs zneupd 1952 1 N must be positive 2 NEV must be positive 3 NCVNEV 1 and less than or equal to N 5 WHICH must be one of LM SM LR SR LI SI 6 BMAT must be one of I or G 7 Length of private work WORKL array is not sufficient 8 Error return from LAPACK eigenvalue calculation This should never happened 9 Error return from calculation of eigenvectors Informational error from LAPACK routine ztrevc 10 IPARAM7 must be 123 11 IPARAM7 1 and BMAT G are incompatible 12 HOWMANY S not yet implemented 13 HOWMANY must be one of A or P if RVEC true 14 ZNAUPD did not find any eigenvalues to sufficient accuracy 15 ZNEUPD got a different count of the number of converged Ritz values than ZNAUPD got This indicates the user probably made an error in passing data from ZNAUPD to ZNEUPD or that the data was modified before entering ZNEUPD Description This subroutine returns the converged approximations to eigenvalues of Az lambdaBz and op tionally 1 The corresponding approximate eigenvectors 2 An orthonormal basis for the associated approximate invariant subspace 3 Both There is negligible additional cost to obtain eigenvectors An orthonormal basis is always computed There is an additional storage cost of nnev if both are requested in this case a separate array Z must be supplied The approximate eigenvalues and eigenvectors of Az lambdaBz are derived from approximate eigenvalues and eigenvectors of of the linear operator OP prescribed by the MODE selection in the call to ZNAUPD ZNAUPD must be called before this routine is called These approximate eigenvalues and vectors are commonly called Ritz values and Ritz vectors respec tively They are referred to as such in the comments that follow The computed orthonormal basis for the invariant subspace corresponding to these Ritz values is re ferred to as a Schur basis The definition of OP as well as other terms and the relation of computed Ritz values and vectors of OP with respect to the given problem Az lambdaBz may be found in the header of ZNAUPD For a brief description see definitions of IPARAM7 MODE and WHICH in the documentation of ZNAUPD zneupd 1953 Remarks 1 Currently only HOWMNY A and P are implemented 2 Schur vectors are an orthogonal representation for the basis of Ritz vectors Thus their numerical properties are often superior If RVEC 1 then the relationship A V1IPARAM5 V1IPARAM5 T and transpose V1IPARAM5 V1IPARAM5 I are approximately satisfied Here T is the leading submatrix of order IPARAM5 of the upper triangular matrix stored worklipntr12 Example The following sets dimensions for this problem nx 10 nev 3 ncv 6 bmat I which LM maxiter 10 Local Arrays iparam zeros111 ipntr zeros141 select zerosncv1 d zerosnev11 resid zerosnx1 0i v zerosnxncv 0i workd zeros3nx11 0i workev zeros3ncv1 rwork zerosncv1 workl zeros3ncvncv5ncv1 0i Build the complex test matrix A diag10onesnx1ionesnx1 A112 A112 diag6onesnx11 A211 A211 diag6onesnx11 tol 0 ido 0 ishfts 1 maxitr 300 mode1 1 iparam1 ishfts zneupd 1954 iparam3 maxitr iparam7 mode1 sigma 0 the real part of the shift M A I N L O O P Reverse communication iter 0 whileitermaxiter infoznaupd 0 iter iter 1 Repeatedly call the routine ZNAUPD and take actions indicated by parameter IDO until either convergence is indicated or maxitr has been exceeded idoresidviparamipntrworkdworklinfoznaupd znaupdidobmatnxwhichnevtolresidncvviparamipntrworkdworklrworkinfoznaupd if ido99 then BE CAREFUL DONT CALL zneupd IF ido 99 break end if ido1 ido1 then Perform matrix vector multiplication workdipntr21ipntr2nx Aworkdipntr11ipntr1nx L O O P B A C K to call ZNAUPD again continue end if infoznaupd 0 then printf Error with znaupd info d infoznaupd printfCheck the documentation of znaupd else PostProcess using ZNEUPD rvec 1 howmany A infozneupd 0 dd12vresidviparamipntrworkdworklinfozneupd zneupdrvechowmanyselectdd12vsigmaworkev bmatnxwhichnevtolresidncvv iparamipntrworkdworklinfozneupd if infozneupd0 then printf Error with zneupd info d infozneupd printfCheck the documentation of zneupd end if infozneupd1 then printf Maximum number of iterations reached elseif infozneupd3 then printf No shifts could be applied during implicit Arnoldi update try increasing NCV end end end Done with program znsimp printf ZNSIMP zneupd 1955 printf printf printfIterations is d iter printfSize of the matrix is d nx printfThe number of Ritz values requested is d nev printfThe number of Arnoldi vectors generated NCV is d ncv printfWhat portion of the spectrum s which printfThe number of Implicit Arnoldi update iterations taken is d iparam3 printfThe number of OPx is d iparam9 printfThe convergence criterion is d tol See Also znaupd dnaupd dneupd Authors Danny Sorensen Richard Lehoucq Phuong Vu CRPC Rice University Applied Mathematics Rice University Houston Texas Bibliography 1 DC Sorensen Implicit Application of Polynomial Filters in a kStep Arnoldi Method SIAM J Matr Anal Apps 13 1992 pp 357385 2 RB Lehoucq Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration Rice University Technical Report TR9513 Department of Computational and Applied Mathematics 3 BN Parlett and Y Saad Complex Shift and Invert Strategies for Real Matrices Linear Algebra and its Applications vol 8889 pp 575595 1987 Used Functions Based on ARPACK routine zneupd Parte XXXVI Funções de Compatibilidade 1957 Name asciimat string matrix ascii conversions aasciimattxt txtasciimata Parameters txt character string or matrix of strings a vector or matrix of integer ASCII codes Description This function convert Scilab string to ASCII code or a matrix of ASCII code to Scilab string Output is a matrix having same number of lines than input what is not the case with ascii See Also ascii Authors VC 1958 Name firstnonsingleton Finds first dimension which is not 1 dimfirstnonsingletonAopt Parameters dim first dimension of A which is not 1 A a variable of any Scilab data type opt a character string giving the type of output we want num returned value is a numerical value str returned value is a character string if possible r instead of 1 and c instead of 2 Description This function is used by mfile2sci to emulate Matlab behavior under Scilab particularly for func tions which treat the values along the first nonsingleton dimension of A in Matlab while in Scilab they treat all values of A Examples A 1 2 34 5 6 Scilab max M maxA Matlab max emulation M maxAfirstnonsingletonA Authors VC 1959 Nom makecell Creates a cell array s makecelldimsa1a2an Parameters dims a vector with positive integer elements the cell array dimension a1a2an Sequence of Scilab variables n must be equal to proddims s resulting cell array Description s makecelldimsa1a2an creates a cell array of dimensions given by dims with the given input arguments The ai are stored along the last dimension first Examples makecell23123xyz See Also cell Authors Farid Belhacen INRIA 1960 Name mstr2sci character string matrix to character matrix conversion amstr2scitxt Parameters txt character string or string matrix a character vector or matrix Description This function converts a Scilab character string to a vector of characters Result is the Scilab equivalent for a Matlab string Caution mstr2sci has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 1961 Name mtlb0 Matlab nonconjugate transposition emulation function Description Matlab and Scilab nonconjugate transposition behave differently in some particular cases With character strings operands The operator is used to transpose whole character strings in Scilab while Matlab realizes the transposition of each character The function mtlb0A is used by mfile2sci to replace A when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlb0 calls If A is not a character string matrix mtlb0A may be replaced by A Caution mtlb0 has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 1962 Name mtlba Matlab addition emulation function Description Matlab and Scilab addition behave differently in some particular cases With character string operands The operator is used into Scilab to catenate character strings while Matlab realizes the sum of the operands ASCII codes With empty matrix In Scilab if one of the operands is an empty matrix the result of the addition is the other operand In Matlab if one of the operand is an empty matrix the result of the addition should be an error or an empty matrix The function mtlbaAB is used by mfile2sci to replace AB when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlba calls If A and B are character strings mtlbaAB may be replaced by asciimatAasciimatB If both A and B are not empty matrices mtlbaAB may be replaced by AB else mtlbaAB may be replaced by If mtlbmodeT then mtlbaAB may be replaced by AB in any case where A and B are not character string matrices Caution mtlba has not to be used for hand coded functions See Also mtlbmode Authors VC 1963 Name mtlball Matlab all emulation function Description Matlab all and Scilab and behave differently in some particular cases When used with one input allA Matlab all treats the values along the first nonsingleton dimension of A as vectors while Scilab and treats all A values When used with two inputs allAdim Matlab tolerates dim to be greater than the number of dimensions of A while Scilab returns an error message in this case The function R mtlballAdim is used by mfile2sci to replace allAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlball calls If A is a scalar or a vector R mtlballA may be replaced by R andA If A is a matrix R mtlballA may be replaced by R andA1 If A is an hypermatrix R mtlballA may be replaced by R andAfirstnonsingletonA or by R andAuserdefinedvalue if the first nonsingleton dimensions of A is known If dim is less equal to the number of dimensions of A R mtlballAdim may be replaced by R andAdim If dim is greater than then number of dimensions of A R mtlballAdim may be replaced by R A0 if A is not an empty matrix or by R A if A is an empty matrix Caution mtlball has not to be used for hand coded functions See Also firstnonsingleton Authors VC 1964 Name mtlbany Matlab any emulation function Description Matlab any and Scilab or behave differently in some particular cases When used with one input anyA Matlab any treats the values along the first nonsingleton dimension of A as vectors while Scilab or treats all A values When used with two inputs anyAdim Matlab tolerates dim to be greater than the number of dimensions of A while Scilab returns an error message in this case The function R mtlbanyAdim is used by mfile2sci to replace anyAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbany calls If A is a scalar or a vector R mtlbanyA may be replaced by R orA If A is a matrix R mtlbanyA may be replaced by R orA1 If A is an hypermatrix R mtlbanyA may be replaced by R orAfirstnonsingletonA or by R orAuserdefinedvalue if the first nonsingleton dimensions of A is known If dim is less equal to the number of dimensions of A R mtlbanyAdim may be replaced by R orAdim If dim is greater than then number of dimensions of A R mtlbanyAdim may be replaced by R A0 if A is not an empty matrix or by R A if A is an empty matrix Caution mtlbany has not to be used for hand coded functions See Also firstnonsingleton Authors VC 1965 Name mtlbaxis Matlab axis emulation function mtlbaxisX mtlbaxisst mtlbaxisaxeshandle modevisibilitydirectionmtlbaxisstate Parameters X a vector of reals xmin xmax ymin ymax or xmin xmax ymin ymax zmin zmax st a string auto manual tight ij xy equal square vis3d off on axeshandle handle of the current axes entity Description Matlab axis have not a Scilab equivalent function The function mtlbaxis is used by mfile2sci to replace axis when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will de termine the correct semantic at run time axis fill axis image and axis normal are not imple mented If you want to have a more efficient code it is possible to replace mtlbaxis call by getaxeshandle prop call prop is a axes property see axisproperties Caution mtlbaxis has not to be used for hand coded functions Authors FB 1966 Name mtlbbeta Matlab beta emulation function Description Matlab and Scilab beta behave differently in some particular cases With inputs having different sizes Matlab beta input parameters must have the same size unless one of them is a scalar In Scilab beta input parameters must have the same size even if one of them is a scalar The function mtlbbetaAB is used by mfile2sci to replace betaAB when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbbeta calls If A is a scalar but not B Y mtlbbetaAB may be replaced by CBCAY mtlbbetaCB If B is a scalar but not A Y mtlbbetaAB may be replaced by CACBY mtlbbetaAC Caution mtlbbeta has not to be used for hand coded functions Authors VC 1967 Name mtlbbox Matlab box emulation function Description There is no Scilab equivalent function for Matlab box but it can be easyly replaced The function mtlbboxaxeshandleval is used by mfile2sci to replace boxaxeshandleval when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbbox calls When called without input parameters mtlbbox may be replaced by agcaif aboxon then aboxoffelse aboxonend If axeshandle is a character string mtlbboxaxeshandle may be replaced by agcaaboxconvstraxeshandlel If axeshandle is a graphic handle mtlbboxaxeshandle may be replaced by if axeshandleboxon then axeshandleboxoffelse axeshandleboxonend If axeshandle is a graphic handle and val is a char acter string mtlbboxaxeshandleval may be replaced by axeshandleboxconvstrvall Caution mtlbbox has not to be used for hand coded functions See Also axesproperties Authors VC 1968 Name mtlbclose Matlab close emulation function Description Scilab equivalent for Matlab close is different according to the current figure type uicontrol or graphic one When current figure is a uicontrol one Scilab equivalent for Matlab close is close When current figure is a graphic one Scilab equivalent for Matlab close is xdel or delete In Scilab we do not get an error status The function mtlbcloseh is used by mfile2sci to replace closeh when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbclose calls If h is a uicontrol figure mtlbcloseh may be replaced by closeh If h is a graphic figure mtlbcloseh may be replaced by deleteh Caution mtlbclose has not to be used for hand coded functions See Also xdel delete winsid close Authors VC 1969 Name mtlbcolordef Matlab colordef emulation function Description There is no Scilab equivalent function for Matlab colordef but there are equivalent instructions The function h mtlbcolordefcoloroption or h mtlbcolordeffigcoloroption is used by mfile2sci to replace colordefcoloroption or colordeffigcoloroption when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbcolordef calls When called with one input parameter if coloroption is equal to black or none mtlbcolordefcoloroption may be replaced by fig gcffigbackground 1 When called with one input parameter if coloroption is equal to white mtlbcolordefcoloroption may be replaced by fig gcffigbackground 2 When called with two input parameters if fig is a graphic handle and coloroption is equal to black or none mtlbcolordefcoloroption may be replaced by figbackground 1 When called with two input parameters if fig is a graphic handle and coloroption is equal to white mtlbcolordefcoloroption may be replaced by figbackground 2 When called with two input parameters if fig is equal to new and coloroption is equal to black or none mtlbcolordefcoloroption may be replaced by fig scfmaxwinsid1figbackground 1 When called with two input parameters if fig is equal to new and coloroption is equal to white mtlbcolordefcoloroption may be replaced by fig scfmaxwinsid1figbackground 2 When called with one output parameter h just add h fig after equivalent instructions Caution mtlbcolordef has not to be used for hand coded functions See Also figureproperties Authors VC 1970 Name mtlbconv Matlab conv emulation function Description Matlab conv and Scilab convol behave differently in some particular cases With column vector inputs if at least input is a column vector Matlab conv returns a column vector but Scilab convol always returns a row vector The function mtlbconvuv is used by mfile2sci to replace convuv when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbconv calls If u and v are row vectors mtlbconvuv may be replaced by convoluv If u or v is a column vector mtlbconvuv may be replaced by convoluv If u and v are column vectors mtlbconvuv may be replaced by convoluv Scilab convol sometimes returns values that may be rounded using clean to have a closer result from Matlab one Caution mtlbconv has not to be used for hand coded functions See Also clean Authors VC 1971 Name mtlbcumprod Matlab cumprod emulation function Description Matlab and Scilab cumprod behave differently in some particular cases When used with one input cumprodA Matlab cumprod treats the values along the first non singleton dimension of A as vectors while Scilab cumprod treats all A values When used with two inputs cumprodAdim Matlab tolerates dim to be greater than the number of dimensions of A while Scilab returns an error message in this case The function R mtlbcumprodAdim is used by mfile2sci to replace cumprodAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbcumprod calls If dim is less equal to the number of dimensions of A R mtlbcumprodAdim may be replaced by R cumprodAdim If dim is greater than then number of dimensions of A R mtlbcumprodAdim may be replaced by R A Caution mtlbcumprod has not to be used for hand coded functions See Also firstnonsingleton Authors VC 1972 Name mtlbcumsum Matlab cumsum emulation function Description Matlab and Scilab cumsum behave differently in some particular cases When used with one input cumsumA Matlab cumsum treats the values along the first non singleton dimension of A as vectors while Scilab cumsum treats all A values When used with two inputs cumsumAdim Matlab tolerates dim to be greater than the num ber of dimensions of A while Scilab returns an error message in this case The function R mtlbcumsumAdim is used by mfile2sci to replace cumsumAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbcumsum calls If dim is less equal to the number of dimensions of A R mtlbcumsumAdim may be replaced by R cumsumAdim If dim is greater than then number of dimensions of A R mtlbcumsumAdim may be replaced by R A Caution mtlbcumsum has not to be used for hand coded functions See Also firstnonsingleton Authors VC 1973 Name mtlbdec2hex Matlab dec2hex emulation function Description Matlab and Scilab dec2hex behave differently in some particular cases With empty matrix Matlab dec2hex returns but in Scilab you get With complex inputs Matlab dec2hex automatically removes complex part of inputs but not Scilab one Matlab dec2hex always returns a row vector but in Scilab dec2hex returns a value which have the same size as the input Matlab dec2hex can have two inputs but not Scilab one The function mtlbdec2hexDN is used by mfile2sci to replace dec2hexDN when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdec2hex calls If D is not an empty matrix mtlbdec2hexD may be re placed by matrixdec2hexrealD11 if D is complex and by matrixdec2hexD11 else Caution mtlbdec2hex has not to be used for hand coded functions Authors VC 1974 Name mtlbdelete Matlab delete emulation function Description The function mtlbdeleteA is used by mfile2sci to replace deleteA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdelete calls If A is a character string mtlbdeleteA may be replaced by mdeleteA If A is a graphic handle mtlbdeleteA may be replaced by deleteA Caution mtlbdelete has not to be used for hand coded functions See Also mdelete Authors VC 1975 Name mtlbdiag Matlab diag emulation function Description Matlab and Scilab diag behave differently in some particular cases With character string matrices Scilab diag function considers each character string as an object while Matlab considers each character individually The function y mtlbdiagxdim is used by mfile2sci to replace y diagxdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdiag calls If x is not a character string matrix y mtlbdiagxdim may be replaced by y diagxdim Caution mtlbdiag has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 1976 Name mtlbdiff Matlab diff emulation function Description Matlab and Scilab diff behave differently in some particular cases With two input parameters Scilab diff considers all values of first input as a vector what Matlab does not With three input parameters If dimension of first input along dimension given by third parameter reaches 1 before n interations have been madeMatlab switches to next nonsingleton dimension what Scilab does not The function mtlbdiffAndim is used by mfile2sci to replace diffAndim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdiff calls With two inputs if A is a scalar or a vector mtlbdiffAn may be replaced by diffAn With three inputs if size of A along dimension given by dim can not reach 1 mtlbdiffAndim may be replaced by diffAndim Caution mtlbdiff has not to be used for hand coded functions Authors VC 1977 Name mtlbdir Matlab dir emulation function Description Matlab and Scilab dir behave differently When result is stored in a variable Matlab dir returns a structure but Scilab dir returns a dir tlist so data can not be extracted in the same way The function mtlbdirpath is used by mfile2sci to replace dirpath when out put is stored in a variable There is no replacement possibility for it else when mtlbdir is re placed by dir data can not be extracted like in Matlab For example Scilab equivalent for Matlab LdirfilenameL1name is LdirfilenameLname1 Caution mtlbdir has not to be used for hand coded functions Authors VC 1978 Name mtlbdouble Matlab double emulation function Description Matlab and Scilab double behave differently in some particular cases With character string input Scilab double does not work with this type of input while Matlab double returns a matrix of ASCII codes With boolean input Scilab double does not work with this type of input while Matlab double returns a matrix of double values The function mtlbdoubleA is used by mfile2sci to replace doubleA when it was not possible to know what were theinput while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbdouble calls If A is a character string mtlbdoubleA may be replaced by asciimatA If A is a boolean matrix mtlbdoubleA may be replaced by bool2sA If A is a double matrix mtlbdoubleA may be replaced by A Caution mtlbdouble has not to be used for hand coded functions See Also asciimat bool2s Authors VC 1979 Name mtlbe Matlab extraction emulation function Description Matlab and Scilab extraction behave differently in some particular cases When extracting data from a matrix with a vector as index Matlab returns a row vector and Scilab returns a column vector When extracting data from a character string matrix due to the fact that character string matrices in Matlab can be adressed as any other matrix each character can be adressed extraction in such a type of matrix does not differ from other But in Scilab it cant be done so and part function has to be used The function mtlbeBk is used by mfile2sci to replace ABk when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbe calls If B is a vector AmtlbeBk may be replaced by ABk If B is a matrix AmtlbeBk may be replaced by ABk If B is a character string matrix and k is a scalar or a vector AmtlbeBk may be replaced by ApartBk Caution mtlbe has not to be used for hand coded functions See Also MatlabScilabcharacterstrings part Authors VC 1980 Name mtlbecho Matlab echo emulation function Description There is no equivalent for Matlab echo in Scilab but some cases can be replaced by calls to Scilab mode echo is equivalent to Scilab modeabsmode1 for scripts and noncompiled functions echo on is equivalent to Scilab mode1 for scripts and noncompiled functions echo off is equivalent to Scilab mode0 The function mtlbechoarg1arg2 is used by mfile2sci to replace echo arg1 arg2 when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbecho calls If arg1 is equal to on mtlbechoarg1 may be replaced by mode1 If arg1 is equal to off mtlbechoarg1 may be replaced by mode0 Caution mtlbecho has not to be used for hand coded functions See Also mode Authors VC 1981 Name mtlbeval Matlab eval emulation function Description Scilab equivalent for Matlab eval is different according to its inputs and outputs The function mtlbevalstr1str2 is used by mfile2sci to replace eval because it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbeval calls When called with one input and no output mtlbevalstr1 may be replaced by evstrstr1 if str1 is a valid Scilab expression or by execstrstr1 if str1 is a valid Scilab instruction When called with one input and one output valmtlbevalstr1 may be replaced by valevstrstr1 if str1 is a valid Scilab instruction When called with two inputs and no output mtlbevalstr1str2 may be replaced by if execstrstr1errcatch0 then execstrstr2end if str1 and str2 are valid Scilab instructions When called with more than one output and one in put val1val2mtlbevalstr1 may be replaced by execstrval1val2str1 if str1 is a valid Scilab instruction When called with two inputs and more than one output val1val2mtlbevalstr1str2 may be replaced by if execstrval1val2str1errcatch0 then execstrval1val2str2 end if str1 and str2 are valid Scilab instructions Caution mtlbeval has not to be used for hand coded functions See Also evstr execstr Authors VC 1982 Name mtlbexist Matlab exist emulation function Description There is no Scilab equivalent for Matlab exist except when input is a variable Scilab mtlbexist is a partial emulation of of this function The function r mtlbexistnamtp is used by mfile2sci to replace existnamtp when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbexist calls When called with one input and if nam is a variable name mtlbexistnam may be replaced by existsnam Caution mtlbexist has not to be used for hand coded functions See Also exists Authors VC 1983 Name mtlbeye Matlab eye emulation function Description Matlab and Scilab eye behave differently in some particular cases With a scalar input Matlab eye returns a n x n matrix while Scilab returns a 1 The function mtlbeyeA is used by mfile2sci to replace eyeA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbeye calls If A is a scalar mtlbeyeA may be replaced by eyeAA If A is not a scalar mtlbeyeA may be replaced by eyeA Caution mtlbeye has not to be used for hand coded functions Authors VC 1984 Name mtlbfalse Matlab false emulation function Description There is no Scilab equivalent for Matlab false However Scilab zeros returns a result interpreted in an equivalent way for Scilab Matlab false and Scilab zeros behave differently in some particular cases With a scalar input Matlab false returns a n x n matrix of zeros while Scilab zeros returns a 0 The function mtlbfalseA is used by mfile2sci to replace falseA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfalse calls If A is a scalar mtlbfalseA may be replaced by zerosAA If A is not a scalar mtlbfalseA may be replaced by zerosA Caution mtlbfalse has not to be used for hand coded functions Authors VC 1985 Name mtlbfft Matlab fft emulation function Description Matlab and Scilab fft behave differently in some particular cases With one input parameter If input is a scalar or vector Scilab equivalent for Matlab fft is fft1 else if input is a matrix Scilab equivalent for Matlab fft is fft121 The function mtlbfftXnjob is used by mfile2sci to replace fftXn job when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfft calls If X is a scalar or a vector mtlbfftX1 may be replaced by fftX1 If X is a matrix mtlbfftX1 may be replaced by fftX121 Caution mtlbfft has not to be used for hand coded functions Authors VC 1986 Name mtlbfftshift Matlab fftshift emulation function Description Matlab and Scilab fftshift behave differently in some particular cases With character string input due to the fact that character strings are not considered in the same way in Matlab and Scilab results can be different for this kind of input With two inputs Matlab fftshift can work even if dim parameter is greater than number of dimensions of first input The function mtlbfftshiftAdim is used by mfile2sci to replace fftshiftAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfftshift calls If A is not a character string matrix mtlbfftshiftA may be replaced by fftshiftA If A is not a character string matrix and dim is not greater than sizesizea mtlbfftshiftAdim may be replaced by fftshiftAdim Caution mtlbfftshift has not to be used for hand coded functions Authors VC 1987 Name mtlbfind Matlab find emulation function Description Matlab and Scilab find behave differently in some particular cases With column vectors and matrices as input Matlab find returns column vectors while Scilab returns row vectors When called with three outputs Matlab find can have three outputs but Scilab not The function ijv mtlbfindB is used by mfile2sci to replace ijv findB when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfind calls When called with one output if B is a row vector i mtlbfindB may be replaced by i findB When called with one output if B is not a row vector i mtlbfindB may be replaced by i matrixfindB11 When called with two outputs if B is a row vector ij mtlbfindB may be replaced by ij findB When called with two outputs if B is not a row vector ij mtlbfindB may be replaced by ij findBi matrixi11j matrixj11 Caution mtlbfind has not to be used for hand coded functions Authors VC 1988 Name mtlbfindstr Matlab findstr emulation function Description There is no Scilab equivalent for Matlab findstr The function mtlbfindstrAB is used by mfile2sci to replace findstrAB when it was not possible to know what were the operandsinputsCUSTOM while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfindstr calls If A is always longer than B ie findstr can be replaced by strfind in Matlab mtlbfindstrAB may be replaced by strindexAB Caution mtlbfindstr has not to be used for hand coded functions Authors VC 1989 Name mtlbfliplr Matlab fliplr emulation function Description Matlab and Scilab fliplr behave differently in some particular cases With character string matrices due to te fact that Scilab and Matlab do not consider character string matrices in the same way result can be different for input of this type The function mtlbfliplrA is used by mfile2sci to replace fliplrA when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfliplr calls If A is not a character string matrix mtlbfliplrA may be replaced by A11 Caution mtlbfliplr has not to be used for hand coded functions Authors VC 1990 Name mtlbfopen Matlab fopen emulation function Description Matlab fopen and Scilab mopen behave differently in some particular cases Scilab function returns no usable error message Scilab file identified does not exist in case of error but Matlab one is set to 1 Matlab function can work with inputs which do not exist in Scilab such as permission options The function mtlbfopenfilenamepermission is used by mfile2sci to replace mopenfilenamepermission when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfopen calls If error message is not used and no error can occurs mtlbfopenfilenamepermission may be replaced by mopenfilenamepermission0 Caution mtlbfopen has not to be used for hand coded functions Authors VC 1991 Name mtlbformat Matlab format emulation function Description Matlab and Scilab format behave differently in some particular cases Some Matlab formats do not exist in Scilab Calling sequence for format is different in Scilab and Matlab The function mtlbformattypeprec is used by mfile2sci to replace formattype prec when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbformat calls If type and prec mtlbformat may be replaced by formatv6 If type and prec mtlbformat may be replaced by format6 If typelong and prec mtlbformatlong may be replaced by for mat16 If typelong and prece mtlbformatlonge may be replaced by formate16 If typelong and precg mtlbformatlongg may be replaced by formate16 If typeshort and prec mtlbformatshort may be replaced by for mat6 If typeshort and prece mtlbformatshorte may be replaced by formate6 If typeshort and precg mtlbformatshortg may be replaced by formate6 Caution mtlbformat has not to be used for hand coded functions Authors VC 1992 Name mtlbfprintf Matlab fprintf emulation function Description There is no Scilab exact equivalent for Matlab fprintf Scilab mfprintf and Matlab fprintf behave differently in many cases but they are equivalents in some cases The function mtlbfprintfvarargin is used by mfile2sci to replace fprintf This function will determine the correct semantic at run time It is sometimes possible to replace calls to mtlbfprintf by calls to mfprintf Caution mtlbfprintf has not to be used for hand coded functions See Also mfprintf Authors VC 1993 Name mtlbfread Matlab fread emulation function Description There is no Scilab equivalent for Matlab fread Scilab mget and Matlab fread behave differently in many cases but they are equivalents in some cases The function mtlbfreadvarargin is used by mfile2sci to replace fread This func tion will determine the correct semantic at run time It is sometimes possible to replace calls to mtlbfread by calls to mget Caution mtlbfread has not to be used for hand coded functions See Also mget Authors VC 1994 Name mtlbfscanf Matlab fscanf emulation function Description There is no Scilab exact equivalent for Matlab fscanf Scilab mfscanf and Matlab fscanf be have differently in many cases but they are equivalents in some cases The function mtlbfscanfvarargin is used by mfile2sci to replace fscanf This func tion will determine the correct semantic at run time It is sometimes possible to replace calls to mtlbfscanf by calls to mfscanf Caution mtlbfscanf has not to be used for hand coded functions See Also mfscanf Authors VC 1995 Name mtlbfull Matlab full emulation function Description Matlab and Scilab full behave differently in some particular cases With character strings input Matlab full can be used with character string input while Scilab function cannot With boolean input Matlab full can be used with boolean input while Scilab function cannot The function mtlbfullA is used by mfile2sci to replace fullA when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbfull calls If A is a double matrix mtlbfullA may be replaced by fullA If A is a boolean matrix mtlbfullA may be replaced by fullbool2sA Caution mtlbfull has not to be used for hand coded functions Authors VC 1996 Name mtlbfwrite Matlab fwrite emulation function Description There is no Scilab equivalent for Matlab fwrite Scilab mput and Matlab fwrite behave differ ently in many cases but they are equivalents in some cases The function mtlbfwritevarargin is used by mfile2sci to replace fwrite This func tion will determine the correct semantic at run time It is sometimes possible to replace calls to mtlbfwrite by calls to mput Caution mtlbfwrite has not to be used for hand coded functions See Also mput Authors VC 1997 Name mtlbgrid Matlab grid emulation function Description There is no Scilab equivalent function for Matlab grid but there are equivalent instructions The function mtlbgridflagorhandleflag is used by mfile2sci to replace gridflagorhandleflag when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbgrid calls With one input if flag is equal to on mtlbgridflag may be replaced by setgcagrid1 1 With one input if flag is equal to off mtlbgridflag may be replaced by setgcagrid1 1 With two inputs if flag is equal to on mtlbgridaxeshandleflag may be replaced by axeshandlegrid1 1 With two inputs if arg2 is equal to off mtlbgridaxeshandleflag may be replaced by axeshandlegrid1 1 Caution mtlbgrid has not to be used for hand coded functions See Also axesproperties Authors VC 1998 Name mtlbhold Matlab hold emulation function Description There is no Scilab equivalent function for Matlab hold but there are equivalent instructions The function mtlbholdflag is used by mfile2sci to replace hold flag when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbhold calls If flag is equal to on mtlbholdflag may be replaced by setgcaautoclearoff If flag is equal to off mtlbholdflag may be replaced by setgcaautoclearon Caution mtlbhold has not to be used for hand coded functions See Also axesproperties Authors VC 1999 Name mtlbi Matlab insertion emulation function Description Matlab and Scilab insertion behave differently in some particular cases When inserting a matrix in a variable Matlab automatically adjusts output variable to fit with matrix to insert but not Scilab For example with A1 A12341234 returns an error in Scilab while in Matlab we get A1234 If values miss comparing to indexes Matlab fills output value with 0 When inserting data into a character string matrix due to the fact that character string matrices in Matlab can be adressed as any other matrix each character can be adressed insertion in such a type of matrix does not differ from other But in Scilab it cant be done somtlbis is an alternative The function AmtlbiAkB is used by mfile2sci to replace AkB when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbi calls If A is not a vector AmtlbiAkB may be replaced by AkB If A and B are both row or column vectors AmtlbiAkB may be replaced by AkB Caution mtlbi has not to be used for hand coded functions See Also MatlabScilabcharacterstrings mtlbis Authors VC 2000 Name mtlbifft Matlab ifft emulation function Description Matlab ifft and Scilab fft behave differently in some particular cases With one input parameter If input is a scalar or vector Scilab equivalent for Matlab ifftA is fftA1 else if input is a matrix Scilab equivalent for Matlab fft is fftA121 The function mtlbifftXnjob is used by mfile2sci to replace ifftXn job when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbifft calls If X is a scalar or a vector mtlbifftX1 may be replaced by fftX1 If X is a matrix mtlbifftX1 may be replaced by fftX121 Caution mtlbifft has not to be used for hand coded functions Authors VC 2001 Name mtlbimp Matlab colon emulation function Description Matlab and Scilab colon behave differently in some particular cases With empty matrices The operator must be used with scalars in Scilab and gives an error message when used with empty matrices while Matlab returns in these cases The function mtlbimpABC is used by mfile2sci to replace ABC when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbimp calls If A B and C are not empty matrices mtlbimpABC may be replaced by ABC Caution mtlbimp has not to be used for hand coded functions Authors VC 2002 Name mtlbint16 Matlab int16 emulation function Description Matlab and Scilab int16 behave differently in some particular cases With complex input Matlab int16 can be used with complex values what Scilab function can not With inf Matlab int16 returns 32767 and Scilab returns 32768 With nan Matlab int16 returns 0 and Scilab returns 32768 With nan Matlab int16 returns 0 and Scilab returns 32768 The function mtlbint16A is used by mfile2sci to replace int16A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbint16 calls If A does not contain inf nan or nan values mtlbint16A may be replaced by int16A Caution mtlbint16 has not to be used for hand coded functions Authors VC 2003 Name mtlbint32 Matlab int32 emulation function Description Matlab and Scilab int32 behave differently in some particular cases With complex input Matlab int32 can be used with complex values what Scilab function can not With inf Matlab int32 returns 2147483647 and Scilab returns 2147483648 With nan Matlab int32 returns 0 and Scilab returns 2147483648 With nan Matlab int32 returns 0 and Scilab returns 2147483648 The function mtlbint32A is used by mfile2sci to replace int32A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbint32 calls If A does not contain inf nan or nan values mtlbint32A may be replaced by int32A Caution mtlbint32 has not to be used for hand coded functions Authors VC 2004 Name mtlbint8 Matlab int8 emulation function Description Matlab and Scilab int8 behave differently in some particular cases With complex input Matlab int8 can be used with complex values what Scilab function can not With inf Matlab int8 returns 127 and Scilab returns 0 With inf Matlab int8 returns 128 and Scilab returns 0 The function mtlbint8A is used by mfile2sci to replace int8A when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbint8 calls If A does not contain inf or inf values mtlbint8A may be replaced by int8A Caution mtlbint8 has not to be used for hand coded functions Authors VC 2005 Name mtlbis Matlab string insertion emulation function Description Matlab and Scilab insertion behave differently for strings due to the fact that they do not consider character strings in the same way The function str mtlbisstosfromij is used by mfile2sci to replace insertion operations for character strings This function will determine the correct semantic at run time There is no replacement possibility for it Caution mtlbis has not to be used for hand coded functions See Also MatlabScilabcharacterstrings mtlbi Authors VC 2006 Name mtlbisa Matlab isa emulation function Description There is no Scilab equivalent function for Matlab isa but some equivalent expressions can be used when the object class exists in Scilab The function mtlbisaOBJclass is used by mfile2sci to replace isaOBJclass when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbisa calls If class is equal to logical mtlbisaOBJclass may be replaced by typeOBJ4 If class is equal to char mtlbisaOBJclass may be replaced by typeOBJ10 If class is equal to numeric mtlbisaOBJclass may be replaced by ortypeOBJ158 If class is equal to intX X being equal to 8 16 or 32 mtlbisaOBJclass may be replaced by typeofOBJintX If class is equal to uintX X being equal to 8 16 or 32 mtlbisaOBJclass may be replaced by typeofOBJuintX If class is equal to single mtlbisaOBJclass may be replaced by typeOBJ1 If class is equal to double mtlbisaOBJclass may be replaced by typeOBJ1 If class is equal to cell mtlbisaOBJclass may be replaced by typeofOBJce If class is equal to struct mtlbisaOBJclass may be replaced by typeofOBJst If class is equal to functionhandle mtlbisaOBJclass may be replaced by typeOBJ13 If class is equal to sparse mtlbisaOBJclass may be replaced by typeOBJ5 If class is equal to lti mtlbisaOBJclass may be replaced by typeofOBJstatespace Caution mtlbisa has not to be used for hand coded functions See Also type typeof Authors VC 2007 Name mtlbisfield Matlab isfield emulation function Description There is no Scilab equivalent function for Matlab isfieldstf and equivalent expressions be have differently in some particular cases If st is not a structure Scilab equivalent returns an error message but Matlab returns 0 The function mtlbisfieldstf is used by mfile2sci to replace isfieldstf when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbisfield calls If st is a structure tf mtlbisfieldstf may be replaced by allfgetfield1sttforallf3f If st is not a structure tf mtlbisfieldstf may be replaced by tfF Caution mtlbisfield has not to be used for hand coded functions See Also getfield Authors VC 2008 Name mtlbisletter Matlab isletter emulation function Description There is no Scilab equivalent function for Matlab isletter and equivalent instructions are quite ugly so mfile2sci uses mtlbisletterA to replace isletterA If you want to have a more efficient code it is possible to replace mtlbisletter calls If A is not a character string tf mtlbisletterA may be replaced by tf zerosA If A is a character string tf mtlbisletterA may be replaced by tf asciimatA65asciimatA90 asciimatA97asciimatA122 Caution mtlbisletter has not to be used for hand coded functions Authors VC 2009 Name mtlbisspace Matlab isspace emulation function Description There is no Scilab function equivalent for Matlab isspace but its behavior can be reproduced The function mtlbisspaceA is used by mfile2sci to replace isspaceA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbisspace calls If A is a character string matrix mtlbisspaceA may be replaced by asciimatA32 If A is not a character string matrix mtlbisspaceA may be replaced by zerosA Caution mtlbisspace has not to be used for hand coded functions See Also asciimat Authors VC 2010 Name mtlbl Matlab left division emulation function Description Matlab and Scilab left division behave differently in some particular cases With character string operands The operator can not be used into Scilab with character strings while in Matlab it can And in this case result is transposed in a very strange way The function mtlblAB is used by mfile2sci to replace AB when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbl calls If both A and B are not character strings mtlblAB may be replaced by AB Caution mtlbl has not to be used for hand coded functions Authors VC 2011 Name mtlblegendre Matlab legendre emulation function P mtlblegendrenX P mtlblegendrenXnormflag Parameters X a scalar vector matrix or hypermatrix with elements in 11 n a positive scalar integer normflag a string sch or norm Description Matlab and Scilab legendre behave differently in some particular cases Scilab legendremnX evaluates the legendre function of degree n and order n for the X elements Matlab legendrenX evaluates the Legendre functions of degree n and order m01n emulated by mtlblegendre for the X elements The option normflag sch doesnt exist for Scilab legendre emulated If X is a hypermatrix then Scilab legendrenX doesnt work emulated The function mtlblegendrenXnormflag is used by mfile2sci to replace legendrenXnormflag when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblegendre call If X is a scalar a vector or a matrix mtlblegendrenXnorm may be replaced by legendren0nXnorm Caution mtlblegendre has not to be used for hand coded functions Authors FB 2012 Name mtlblinspace Matlab linspace emulation function Description Matlab and Scilab linspace behave differently in some particular cases With character string inputs Matlab linspaceABn returns a character string vector if A andor B are character strings but Scilab function does not work with such inputs The function mtlblinspaceABn is used by mfile2sci to replace linspaceABn when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblinspace calls If A and B are not character strings mtlblinspaceABn may be replaced by linspaceABn If A or B are character strings mtlblinspaceABn may be replaced by asciilinspaceasciiAasciiBn Caution mtlblinspace has not to be used for hand coded functions See Also ascii Authors VC 2013 Name mtlblogic Matlab logical operators emulation function Description Matlab and Scilab logical operator behave differently in some particular cases With complex operands The and operators can not be used into Scilab with complex operands while in Matlab they can And in this case only real part of complex operands is com pared With empty matrices If both operands of and operators are empty matrices Scilab returns an error message while Matlab returns an empty matrix For operators and if at least one operand is an empty matrix Matlab returns while Scilab returns a boolean value T or F The function mtlblogicAsymbolB with symbol a character string containing the oper ator symbol is used by mfile2sci to replace A symbol B when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblogic calls If both A and B are not complex values nor empty matrices mtlblogicAsymbolB may be replaced by A symbol B Caution mtlblogic has not to be used for hand coded functions Authors VC 2014 Name mtlblogical Matlab logical emulation function Description There is no Scilab equivalent function for Matlab logical but its behavior can be easyly reproduced The function mtlblogicalA is used by mfile2sci to replace logicalA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblogical calls If A is a boolean matrix mtlblogicalA may be replaced by A If A is not an empty matrix mtlblogicalA may be replaced by A If A is an empty matrix mtlblogicalA may be replaced by Caution mtlblogical has not to be used for hand coded functions Authors VC 2015 Name mtlblower Matlab lower emulation function Description Matlab lowerA and Scilab convstrAl behave differently in some particular cases If A is not a chacarter string matrix Matlab lower can be used with a notcharacterstring A but not Scilab convstr The function mtlblowerA is used by mfile2sci to replace lowerA when it was not pos sible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlblower calls If A is a character string matrix mtlblowerA may be replaced by convstrAl If A is not a character string matrix mtlblowerA may be replaced by A Caution mtlblower has not to be used for hand coded functions See Also convstr Authors VC 2016 Name mtlbmax Matlab max emulation function Description Matlab and Scilab max behave differently in some particular cases With complex values Matlab max can be used with complex values but not Scilab function When called with one input Matlab max threats values along the first nonsingleton dimension but Scilab threats all input values When called with two inputs if one is an empty matrix Scilab returns an error message but Matlab returns When called with three inputs if dim parameter is greater than number of dimensions of first input Scilab returns an error message and Matlab returns the first input The function rk mtlbmaxABdim is used by mfile2sci to replace rk maxABdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbmax calls When called with one input if A is a vector or a scalar rk mtlbmaxA may be replaced by maxA When called with one input if A is a matrix rk mtlbmaxA may be replaced by maxAr When called with two inputs if A and B are real matrices and not empty matrices rk mtlbmaxAB may be replaced by maxAB When called with three inputs if dim is lesser than the number of dimensions of A rk mtlbmaxAdim may be replaced by maxAdim Caution mtlbmax has not to be used for hand coded functions See Also firstnonsingleton Authors VC 2017 Name mtlbmin Matlab min emulation function Description Matlab and Scilab min behave differently in some particular cases With complex values Matlab min can be used with complex values but not Scilab function When called with one input Matlab min threats values along the first nonsingleton dimension but Scilab threats all input values When called with two inputs if one is an empty matrix Scilab returns an error message but Matlab returns When called with three inputs if dim parameter is greater than number of dimensions of first input Scilab returns an error message and Matlab returns the first input The function rk mtlbminABdim is used by mfile2sci to replace rk minABdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbmin calls When called with one input if A is a vector or a scalar rk mtlbminA may be replaced by minA When called with one input if A is a matrix rk mtlbminA may be replaced by minAr When called with two inputs if A and B are real matrices and not empty matrices rk mtlbminAB may be replaced by minAB When called with three inputs if dim is lesser than the number of dimensions of A rk mtlbminAdim may be replaced by minAdim Caution mtlbmin has not to be used for hand coded functions See Also firstnonsingleton Authors VC 2018 Name mtlbmore Matlab more emulation function Description Matlab more and Scilab lines behave differently in some particular cases With character strings as input Matlab more can take on and off as input but not Scilab lines but there are equivalents 0 and 60 The function mtlbmorein is used by mfile2sci to replace morein when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbmore calls If in is equal to on mtlbmorein may be replaced by lines60 If in is equal to off mtlbmorein may be replaced by lines0 If in is a double value mtlbmorein may be replaced by linesin Caution mtlbmore has not to be used for hand coded functions Authors VC 2019 Name mtlbnum2str Matlab num2str emulation function Description Matlab num2str and Scilab equivalents string msprintf behave differently in some partic ular cases With two input parameters the second giving precision There is no Scilab equivalent function but msprintf can be used to emulate With two input parameters the second giving format Scilab equivalent for Matlab num2stringaformat is msprintfformata The function mtlbnum2strxf is used by mfile2sci to replace num2strxf when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbnum2str calls If f is a character string mtlbnum2strxf may be replaced by msprintffx Caution mtlbnum2str has not to be used for hand coded functions See Also string msprintf Authors VC 2020 Name mtlbones Matlab ones emulation function Description Matlab and Scilab ones behave differently in some particular cases With a scalar input Matlab ones returns a n x n matrix while Scilab returns a 1 The function mtlbonesA is used by mfile2sci to replace onesA when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbones calls If A is a scalar mtlbonesA may be replaced by onesAA If A is not a scalar mtlbonesA may be replaced by onesA Caution mtlbones has not to be used for hand coded functions Authors VC 2021 Name mtlbplot Matlab plot emulation function Description Matlab plot and Scilab plot2d behave differently The function mtlbplotvarargin is used by mfile2sci to replace plotvarargin when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbplot calls when there is no output value however in this case you have to set colors manualy With one input if Y is real mtlbplotY may be replaced by plot2dY With one input if Y is complex mtlbplotY may be replaced by plot2drealYimagY With two inputs X and Y if Y is not a character string mtlbplotXY may be replaced by plot2dXY Caution mtlbplot has not to be used for hand coded functions See Also plot2d Authors VC 2022 Name mtlbprod Matlab prod emulation function Description Matlab and Scilab prod behave differently in some particular cases When called with one input Matlab prod threts the values along the first nonsingleton dimension of input while Scilab prod threats all values of input When called with two inputs Matlab prod can be used with second input giving a nonexisting dimension of first input while Scilab prod returns an error message The function mtlbprodAdim is used by mfile2sci to replace prodAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbprod calls When called with one input if A is an empty matrix a scalar or a vector mtlbprodA may be replaced by prodA When called with one input if A is a notempty matrix mtlbprodA may be replaced by prodA1 When called with one input if A is a multidimensional array mtlbprodA may be replaced by prodAfirstnonsingletonA When called with two inputs if dim is lesser than the number of dimensions of A mtlbprodAdim may be replaced by prodAdim Caution mtlbprod has not to be used for hand coded functions See Also firstnonsingleton Authors VC 2023 Name mtlbrand Matlab rand emulation function Description Matlab and Scilab rand behave differently in some particular cases With a scalar input Matlab rand returns a n x n matrix while Scilab returns a scalar The function mtlbrandA is used by mfile2sci to replace randA when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrand calls If A is a scalar mtlbrandA may be replaced by randAA If A is not a scalar mtlbrandA may be replaced by randA Caution mtlbrand has not to be used for hand coded functions Authors VC 2024 Name mtlbrandn Matlab randn emulation function Description Matlab rand and Scilab randnormal behave differently in some particular cases With a scalar input Matlab randn returns a n x n matrix while Scilab randnormal returns a scalar The function mtlbrandnA is used by mfile2sci to replace randnA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrandn calls If A is a scalar mtlbrandnA may be replaced by randAAnormal If A is not a scalar mtlbrandnA may be replaced by randAnormal Caution mtlbrandn has not to be used for hand coded functions Authors VC 2025 Name mtlbrcond Matlab rcond emulation function Description Matlab and Scilab rcond behave differently in some particular cases With empty matrix Matlab rcond returns Inf and Scilab rcond returns The function mtlbrcondA is used by mfile2sci to replace rcondA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrcond calls If A is not an empty matrix mtlbrcondA may be replaced by rcondA Caution mtlbrcond has not to be used for hand coded functions Authors VC 2026 Name mtlbrealmax Matlab realmax emulation function Description Scilab equivalent for Matlab realmax is numberproperties but not all cases are implemented Scilab equivalent for Matlab realmax or realmaxdouble is numberpropertieshuge There is no Scilab equivalent for Matlab realmaxsingle The function mtlbrealmaxprec is used by mfile2sci to replace realmaxprec when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrealmax calls If prec is equal to double mtlbrealmaxprec may be replaced by numberpropertieshuge Caution mtlbrealmax has not to be used for hand coded functions See Also numberproperties Authors VC 2027 Name mtlbrealmin Matlab realmin emulation function Description Scilab equivalent for Matlab realmin is numberproperties but not all cases are implemented Scilab equivalent for Matlab realmin or realmindouble is numberpropertiestiny There is no Scilab equivalent for Matlab realminsingle The function mtlbrealminprec is used by mfile2sci to replace realminprec when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrealmin calls If prec is equal to double mtlbrealminprec may be replaced by numberpropertiestiny Caution mtlbrealmin has not to be used for hand coded functions See Also numberproperties Authors VC 2028 Name mtlbrepmat Matlab repmat emulation function Description There is no Scilab equivalent function for Matlab repmat but there are equivalent instructions The function mtlbrepmatMmn is used by mfile2sci to replace repmatMmn when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbrepmat calls If A is of Double type and m is a scalar mtlbrepmatMm may be replaced by onesmmM and mtlbrepmatMmn may be replaced by onesmnM If A is of Boolean type and m is a scalar mtlbrepmatMm may be re placed by onesmmbool2sM and mtlbrepmatMmn may be replaced by onesmnbool2sM If A is of String type and m is a scalar mtlbrepmatMm may be replaced by asciimatonesmmasciimatM and mtlbrepmatMmn may be replaced by asciimatonesmnasciimatM If A is of Double type and m is a vector mtlbrepmatMm may be replaced by onesm1m2M If A is of Boolean type and m is a vector mtlbrepmatMm may be replaced by onesm1m2bool2sM If A is of String type and m is a vector mtlbrepmatMm may be replaced by asciimatonesm1m2asciimatM Caution mtlbrepmat has not to be used for hand coded functions See Also ones kron Authors VC 2029 Name mtlbs Matlab substraction emulation function Description Matlab and Scilab substraction behave differently in some particular cases With character string operands The operator can not be used into Scilab with character strings while Matlab realizes the substraction of the operands ASCII codes With empty matrix In Scilab if one of the operands is an empty matrix the result of the substraction is the other operand In Matlab if one of the operand is an empty matrix the result of the substraction should be an error or an empty matrix The function mtlbsAB is used by mfile2sci to replace AB when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbs calls If A and B are character strings mtlbsAB may be replaced by asciimatA asciimatB If both A and B are not empty matrices mtlbsAB may be replaced by AB else mtlbsAB may be replaced by If mtlbmodeT then mtlbsAB may be replaced by AB in any case where A and B are not character string matrices Caution mtlbs has not to be used for hand coded functions See Also mtlbmode Authors VC 2030 Name mtlbsetstr Matlab setstr emulation function Description Matlab setstr and Scilab ascii behave differently in some particular cases With character string input Matlab setstr returns a character string while Scilab ascii returns ASCII codes With double matrix input Matlab setstr returns a character matrix having the same size as input while Scilab ascii returns a single character string The function mtlbsetstrA is used by mfile2sci to replace setstrA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbsetstr calls If A is a character string or a character string matrix mtlbsetstrA may be replaced by A If A is a double row vector mtlbsetstrA may be replaced by asciiA Caution mtlbsetstr has not to be used for hand coded functions Authors VC 2031 Name mtlbsize Matlab size emulation function Description Matlab and Scilab size behave differently in some particular cases With two inputs Matlab size can be used with second parameter giving a notexisting dimension of first parameter returns 1 in this case but not Scilab one With more than one output if number of output is lesser than number of dimensions last output is the product of all remaining dimensions in Matlab but not in Scilab If number of output is greater than number of dimensions outputs corresponding to a notexisting dimension are set to 1 in Matlab but Scilab gives an error in this case The function d1d2 mtlbsizeXdim is used by mfile2sci to replace d1d2 sizeXdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbsize calls With two inputs if dim gives an existing dimension of X mtlbsizeXdim may be replaced by sizeXdim With more than one outputs if the number of outputs is equal to the number of dimensions of X d1d2 mtlbsizeX may be replaced by d1d2 sizeX Caution mtlbsize has not to be used for hand coded functions Authors VC 2032 Name mtlbsort Matlab sort emulation function P mtlbsortX P mtlbsortXdimmode Parameters X a scalar vector matrix of reals booleans or a string dim a positive scalar integer mode a string ascend or descend Description Matlab sort and Scilab gsort behave differently in some particular cases For a vector X the Matlab sortXgi function call is equivalent to the Scilab gsortX function call The value 1 resp 2 of the Matlab dim is equivalent to the Scilab r flag resp c The Matlab ascend resp descend mode is equivalent to the Scilab i resp d flag The function mtlbsortXdimmode is used by mfile2sci to replace sortXdimmode when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbsort call by gsort call Caution mtlbsort has not to be used for hand coded functions Authors FB 2033 Name mtlbstrcmp Matlab strcmp emulation function Description There is no Scilab function equivalent for Matlab strcmp there is equivalent instructions The function mtlbstrcmpAB is used by mfile2sci to replace strcmpAB when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbstrcmp calls If A and B are character strings mtlbstrcmpAB may be replaced by AB If A andor B is not a character string mtlbstrcmpAB may be replaced by 0 Caution mtlbstrcmp has not to be used for hand coded functions Authors VC 2034 Name mtlbstrcmpi Matlab strcmpi emulation function Description There is no Scilab function equivalent for Matlab strcmpi there is equivalent instructions The function mtlbstrcmpiAB is used by mfile2sci to replace strcmpiAB when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbstrcmpi calls If A and B are character strings mtlbstrcmpiAB may be replaced by convstrAconvstrB If A andor B is not a character string mtlbstrcmpiAB may be replaced by 0 Caution mtlbstrcmpi has not to be used for hand coded functions Authors VC 2035 Name mtlbstrfind Matlab strfind emulation function Description Matlab strfind and Scilab strindex behave differently in some particular cases With inputs which not character strings Matlab strfind can be used with not character strings inputs but not Scilab strindex The function mtlbstrfindAB is used by mfile2sci to replace strfindAB when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbstrfind calls If A and B are character strings mtlbstrfindAB may be replaced by strindexAB Caution mtlbstrfind has not to be used for hand coded functions Authors VC 2036 Name mtlbstrrep Matlab strrep emulation function Description Matlab strrep and Scilab strsubst behave differently in some particular cases With inputs which not character strings Matlab strrep can be used with not character strings inputs but not Scilab strsubst The function mtlbstrrepABC is used by mfile2sci to replace strrepABC when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbstrrep calls If A B and C are character strings mtlbstrrepABC may be replaced by strsubstABC Caution mtlbstrrep has not to be used for hand coded functions Authors VC 2037 Name mtlbsum Matlab sum emulation function Description Matlab and Scilab sum behave differently in some particular cases When called with one input Matlab sum threts the values along the first nonsingleton dimension of input while Scilab sum threats all values of input When called with two inputs Matlab sum can be used with second input giving a nonexisting dimension of first input while Scilab sum returns an error message The function mtlbsumAdim is used by mfile2sci to replace sumAdim when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbsum calls When called with one input if A is an empty matrix a scalar or a vector mtlbsumA may be replaced by sumA When called with one input if A is a notempty matrix mtlbsumA may be replaced by sumA1 When called with one input if A is a multidimensional array mtlbsumA may be replaced by sumAfirstnonsingletonA When called with two inputs if dim is lesser than the number of dimensions of A mtlbsumAdim may be replaced by sumAdim Caution mtlbsum has not to be used for hand coded functions See Also firstnonsingleton Authors VC 2038 Name mtlbt Matlab transposition emulation function Description Matlab and Scilab transposition behave differently in some particular cases With character strings operands The operator is used to transpose whole character strings in Scilab while Matlab realizes the transposition of each character The function mtlbtA is used by mfile2sci to replace A when it was not possible to know what were the operands while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbt calls If A is not a character string matrix mtlbtA may be replaced by A Caution mtlbt has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 2039 Name mtlbtoeplitz Matlab toeplitz emulation function Description Matlab and Scilab toeplitz behave differently in some particular cases With one input parameter if this parameter is complex or is a matrix output value of Matlab and Scilab toeplitz can be different With two input parameters if they are vectors and their first elements are not equal Scilab returns an error but Matlab gives priority to the column element If they are matrices output value of Matlab and Scilab toeplitz are different The function mtlbtoeplitzcr is used by mfile2sci to replace toeplitzcr when it was not possible to know what were the operandsinputsCUSTOM while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbtoeplitz calls When called with one input if c is a real scalar or vector mtlbtoeplitzc may be replaced by toeplitzc When called with two inputs if c and r are scalars or vectors and their first elements are equal mtlbtoeplitzcr may be replaced by toeplitzcr Caution mtlbtoeplitz has not to be used for hand coded functions Authors VC 2040 Name mtlbtril Matlab tril emulation function Description Matlab and Scilab tril behave differently in some particular cases With complex input Matlab tril can be used with complex data but not Scilab one With character strings inputs due to the fact the Matlab and Scilab do not consider character strings in the same way Scilab and Matlab tril do not give the same results for this type of input With boolean inputs Matlab tril can be used with boobean data but not Scilab one The function mtlbtrilxk is used by mfile2sci to replace trilxk when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbtril calls If X contains real double values mtlbtrilxk may be replaced by trilxk If X contains boolean values mtlbtrilxk may be replaced by trilbool2sxk Caution mtlbtril has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 2041 Name mtlbtriu Matlab triu emulation function Description Matlab and Scilab triu behave differently in some particular cases With complex input Matlab triu can be used with complex data but not Scilab one With character strings inputs due to the fact the Matlab and Scilab do not consider character strings in the same way Scilab and Matlab triu do not give the same results for this type of input With boolean inputs Matlab triu can be used with boobean data but not Scilab one The function mtlbtriuxk is used by mfile2sci to replace triuxk when it was not possible to know what were the inputs while porting Matlab code to Scilab This function will deter mine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbtriu calls If X contains real double values mtlbtriuxk may be replaced by triuxk If X contains boolean values mtlbtriuxk may be replaced by triubool2sxk Caution mtlbtriu has not to be used for hand coded functions See Also MatlabScilabcharacterstrings Authors VC 2042 Name mtlbtrue Matlab true emulation function Description There is no Scilab equivalent for Matlab true However Scilab ones returns a result interpreted in an equivalent way for Scilab Matlab true and Scilab ones behave differently in some particular cases With a scalar input Matlab true returns a n x n matrix of ones while Scilab ones returns a 1 The function mtlbtrueA is used by mfile2sci to replace trueA when it was not pos sible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbtrue calls If A is a scalar mtlbtrueA may be replaced by onesAA If A is not a scalar mtlbtrueA may be replaced by onesA Caution mtlbtrue has not to be used for hand coded functions Authors VC 2043 Name mtlbuint16 Matlab uint16 emulation function Description Matlab and Scilab uint16 behave differently in some particular cases With complex input Matlab uint16 can be used with complex values what Scilab function can not With inf Matlab uint16 returns 65535 and Scilab returns 0 The function mtlbuint16A is used by mfile2sci to replace uint16A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbuint16 calls If A does not contain inf values mtlbuint16A may be replaced by uint16A Caution mtlbuint16 has not to be used for hand coded functions Authors VC 2044 Name mtlbuint32 Matlab uint32 emulation function Description Matlab and Scilab uint32 behave differently in some particular cases With complex input Matlab uint32 can be used with complex values what Scilab function can not With inf Matlab uint32 returns 4294967295 and Scilab returns 0 The function mtlbuint32A is used by mfile2sci to replace uint32A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbuint32 calls If A does not contain inf values mtlbuint32A may be replaced by uint32A Caution mtlbuint32 has not to be used for hand coded functions Authors VC 2045 Name mtlbuint8 Matlab uint8 emulation function Description Matlab and Scilab uint8 behave differently in some particular cases With complex input Matlab uint8 can be used with complex values what Scilab function can not With inf Matlab uint8 returns 255 and Scilab returns 0 The function mtlbuint8A is used by mfile2sci to replace uint8A when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbuint8 calls If A does not contain inf values mtlbuint8A may be replaced by uint8A Caution mtlbuint8 has not to be used for hand coded functions Authors VC 2046 Name mtlbupper Matlab upper emulation function Description Matlab upperA and Scilab convstrAu behave differently in some particular cases If A is not a chacarter string matrix Matlab upper can be used with a notcharacterstring A but not Scilab convstr The function mtlbupperA is used by mfile2sci to replace upperA when it was not pos sible to know what were the inputs while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbupper calls If A is a character string matrix mtlbupperA may be replaced by convstrAu If A is not a character string matrix mtlbupperA may be replaced by A Caution mtlbupper has not to be used for hand coded functions See Also convstr Authors VC 2047 Name mtlbvar Matlab var emulation function Parameters x a real or a complex vector or matrix s a real scalar or real vector If x is a vector s is the variance of x If x is a matrix s is a row vector containing the variance of each column of x w type of normalization to use Valid values are depending on the number of columns m of x w 0 normalizes with m1 provides the best unbiased estimator of the variance this is the default w 1 normalizes with m this provides the second moment around the mean dim the dimension along which the variance is computed default is 1 ie column by column If dim is 2 the variance is computed row by row Description This function computes the variance of the values of a vector or matrix x It provides the same service as Octave and Matlab It differs from Scilabs variance primitive mtlbvar returns a real ie with a zero imaginary part variance even if x is a complex vector or matrix The Scilab variance primitive returns a complex value if the input vector x is complex and if no option additionnal is used Whatever the type of the input data x ie vector or matrix mtlbvar computes the variance either on dimension 1 or on dimension 2 while if no option is passed to the Scilabs variance primitive the variance is computed on all dimension at once Examples The following 3 examples illustrates the use of the mtlbvar function In the first case a column vector is passed to the function which returns the value 750 In the second case a matrix is passed to the function which returns the row vector 016 009 In the third case a complex column vector is passed to the function which returns a value close to 2 x 10 20 30 40 50 60 70 80 90 computed mtlbvarx x 09 07 01 01 05 04 computed mtlbvarx N1000 x grandN1nor01 igrandN1nor01 mtlbvar 2048 computed mtlbvarx See Also variance Authors Michael Baudin 2049 Name mtlbzeros Matlab zeros emulation function Description Matlab and Scilab zeros behave differently in some particular cases With a scalar input Matlab zeros returns a n x n matrix while Scilab returns a 0 The function mtlbzerosA is used by mfile2sci to replace zerosA when it was not possible to know what was the input while porting Matlab code to Scilab This function will determine the correct semantic at run time If you want to have a more efficient code it is possible to replace mtlbzeros calls If A is a scalar mtlbzerosA may be replaced by zerosAA If A is not a scalar mtlbzerosA may be replaced by zerosA Caution mtlbzeros has not to be used for hand coded functions Authors VC Parte XXXVII Interface Java 2051 Name javasciSciBoolean Class to use boolean object with scilab Description Method Summary public SciBooleanString nameSciBoolean Obj public SciBooleanString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public SciBooleanString nameboolean Value public String getNameGet Name of scilab object public boolean getDataGet Value of scilab object public void GetGet in java object value of scilab object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void SendSend to scilab object value of java object public void dispdisp object Examples See SCImodulesjavasciexamples directory See Also javasciScilab Compile and run with Javasci SciBooleanArray SciDoubleArray SciString SciStringArray Authors AC 2053 Name javasciSciBooleanArray Class to use boolean matrix in Scilab Description Method Summary public SciBooleanArrayString nameSciBooleanArray Obj public SciBooleanArrayString nameint rint c public SciBooleanArrayString nameint rint cboolean x Constructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public boolean getData Get Value of scilab object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void GetGet in java object value of scilab object public void SendSend to scilab object value of java object public boolean GetElementint indr int indcGet a specific element of scilab object Examples javasciSciBooleanArray 2054 See SCImodulesjavasciexamples directory See Also javasciScilab Compile and run with Javasci SciBoolean SciDouble SciString SciStringArray Authors AC 2055 Name javasciSciComplex Class to use complex object with scilab Description Method Summary public SciComplexString nameSciComplex Obj public SciComplexString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public SciComplexString namedouble realpartdouble imaginary part Constructor public String getNameGet Name of scilab object public double getRealPartDataGet Real Part Value of scilab object public double getImaginaryPartDataGet Imaginary Part Value of scilab object public void GetGet in java object value of scilab object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void SendSend to scilab object value of java object public void dispdisp object javasciSciComplex 2056 public void toStringconvert complex to a string Examples See SCImodulesjavasciexamples directory See Also javasciScilab Compile and run with Javasci SciComplexArray SciString SciStringArray Sci DoubleArray SciDouble Authors AC 2057 Name javasciSciComplexArray Class to use complex matrix in Scilab javasciSciComplexArray 2058 Description javasciSciComplexArray 2059 Method Summary public SciComplexArrayString nameSciComplexArray Obj public SciComplexArrayString nameint rint c public SciComplexArrayString nameint rint cdouble realpartdouble imaginarypartConstructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public double getRealPartDataGet Real Part Value of scilab object public double getImaginaryPartDataGet Imaginary Part Value of scilab object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void GetGet in java object value of scilab object public void SendSend to scilab object value of java object public double GetRealPartElementint indr int indcGet a specific element of scilab object public double GetImaginaryPartElementint indr int indcGet a specific element of scilab object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciComplex SciDouble SciDoubleArray SciString SciStringArray Authors AC 2060 Name javasciSciDouble Class to use double object with scilab Description Method Summary public SciDoubleString nameSciDouble Obj public SciDoubleString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public SciDoubleString namedouble Value public String getNameGet Name of scilab object public double getDataGet Value of scilab object public void GetGet in java object value of scilab object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void SendSend to scilab object value of java object public void dispdisp object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciDoubleArray SciString SciStringArray Authors AC 2062 Name javasciSciDoubleArray Class to use real matrix in Scilab Description Method Summary public SciDoubleArrayString nameSciDoubleArray Obj public SciDoubleArrayString nameint rint c public SciDoubleArrayString nameint rint cdouble x Constructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public double getData Get Value of scilab object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void GetGet in java object value of scilab object public void SendSend to scilab object value of java object public double GetElementint indr int indcGet a specific element of scilab object Examples javasciSciDoubleArray 2063 See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciDouble SciString SciStringArray Authors AC 2064 Name javasciSciInteger Class to use integer object with scilab Description Method Summary public SciIntegerString nameSciInteger Obj public SciIntegerString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public SciIntegerString nameint Value public String getNameGet Name of scilab object public int getDataGet Value of scilab object public void GetGet in java object value of scilab object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void SendSend to scilab object value of java object public void dispdisp object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciIntegerArray SciString SciStringArray Authors AC 2065 Name javasciSciIntegerArray Class to use int matrix in Scilab Description Method Summary public SciIntegerArrayString nameSciIntegerArray Obj public SciIntegerArrayString nameint rint c public SciIntegerArrayString nameint rint cint x Constructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public int getData Get Value of scilab object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public void GetGet in java object value of scilab object public void SendSend to scilab object value of java object public int GetElementint indr int indcGet a specific element of scilab object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciInteger SciString SciStringArray Authors AC 2066 Name javasciSciString Map a Java String into a Scilab string Description Method Summary public SciStringString nameSciString Obj public SciStringString name Constructor if name exists in Scilab and has the same type variable is imported from Scilab public String getNameGet Name of scilab object public void GetGet in java object value of scilab object public String getData Get Value of scilab object public void SendSend to scilab object value of java object public void disp disp object public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciDouble SciDoubleArray SciStringArray Authors AC 2068 Name javasciSciStringArray Classe to use String matrix in Scilab Description Method Summary public SciDoubleArrayString nameSciDoubleArray Obj public SciStringArrayString nameint rint c public SciStringArrayString nameint rint cString x Constructor public int getNumbersOfRowsGet number of rows public int getNumbersOfCols Get number of colons public String getNameGet Name of scilab object public String getDataGet Value of scilab object public void Get Get in java object value of scilab object public void Send Send to scilab object value of java object public void disp disp object javasciSciStringArray 2069 public boolean JobString jobdeprecated see ScilabExec Execute a job in scilab public String GetElementint indr int indcGet a specific element of scilab object Examples See SCImodulesJavasciexamples directory See Also javasciScilab Compile and run with Javasci SciDouble SciDoubleArray SciString Authors AC 2070 Name javasciScilab This class provides the basic methods to execute Scilab code and scripts Description This class is static Since the Scilab environnement is persistant all variables will remain accessible with the Java application Method Summary public static void Events Execute a Scilab event public static boolean HaveAGraph Check if there is any scilab graphic window open return True if it is the case public static boolean ExecString job Execute a job in scilab return true if there is no error Note that the given expression must be consistent by itself Then a serie of Exec defining a function will not work Please consider calling it with a single string instruction or using a temporary file with the method ExecuteScilabScript For example ScilabExecfunction foo dispbar end function will work when ScilabExecfunction foo ScilabExecdispbar ScilabExecendfunction will not work since each statement being processed independently public static native boolean ExistVarString VarName Detect if VarName exists in Scilab return true if Varname exist public static native int TypeVarString VarName Return Scilab type of VarName See type public static native int GetLastErrorCode Return last Error code See lasterror public static boolean ExecuteScilabScriptString scilabscriptfile name Execute a scilab script sce return true if there is no error public static native boolean Finish Terminate scilab call scilabquit close a scilab object Examples A Scilab Java example Filename ScilabExamplejava import javasciScilab public class ScilabExample public static void mainString args String myVarmyVariable ScilabExecmyVarpi490dispmyVariable Simple display if ScilabExistVarmyVar SystemoutprintlnVariable myVar exists Type ScilabTypeVarmyVar if ScilabExecdispplop Error javasciScilab 2071 SystemerrprintlnLast error ScilabGetLastErrorCode Error ScilabFinish See Also Compile and run with Javasci SciDouble SciDoubleArray SciString SciStringArray type lasterror Authors AC 2072 Name Compile and run with javasci How to compile a Java application using Javasci Description To compile a Java code based on Javasci it is only necessary to have javascijar defined in the class path For example with the code defined in the example of this page the command would be on LinuxUnixMacOSX javac cp SCImodulesjavascijarjavascijar BasicExamplejava on Windows D javac cp SCImodulesjavascijarjavascijar BasicExamplejava To run Scilab there are a few other things to set up Some global variables must me set SCI Path to Scilab files LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilabsharescilab In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabsource tree Windows path of scilab root directory set SCICprogram filesscilab51 LDLIBRARYPATH Paths to libscilabso and libjavasciso or jnilib LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilablibscilab In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabmod ulesjavascilibs and pathtoscilablibs Windows Path to libscilabdll and javascidll equivalent to LDLIBRARYPATH on Windows is PATH set PATHSCIbinPATH To launch the Java Application you can either provide them with environnement variable LinuxUnixMacOSX LDLIBRARYPATHpathtolibjavasci SCIpathtoscilab java cp modulesjavascijarjavascijar BasicExample SCIpathtoscilab java Djavalibrarypathpathtolibjavas ci cp modulesjavascijarjavascijar BasicExample Compile and run with javasci 2073 or with the arguments Windows set SCIcprogram filesscilab51 set PATHSCIbinPATH Djava cp SCImodulesjavascijarjavascijar BasicExample optional options to launch java DjavacompilerJIT Xmx256m With these arguments you launch javasci with same initial options that standard scilab Note that two environnement variables are taken in account for specific needs SCIDISABLETK1 Disables Tk Tcls GUI SCIJAVAENABLEHEADLESS1 Launch Java in headless mode no AWTSwing Examples A simple Java example Filename BasicExamplejava import javasciScilab public class BasicExample public static void mainString args ScilabExecdisppi26 See Also Javasci Javasci FAQ SciDouble SciDoubleArray SciString SciStringArray Authors Allan Cornet Sylvestre Ledru 2074 Name javasci Call Scilab engine from a Java application Description Scilab offers the possibility to be called from a Java application This help describes the features of the javasci API Examples A simple Java example Filename DisplayPIjava import javasciScilab public class DisplayPI public static void mainString args ScilabExecdisppi See Also Compile and run with Javasci Javasci FAQ SciDouble SciDoubleArray SciString SciStringArray Authors Allan Cornet Sylvestre Ledru 2075 Name javasci FAQ The frequently asked questions Questions Answers 1 Running an application based on javasci I get the error Exception in thread main javalangNoClassDefFoundError javasciScilab javascijar is probably not defined in the CLASSPATH See See Also Javasci Compile and run with javasci Authors Sylvestre Ledru Parte XXXVIII Interface Maple 2077 Name sci2map Scilab to Maple variable conversion txtsci2mapaMapname Parameters a Scilab object matrix polynomial list string Mapname string name of the Maple variable txt vector of strings containing the corresponding Maple code Description Makes Maple code necessary to send the Scilab variable a to Maple the name of the variable in Maple is Mapname A Maple procedure maple2scilab can be found in SCIDIRmaple directory Examples txtsci2map1 23 4a sci2maps23s4p Parte XXXIX Dicas de Conversão de Matlab para Scilab 2079 Name AboutM2SCItools Generally speaking about tools to convert Matlab files to Scilab Description Scilab 30 includes a new version of useful tools to convert Matlab Mfiles to Scilab Taking a Matlab Mfile mfile2sci modifies this files so that it can be compiled by Scilab After that this compiled code is converted to a tree of instructions by macr2tree This tree is an imbrication of Scilab lists and tlists and is the basis for conversion Each instruction of this tree is converted to Scilab and inference is done to known what are the variables Once this tree is converted to Scilab code is generated using tree2code All tlists used for coding this tree and we call MSCI tlists are listed below funcall tlist representing a function call created by Funcall operation tlist representing an operation created by Operation variable tlist representing a variable created by Variable cste tlist representing a constant created by Cste equal tlist representing an instruction created by Equal ifthenelse tlist representing an IFTHENELSE control instruction created inside M2SCI kernel functions while tlist representing a WHILE control instruction created inside M2SCI kernel functions selectcase tlist representing a SELECTCASE control instruction created inside M2SCI kernel functions for tlist representing a FOR control instruction created inside M2SCI kernel functions The contents of these tlists is described in corresponding help pages Operations are converted using a fonction named opcode2sci with opcode the Scilab code for this operator See help page for overloading to have these codes All these functions are already written and are in directory SCImodulesm2scimacrospercent Function calls are converted using a function called sciMatlabfunctionname Some of these functions have been written and are in directory SCImodulesm2scimacrosscifiles We are working on increasing the set of Matlab functions converted However everybody can written such functions using help page scifiles Inference is done using tlists of type infer containing fields dims list of dimensions type type tlist AboutM2SCItools 2080 contents contents tlist if a Cell or a Struct Type is a tlist of type type containing fields vtype data type property property To have more details about inference see help page for m2scideclare See Also mfile2sci translatepaths overloading scifiles Funcall Operation Variable Cste Infer Type Equal m2scideclare Authors VC 2081 Name Contents Create a tree containing contents inference data contentsContentslistofindexlistofinfer Parameters listofindex list of indexes similar to indexes returned by macr2tree listofinfer list of infer tlists containing inference data for matching index contents a contents tlist Description This function create a tlist representing inference data for the contents of a Cell or a Struct when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists Un known1 in M2SCI Please ensure that for each entry you insert in listofindex you also insert an entry in listofinfer See Also getcontentsinfer Funcall Operation Variable Cste Infer Type Equal Authors VC 2082 Name Cste Create a tree representing a constant constCstevalue Parameters value constante value const a cste tlist Description This function create a tlist representing a constant when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Funcall Operation Variable Infer Contents Type Equal Authors VC 2083 Name Equal Create a tree representing an instruction eqEquallhslistexpression Parameters lhslist list of lhs parameters list of M2SCI tlists expression right member of equal an M2SCI tlist eq an equal tlist Description This function create a tlist representing an instruction when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Funcall Operation Variable Cste Infer Contents Type Authors VC 2084 Name Funcall Create a tree representing a function call fcFuncallnamelhsnbrhslistlhslist Parameters name function name character string lhsnb number of outputs constant rhslist list of inputs list of M2SCI tlists lhslist list of outputs list of M2SCI tlists fc a funcall tlist Description This function create a tlist representing a function call when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Operation Variable Cste Infer Contents Type Equal Authors VC 2085 Name Infer Create a tree containing inference data inferInfervarargin Parameters varargin data for inference varargin1 list of dimensions default value is listUnknownUnknown varargin2 type type tlist see Type help page default value is TypeUnknownUnknown varargin3 contents contents tlist see Contents help page default value is Contentslistlist This field is only used if represented data is a Cell or a Struct infer an infer tlist Description This function create a tlist representing inference data when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists Unknown1 in M2SCI See Also Funcall Operation Variable Cste Contents Type Equal Authors VC 2086 Name MatlabScilabcharacterstrings Generally speaking about Description Matlab and Scilab character strings are not considered in the same way Here is a little talk about differences between them Matlab considers a character string as Scilab considers a matrix of characters For example a Scilab equivalent for Matlab mystring could be mystring So in Scilab a character string is a object of type string 10 and always have size 1 x 1 but in Matlab a character string have size equal to 1 x numberofcharacters Considering this we can see that a Matlab character string matrix column can only be made of same size character strings what is not true in Scilab We can say that a Scilab character string matrix is equivalent to a Matlab cell of character strings All these differences can lead to different results while executing same commands in Scilab or in Matlab particularly for dimension functions such as length or size See Also mstr2sci Authors VC 2087 Name Operation Create a tree representing an operation opOperationoperatoroperandsout Parameters operator operator symbol character string operands list of operands list of M2SCI tlists out list of outputs list of M2SCI tlists op an operation tlist Description This function create a tlist representing an operation when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Funcall Variable Cste Infer Contents Type Equal Authors VC 2088 Name Type Create a tree containing type inference data tpTypevtypeproperty Parameters vtype data type see m2scideclare property property of data see m2scideclare tp a type tlist Description This function create a tlist representing type inference data when using M2SCI All input param eters values are verified to be compatible with M2SCI tlists Unknown1 in M2SCI See Also Funcall Operation Variable Cste Infer Contents Equal m2scideclare Authors VC 2089 Name Variable Create a tree representing a variable varVariablenameinfer Parameters var variable name character string infer inference data a tlist of type infer see Infer help page var a variable tlist Description This function create a tlist representing a variable when using M2SCI All input parameters values are verified to be compatible with M2SCI tlists See Also Funcall Operation Cste Infer Contents Type Equal Authors VC 2090 Name getcontentsinfer Search for information in a M2SCi tlist contents inferposgetcontentsinferm2scitlistindex Parameters m2scitlist a M2SCI tlist index an index similar to indexes returned by macr2tree infer an infer tlist pos position of information in list Description This functions searches for inference informations of a given index in the contents of a Cell or a Struct taken in account the If no information has been found returned values are inferinfer and pos0 See Also Infer Contents Authors VC 2091 Name m2scideclare Giving tips to help M2SCI Description The main difficulty for M2SCI mfile2sci is to find what variables are dimensions type To help this tool just add comments beginning with m2scideclare in the Mfile to convert m2sciassume was used in previous Scilab versions and is now obsolete The syntax of this command is m2scideclare variablenamedimensionsdatatypeproperty with variablename name of the variable declared It can be a Struct field eg x12name or describe the contents of a Cell using syntax x12entries NOTE that for Cells and Structs can be used as an index see examples below dimensions dimensions of the variable declared separated by blanks if a dimension is unknown replace it by NOTE that String dimensions must be similar to Matlab ones eg 1 6 for character string string datatype data type of the variable which can be m2scideclare data type Scilab equivalent type Double 1 Boolean 4 Sparse 5 Int 8 Handle 9 String 10 Struct Matlab struct 16 Cell Matlab cell 17 Void No type 0 Unknown type property property of the variable which can be m2scideclare property Scilab equivalent Real Real data Complex Complex data Unknown property This field is ignored for following datatypes Cell Struct String and Boolean All data given by m2scideclare are compared with infered data in case of conflict infered data are kept and a warning message is displayed If you are sure about your data report a bug Some examples are given below m2scideclare var12 3DoubleRealvar1 is declared as a 2x3 Double matrix con taining real data m2scideclare 2092 m2scideclare var22 3 10DoubleComplexvar2 is declared as a 2x3x10 Double hypermatrix containing complex data m2scideclare var312name1 10Stringvar3 is declared as a Struct array containing a 1x10 character string in field name of struct at index 12 m2scideclare var415entries1 Booleanvar4 is declared as a Cell con taining a row boolean vector at index 15 m2scideclare var416entries Intvar4 is declared as a Cell containing a row boolean vector at index 15 and integer data at index 16 m2scideclare var5name1 Stringvar5 is declared as a Struct array containing a 1xn character string in all fields name m2scideclare var62entries1 3DoubleRealvar6 is declared as a Cell array containing a 1x3 double vector in each element of its second row Authors VC 2093 Name matfile2sci converts a Matlab 5 MATfile into a Scilab binary file matfile2scimatfilepathscifilepath Parameters matfilepath character string containing the path of the Matlab input file scifilepath character string containing the path of the Scilab output file Description Converts a Matlab 5 MATfile into a Scilab binary file compatible with the function load The Matlab data types are converted into the Scilab equivalents See Also loadmatfile load mfile2sci Authors Serge Steer INRIA Bibliography This function has been developped according to the document MATFile Format MatFile Format httpwwwmathworkscomaccesshelpdeskhelppdfdocmatlabmatfileformatpdf 2094 Name mfile2sci Matlab Mfile to Scilab conversion function mfile2sciMfilepath resultpath Recmode onlydouble verbosemode prettyprintoutput Parameters Mfilepath a character string which gives the path of Matlab Mfile to convert resultpath a character string which gives the directory where the result has to be written Default value is current directory Recmode Boolean flag used by translatepaths function for recursive conversion Must be F to convert a single mfile Default value f onlydouble Boolean flag if T mfile2sci considers that numerical function have been used only with numer ical data no Scilab overloading function is needed Default value F verbosemode display information mode 0 no information displayed 1 information written as comment is resulting SCIfile 2 information written as comment is resulting SCIfile and in logfile 3 information written as comment is resulting SCIfile in logfile and displayed in Scilab win dow prettyprintoutput Boolean flag if T generated code is beautified Default value F Description M2SCI and particularly mfile2sci is Matlab Mfile to Scilab function conversion tools It tries when ever possible to replace call to Matlab functions by the equivalent Scilab primitives and functions To convert a Matlab Mfile just enter the Scilab instruction mfile2scifile where file is a character string giving the path name of the Mfile mfile2sci will generate three files in the same directory functionnamesci the Scilab equivalent of the Mfile functionnamecat the Scilab help file associated to the function mfile2sci 2095 scifunctionnamesci the Scilab function required to convert the calls to this Matlab Mfile in other Matlab Mfiles This function may be improved by hand This function is only useful for conversion not for use of translated functions Some functions like eye ones size sum behave differently according to the dimension of their arguments When mfile2sci cannot infer dimensions it replaces these function call by a call to an emulation function named mtlbfunctionname For efficiency these functions may be re placed by the proper scilab equivalent instructions To get information about replacement enter help mtlbfunctionname in Scilab command window Some other functions like plot has no straightforward ï½quivalent in scilab They are also replaced by an emulation function named mtlbfunctionname When translation may be incorrect or may be improved mfile2sci adds a comment which begins by according to verbosemode When called without rhs mfile2sci launches a GUI to help to select a filedirectory and options Examples Create a simple Mfile writeTMPDIRrot90mfunction B rot90Ak mn sizeA if nargin 1 k 1 else k remk4 if k 0 k k 4 end end if k 1 A A B An11 elseif k 2 B Am11n11 elseif k 3 B Am11 B B else B A end Convert it to scilab mfile2sciTMPDIRrot90mTMPDIR Show the new code writeio2readTMPDIRrot90sci11a get it into scilab execTMPDIRrot90sci Execute it mrand42rot90m1 mfile2sci 2096 See Also translatepaths Authors V Couvert S Steer 2097 Name scifiles How to write conversion functions Description To convert calls to Matlab functions mfile2sci uses a function called sciMatlabfunctionname All these functions are defined in scifiles in directory SCImodulesm2scimacrosscifiles The set of scifiles given in Scilab distribution does not allow to convert calls to all Matlab functions yet However a Scilab user can add scifiles for Matlab functions or for user defined functions to Scilab using the following tips In M2SCI a function call is considered as a tree it is also the case for the instructions of the file to convert represented in Scilab by a tlist with following fields name Matlab function name lhsnb number of Matlab function output parameters lhs list of Matlab function output parameters rhs list of Matlab function input parameters A scifunction has one input called tree which is also the output of the function A scifunction has to convert this incoming tree so that it is compatible with Scilab by changing name lhsnb lhs andor rhs The other task that has to be done by this function is inference Incoming tree contains inference data in its lhs that have to be updated with what can be infered for the outputs of this function Some useful functions have been written to help to create M2SCI tlists while writing this conversion function Funcall create a tree representing a function call Operation create a tree representing an operation Variable create a tree representing a variable Cste create a tree representing a constante value Infer create a tree representing inference data Type create a tree representing type for inference Equal create a tree representing an instruction Some other functions have been designed to get properties of operandsinputs Considering A is tlist used in macro tree you can use the following functions Function returns T if scifiles 2098 isemptyA all dimensions of A are 0 notemptyA all dimensions of A are known and at least one dimension of A is not 0 isascalarA all dimensions of A are 1 notascalarA all dimensions of A are known and at least one dimension of A is not 1 isavectorA all dimensions of A are known and all dimensions of A but one are equal to 1 notavectorA all dimensions of A are known and at least two dimensions of A are greater than one isrealA A is real iscomplexA A is complex isdefinedvarA A is a variable already created in Mfile currently converted allunknownA all dimensions of A are unknown Some other functions have been written for specific needs while writing conversion files firstnonsingleton is an equivalent to firstnonsingleton for an M2SCI tlist Calling sequence dim firstnonsingletonA gettempvar generates a temporary variable having a name which does not already exist Calling sequence v gettempvar insert allows to insert instructions Calling sequence insertEqualopt with opt1 to insert before current instruction and opt1 to insert after it getoperands can be used to get each operand as a variable Calling sequence AB getoperandsoperationtlist getrhs can be used to get each parameter as a variable Calling sequence A getrhsfuncalltlist convert2double change type of input when this type is not implemented for a particular function is Scilab Calling sequence A convert2doubleA To have more information about how to write such files refer to directory SCImodulesm2scimacros scifiles which gives many examples from very simple ones eg sciabssci to very complex ones eg scizerossci See Also m2scideclare Funcall Operation Variable Cste Infer Type Equal Authors VC 2099 Name translatepaths convert a set of Matlab Mfiles directories to Scilab translatepathsdirspath respath Parameters dirspath a character string vector which gives the paths of Matlab Mfile directories to convert respath a character string which gives the path of the directory where the Scilab functions are written to Default value is current directory Description translatepaths converts all Matlab Mfile contained in a set of directories to Scilab functions Each function is converted by mfile2sci Trace of conversion information is stored in a file named log in the respath directory When called without rhs translatepaths launches a GUI to help to select a filedirectory and options See Also mfile2sci Authors V Couvert S Steer Parte XL Interfaces com TclTk 2101 Name ScilabEval tcl instruction Evaluate a string with scilab interpreter ScilabEval instruction ScilabEval instruction seq ScilabEval instruction sync ScilabEval instruction sync seq ScilabEval flush Parameters instruction tcl string character contains a Scilab instruction to evaluate with the current Scilab interpreter Description This function must be called in a tcltk script executed from Scilab It allows to associate Scilab actions to tcltk widgets graphic objects or to use Scilab to perform some computations within a tcl script ScilabEval instruction If the ScilabEval instruction syntax is used the instruction is first stored in a FIFO queue ScilabEval returns immediately Scilab executes the queued instructions when possible it should be at the prompt but also at the end of each instructions of the currently running function in the order they were submitted This syntax can be used to associate Scilab actions to tcltk widgets but not into a tcl script executed by TCLEvalFile or TCLEvalStr be cause in this situation the Scilab interpreter is blocked up to the end of the script Note that with the ScilabEval instruction syntax if there are many ScilabEval commands stored in the queue the execution of the second one can be started in the middle of the execution of the first one in particular if the first one contains more than a simple expression If the seq option is added the associated instruction evaluation should be finished or paused before the next queued instruction evaluation can be started The next callback stored in the com mand queue will only be taken into account when the current one will be finished or paused ScilabEval instruction sync If the ScilabEval instruction sync syntax is used the instruction is executed im mediately not queued and the ScilabEvalreturns when the instruction evaluation is finished The scilab instruction evaluation may be interrupted by new or queued commands If the seq option is added the associated instruction evaluation should be finished or paused before any queued instruction evaluation can be started The scilab instruction evaluation may not be interrupted by new or queued commands except if it is paused ScilabEval flush If the ScilabEval flush syntax is used all the previously queued instructions are executed immediately and the ScilabEval returns when the execution is finished Each in struction is executed with the option used at the time of queuing up ie seq or no option The evaluation context of all these cases is the current Scilab context when theinstruction eval uation starts Examples Callbacks and seq option usage ScilabEval 2102 create tcl instructions tclscripttoplevel w1 button w1b text Click here to execute without seq option command WithoutSeq button w1b1 text Click here to execute with seq option command WithSeq pack w1b w1b1 proc WithoutSeq ScilabEval contfcontt ScilabEval if cont then dispokelse dispwrongendcontf proc WithSeq ScilabEval contfcontt seq ScilabEval if cont then dispokelse dispwrongendcontf mputltclscriptTMPDIRtesttcl write them to a file Execute the tcl script contf TCLEvalFileTMPDIRtesttcl scripts and sync option usage without sync tclscript set t 0 while t 10 ScilabEval atmprintfd a incr t mputltclscriptTMPDIRtesttcl write them to a file Execute the tcl script TCLEvalFileTMPDIRtesttclmprintfTCLEvalFile finished The ScilabEval are executed after the and of TCLEvalFile with sync tclscript set t 0 while t 10 ScilabEval atmprintfd a sync incr t mputltclscriptTMPDIRtesttcl write them to a file Execute the tcl script TCLEvalFileTMPDIRtesttclmprintfTCLEvalFile finished The ScilabEval are executed synchronously with TCLEvalFile See Also TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar Authors Bertrand Guiheneuf 2103 Name TCLCreateSlave Create a TCL slave interpreter TCLCreateSlaveslaveName isSafe Parameters slaveName String Name of the TCL slave interpreter to create isSafe Boolean T to create a safe slave interpreter F otherwise The default value is F A safe slave is not allowed to perform some operations see the TCL documentation for more information Description This routine allows to create a TCL slave interpreter Examples TCLCreateSlaveTCLinterp TCLSetVararTCLinterp TCLExistVaraTCLinterp TCLExistVara TCLDeleteInterpTCLinterp TCLCreateSlaveTCLinterp T TCLSetVararTCLinterp TCLExistVaraTCLinterp TCLExistVara TCLDeleteInterpTCLinterp See Also TCLSetVar TCLExistVar TCLDeleteInterp Authors Allan CORNET VC 2104 Name TCLDeleteInterp delete TCL interpreter TCLDeleteInterpinterp TCLDeleteInterp Parameters interp character string parameter Name of the slave tcl interpreter to delete If not provided it defaults to the main tcl interpreter created by Scilab Description This routine allows to delete a TCL slave interpreter or the main scilab TCL interpreter Examples TCLSetVarScilabOK TCLExistVarScilab TCLDeleteInterp TCLExistVarScilab TCLCreateSlaveBisInterp TCLExistInterpBisInterp TCLSetVarScilabOKBisInterp TCLExistVarScilabBisInterp TCLDeleteInterpBisInterp TCLExistInterpBisInterp See Also TCLSetVar TCLExistVar TCLCreateSlave TCLExistInterp Authors Allan CORNET 2105 Name TCLEvalFile Reads and evaluate a tcltk file TCLEvalFilefilename interp Parameters filename character string Contains the name of the file to read and evaluate interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab Description With this routine one can read and evaluate the content of a file containing tcltk scripts This allows to create powerful tk interfaces The filename might be relative or absolute Advantages and drawbacks of this functionality This routines allows to use directly tcltk scripts This thus allows for instance to use Interface Builders such as SpecTcl to design the interface The interfaces built directly with tcltk scripts are much faster than the ones built with the Scilab Graphic Object library provided with tksci see uicontrol for exam ple Indeed those Objects are warpings around tk graphic widgets Nevertheless this way of creating graphic user interface should only be used when one aims at addressing directly specific tktcl features There are two main reasons for this First of all there is no simple way to manipulate Scilab objects from within a tcltk script Thus the interface designer has to write two sets of callbacks routines One to describe the changes occuring in the interface when the user acts on the widgets The second set of call routines will perform the pure Scilab reactions to the user actions Here is an example Suppose you design a scrollbar corresponding to a spline tension value You want the spline to be displayed in a graphic windows and updated each time the user moves the scrollbar At the same time you want the value of this tension parameter to be displayed within the Interface You will have to write a first tcltk callback function which will be automatically called by the tk scrollbar command option This callback function will update the displayed value of the parameter in the interface and will then call the scilab routine ScilabEval command to update the graph Remarks on the tcltk script style Because Scilab manages the tcltk events it creates the root window this window should not be destroyed nor directly used by your tcltk scripts You should thus always create your own toplevel windows Moreover since this module was written at a time when namespaces didnt exist some vari ables defined by scilab tcltk scripts could collide your code Running your scripts in a slave interpreter may help in such a case Examples TCLEvalFileSCImodulestclscidemostkpuzzle See Also ScilabEval TCLEvalStr TCLGetVar TCLSetVar TCLExistVar TCLUnsetVar TCLUpVar TCLEvalFile 2106 Authors Allan CORNET 2107 Name TCLEvalStr Evaluate a string whithin the TclTk interpreter TCLEvalStrstr interp res TCLEvalStrstr interp Parameters str string or matrix of strings contains a TclTk script in each element interp optional character string parameter Name of the slave Tcl interpreter in which the operation has to be performed If not provided it defaults to the main Tcl interpreter created by Scilab res result of the evaluation if it is successful This is a character string matrix giving the evaluation result for each element of the input argument str Description This routine allows to evaluate TclTk instructions with the TclTk interpreter launched with Scilab when the interp parameter is not given or in a slave interpreter When TclTk support is enabled in Scilab you can evaluate TclTk expression from Scilab interpreter In fact Scilab launches a main TclTk interpreter The Scilab instruction TCLEvalStr can be used to evaluate expressions without having to write TclTk instructions in a separated file this capability is provided by TCLEvalFile Examples with one call TCLEvalStrtoplevel foo1 label foo1l text TK married Scilab pack foo1l button foo1b text close command destroy foo1 pack foo1b step by step debugging TCLEvalStrtoplevel foo2 creates a toplevel TK window TCLEvalStrlabel foo2l text TK married Scilab create a static label TCLEvalStrpack foo2l pack the label widget It appears on the screen textbutton foo2b text close command destroy foo2 TCLEvalStrtext TCLEvalStrpack foo2b kill the windows by program TCLEvalStrdestroy foo1 TCLEvalStrdestroy foo2 TCLEvalStr 2108 with one call and in a slave interpreter TCLCreateSlaveTCLSlave TCLEvalStrset test in Slave TCL InterpTCLSlave TCLGetVartestTCLSlave TCLDeleteInterpTCLSlave return a result res TCLEvalStrexpr 11 res TCLEvalStrtkmessageBox message Hello type okcancel res TCLEvalStrexpr 45 lsearch all a b c a b c c list list a b c list d e f list g h i llength a b c d e See Also ScilabEval TCLEvalFile TCLGetVar TCLSetVar TCLExistVar TCLUnsetVar TCLUpVar Authors Allan CORNET 2109 Name TCLExistArray Return T if a tcl array exists OKTCLExistArrayarrayname interp Parameters arrayname character string Contains the name of the tcltk array interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab ok boolean T if arrayname exists Description This routine allows to test if a tcl array exists Examples TCLExistVarA aABCDEF TCLSetVarAa TCLExistVarA TCLExistArrayA See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar TCLUnsetVar TCLUpVar TCLCreateSlave Authors Allan CORNET 2110 Name TCLExistInterp Return T if a tcl slave interperter exists OKTCLExistInterpinterp Parameters interp character string parameter Name of the slave tcl interpreter ok boolean T if TCL interpreter exists Description This routine allows to test if TCL interpreter exists Examples TCLExistInterpSlaveInterp TCLCreateSlaveSlaveInterp TCLExistInterpSlaveInterp TCLDeleteInterpSlaveInterp See Also TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2111 Name TCLExistVar Return T if a tcl variable exists OKTCLExistVarvarname interp Parameters varname character string Contains the name of the tcltk variable interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab ok boolean T if varname exists Description This routine allows to test if a tcl variable exists Examples TCLSetVarScilabOK TCLGetVarScilab TCLUnsetVarScilab TCLExistVarScilab TCLSetVaraa1 TCLCreateSlaveSlaveInterp TCLSetVaraa2SlaveInterp TCLExistVaraa TCLGetVaraa TCLUnsetVaraa TCLGetVaraaSlaveInterp TCLUnsetVaraaSlaveInterp TCLExistVaraaSlaveInterp TCLDeleteInterpSlaveInterp See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar TCLUnsetVar TCLUpVar TCLCreateSlave Authors Allan CORNET 2112 Name TCLGetVar Get a tcltk variable value valueTCLGetVarVarname interp Parameters varname character string Contains the name of the tcltk variable interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab value may be a character string or a strings matrix Contains the value of the tcltk variable varname in the interpreter interp Description When tcltk support is enabled in Scilab this routine can be used to retreive the value of a tcltk variable Examples TCLEvalStrtoplevel tst1 creates a toplevel TK window TCLEvalStrentry tst1e textvariable tvar create an editable entry TCLEvalStrset tvar foobar set the entry value TCLEvalStrpack tst1e pack the entry widget It appears on the screen textTCLGetVartvar retrieve the variable value change the entry text and repeat the last command delete the toplevel TK window TCLEvalStrdestroy tst1 aABCDEF TCLSetVarAa AfromTCLTCLGetVarA b641235 TCLSetVarBb BfromTCLTCLGetVarB TCLGetVar 2113 TCLSetVarStringTCLstring StringFromTCLTCLGetVarStringTCL TCLSetVarScalarTCL122 ScalarFromTCLTCLGetVarScalarTCL Examples with a slave interpreter aAABBCCDDEEFF TCLCreateSlaveSlaveInterp TCLSetVarAslaveaSlaveInterp AfromTCLslaveTCLGetVarAslaveSlaveInterp TCLDeleteInterpSlaveInterp b664411223355 TCLCreateSlaveSlaveInterp1 TCLSetVarBslavebSlaveInterp1 BfromTCLslaveTCLGetVarBslaveSlaveInterp1 TCLDeleteInterpSlaveInterp1 TCLCreateSlaveSlaveInterp2 TCLSetVarStringTCLslavestring in slave interpreterSlaveInterp2 StringFromTCLslaveTCLGetVarStringTCLslaveSlaveInterp2 TCLDeleteInterpSlaveInterp2 TCLCreateSlaveSlaveInterp3 TCLSetVarScalarTCLslave122SlaveInterp3 ScalarFromTCLslaveTCLGetVarScalarTCLslaveSlaveInterp3 TCLDeleteInterpSlaveInterp3 See Also ScilabEval TCLEvalFile TCLEvalStr TCLSetVar TCLExistVar TCLUnsetVar TCLUpVar TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2114 Name TCLGetVersion get the version of the TCLTK library at runtime TCLGetVersion retTCLGetVersionnumbers Description get the version of the TCLTK library at runtime retTCLGetVersionnumbers returns a matrix with the version of the TCLTK library at runtime Examples TCLGetVersion TCLGetVersionnumbers Authors Allan CORNET 2115 Name TCLSetVar Set a tcltk variable value TCLSetVarvarname value interp Parameters varname character string Contains the name of the tcltk variable to set value may be a character string a scalar a real or string matrix m x n Contains the value to give to the tcltk variable interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab Description This routine allows to set a variable within a tcltk interpreter When tcltk support is enabled in scilab this routine can be used to set up the value of a tcltk variable This can be useful to change some value in the tcltk interpreter without having to build a tcltk instruction and use TCLEvalStr Examples TCLEvalStrtoplevel tst1 creates a toplevel TK window TCLEvalStrentry tst1e textvariable tvar create an editable entry TCLEvalStrset tvar foobar set the entry value TCLEvalStrpack tst1e pack the entry widget It appears on the screen textTCLGetVartvar retrieve the variable value change the entry text and repeat the last command delete the toplevel TK window TCLEvalStrdestroy tst1 aABCDEF TCLSetVarAa AfromTCLTCLGetVarA b641235 TCLSetVarBb BfromTCLTCLGetVarB TCLSetVar 2116 TCLSetVarStringTCLstring StringFromTCLTCLGetVarStringTCL TCLSetVarScalarTCL122 ScalarFromTCLTCLGetVarScalarTCL Examples with a slave interpreter TCLCreateSlaveTCLSlave aAABBCCDDEEFF TCLSetVarAslaveaTCLSlave AfromTCLslaveTCLGetVarAslaveTCLSlave TCLDeleteInterpTCLSlave TCLCreateSlaveTCLSlave b664411223355 TCLSetVarBslavebTCLSlave BfromTCLslaveTCLGetVarBslaveTCLSlave TCLDeleteInterpTCLSlave TCLCreateSlaveTCLSlave TCLSetVarStringTCLslavestring in slave interpreterTCLSlave StringFromTCLslaveTCLGetVarStringTCLslaveTCLSlave TCLDeleteInterpTCLSlave TCLCreateSlaveTCLSlave TCLSetVarScalarTCLslave122TCLSlave ScalarFromTCLslaveTCLGetVarScalarTCLslaveTCLSlave TCLDeleteInterpTCLSlave See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLExistVar TCLUnsetVar TCLUpVar TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2117 Name TCLUnsetVar Remove a tcl variable OKTCLUnsetVarvarname interp Parameters varname character string Contains the name of the tcltk variable to unset interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab ok boolean T if varname was deleted Description This routine allows to unset a tcl variable Examples TCLSetVarScilabOK TCLGetVarScilab TCLUnsetVarScilab TCLExistVarScilab TCLCreateSlaveInterpSlave TCLSetVarScilabGoodInterpSlave TCLGetVarScilabInterpSlave TCLUnsetVarScilabInterpSlave TCLExistVarScilabInterpSlave TCLDeleteInterpInterpSlave See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar TCLExistVar TCLUpVar TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2118 Name TCLUpVar Make a link from a tcl source variable to a tcl destination variable OKTCLUpVarvarname1varname2interp Parameters varname1 character string Contains the name of the tcl source variable varname2 character string Contains the name of the tcl destination variable interp optional character string parameter Name of the slave tcl interpreter in which the operation has to be performed If not provided it defaults to the main tcl interpreter created by Scilab ok boolean T if it is ok Description Make a link from a tcl source variable to a tcl destination variable Examples TCLSetVarScilabOK TCLUpVarScilabScilabBis TCLGetVarScilabBis TCLSetVarScilabNOK TCLGetVarScilabBis TCLSetVarScilabBismodified TCLGetVarScilabBis TCLGetVarScilab TCLCreateSlaveInterpBis TCLSetVarScilabGoodInterpBis TCLUpVarScilabScilabBisInterpBis TCLGetVarScilabBisInterpBis TCLSetVarScilabNot goodInterpBis TCLGetVarScilabBisInterpBis TCLSetVarScilabBismodified againInterpBis TCLGetVarScilabBisInterpBis TCLGetVarScilabInterpBis TCLDeleteInterpInterpBis See Also ScilabEval TCLEvalFile TCLEvalStr TCLGetVar TCLSetVar TCLExistVar TCLUnsetVar TCLCreateSlave TCLDeleteInterp Authors Allan CORNET 2119 Name browsevar Scilab variable browser browsevar Description browsevar is an embedded Scilab variable browser written in TCLTK browsevar can show all variables and function like who browsevar can be costumized to show all or some type of variable Its also posibble exclude variable names Examples browsevar Authors Jaime Urzua 2120 Name config Scilab general configuration config Description config allows configure scilab parameters like lines to display stacksize ODEOPTIONS Authors Jaime Urzua 2121 Name editvar Scilab variable editor editvar varname Parameters varname variable name The variable must exist in scilab Description editvar is an embedded Scilab variable editor written in TCLTK editvar can edit the following variable type real or complex constant matrix type 1 boolean matrix type 4 an matrix of character strings type 10 Examples arand1010 editvar a bhellogood bye editvar b Authors Jaime Urzua 2122 Name tkgetdir dialog to get a directory path pathtkgetdirTitlestring pathtkgetdirstartdirTitlestring pathtkgetdirstartdirwindowtitle Parameters startdir a character string which gives the initial directory used for directory search By default tkgetdir uses the previously selected directory path is the user selected file path if user answers Ok or the string if user answers Cancel Titlestring Optional argument which gives the title for the tkgetdir window Warning Use the new vari able Title instead of the old variable title Description WARNING this function is deprecated see uigetdir as a replacement of tkgetdir It will be removed in Scilab 53 Creates a dialog window for file selection Examples tkgetdir tkgetdirSCImodules tkgetdirTitleChoose a directory name See Also uigetdir uigetfile file fileinfo 2123 Name tksavefile dialog to get a file path for writing pathtksavefileTitlestring pathtksavefilefilemaskTitlestring pathtksavefilefilemaskdirTitlestring pathtksavefilefilemaskdirstring Parameters filemask a character string which gives the file mask to use for file selection filemask is written with Unix convention the default value is dir a character string which gives the initial directory used for file search by default tksavefile uses the previously selected directory path is the user selected file path if user answers Ok or the string if user answers Cancel Titlestring Optional argument which gives the title for the tksavefile window Warning Use the new variable Title instead of the old variable title Description WARNING this function is obsolete see uigetfile as a replacement of tksavefile It will be removed in Scilab 53 Creates a dialog window for output file selection Examples tksavefile tksavefilesciSCImodulesgraphicsmacros tksavefileTitleChoose a file name See Also uigetfile uigetdir file fileinfo 2124 Name winclose close windows created by sciGUI winclosewinIds Parameters winIds matrix of integer greater than 0 window identificator Description winclosewinIds close windows created by sciGUI Examples CREATE SOME WINDOWS win1waitbarThis is an example win2waitbarHELLO winclosewin1win2 Authors Jaime Urzua 2125 Name winlist Return the winId of current window created by sciGUI winIdswinlist Parameters winIds matrix of integer greater than 0 window identificator Description winlist Return the winId of current window created by sciGUI Authors Jaime Urzua Parte XLI Texmacs 2127 Name pol2tex convert polynomial to TeX format This function is obsolete and will be removed in Scilab 53 Please use prettyprint ypol2texx Parameters x polynomial y list Description Latex source code for the polynomial x For use with texprint This function is obsolete and will be removed in Scilab 53 Please use prettyprint Examples spoly0s ps32s5 pol2texp See Also prettyprint 2128 Name texprint TeX output of Scilab object This function is obsolete and will be removed in Scilab 53 Please use prettyprint text texprinta Parameters a Scilab object text list Description returns the Tex source code of the Scilab variable a a is a matrix constant polynomial rational or a linear system syslin list This function is obsolete and will be removed in Scilab 53 Please use prettyprint Examples spoly0s texprint1ss2 See Also prettyprint pol2str Parte XLII Manipulação de Arquivos de Som 2130 Name analyze frequency plot of a sound signal Parameters fminfmaxratepoints scalars default values fmin100fmax1500rate22050points8192 Description Make a frequency plot of the signal w with sampling rate rate The data must be at least points long The maximal frequency plotted will be fmax the minimal fmin Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound ssin440tsin220t2sin880t2 nrncsizet snc2ncsin330tnc2nc analyzes 2131 Name auread load au sound file yaureadaufile yaureadaufileext yFsbitsaureadaufile yFsbitsaureadaufileext Parameters aufile string The au extension is appended if no extension is given Fs integer frequency sampling in Hz ext string size or snd or integer to read n samples or 1 x 2 integer vector n1n2 to read from n1 to n2 Description Utility function to read au sound file aureadaufile loads a sound file specified by the string aufile returning the sampled data in y Amplitude values are in the range 11 Supports multichannel data in the following formats 8bit mulaw 8 16 and 32bit linear and floating point yFsbitsaureadaufile returns the sample rate Fs in Hertz and the number of bits per sample used to encode the data in the file aureadaufilen returns the first n samples from each channel aureadaufilen1n2 returns samples n1 to n2 aureadaufilesize returns the size of the audio data contained in the file in place of the actual audio data returning the vector as samples channels aureadaufilesnd returns information about the sample and data as a tlist Examples ywavreadSCImodulessounddemoschimeswav default is 8bits mulaw auwriteyTMPDIRtmpau y1aureadTMPDIRtmpau maxiabsyy1 See Also savewave analyze mapsound 2132 Name auwrite writes au sound file auwriteyaufile auwriteyFsaufile auwriteyFsbitsaufile auwriteyFsbitsmethodaufile Parameters y real vector or matrix with entries in 11 aufile string The au extension is appended if no extension is given Fs integer frequency sampling in Hz bits integer number of bits in the encoding method string mu default or linear encoding method Description Utility function to save au sound file auwriteyaufile writes a sound file specified by the string aufile The data should be arranged with one channel per column Amplitude values outside the range 11 are ignored Supports multichannel data for 8bit mulaw and 8 16 32 64 bits linear formats auwriteyFsaufile specifies in Fs the sample rate of the data in Hertz auwriteyFsbitsaufile selects the number of bits in the encoder Allowable settings are bits in 8163264 auwriteyFsbitsmethodaufile allows selection of the encoding method which can be either mu or linear Note that bits must be 8 for mu choice The default method is 8bits mulaw enconding Examples Amatrix1623 auwriteA62205064linearTMPDIRfooau BaureadTMPDIRfooau maxiabsA roundB6 See Also auread wavread savewave analyze mapsound 2133 Name beep Produce a beep sound beep beepon beepoff sbeep Description beep produces your computers default beep sound beepon turns the beep on beepoff turns the beep off sbeep returns the current beep mode on or off Authors AC 2134 Name lin2mu linear signal to mulaw encoding mulin2muy Parameters y real vector mu real vector Description Utility fct converts linear signal to mulaw encoding mu lin2muy converts linear audio signal amplitudes in the range 1 y 1 to mulaw in the range 0 mu 255 See Also mu2lin 2135 Name loadwave load a sound wav file into scilab xloadwavefilename xyloadwavefilename Parameters filename a string The path of the wav file to be loaded x a matrix one line for each channel y vector as data format number of channels samples per second per channel estimate of bytes per second needed byte alignment of a basic sample block bits per sample length of sound data in bytes bytes per sample per channel Description Reads a wav sound file into Scilab as a matrix If y is given it is filled with information about the samples See the message sent by loadwave Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound a two channels sound ssin2pi440tsin2pi350t savewaveTMPDIRfoowavs s1loadwaveTMPDIRfoowav maxabss1s See Also savewave analyze mapsound 2136 Name mapsound Plots a sound map mapsound wdtfminfmaxsimplrate Parameters dtfminfmaxsimplrate scalars default values dt01fmin100fmax1500simpl1rate22050 Description Plots a sound map for a sound It does FFT at time increments dt rate is the sampling rate simpl points are collected for speed reasons fmin and fmax are used for graphic boundaries Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound ssin440tsin220t2sin880t2 nrncsizet snc2ncsin330tnc2nc mapsounds 2137 Name mu2lin mulaw encoding to linear signal mulin2muy Parameters y real vector mu real vector Description Utility fct ymu2linmu converts mulaw encoded 8bit audio signals stored in the range 0 mu 255 to linear signal amplitude in the range s y s where s 3212432768 9803 The input mu is often obtained using mgetuc to read byteencoded audio files Translation of C program by Craig Reese IDASupercomputing Research Center Joe Campbell Department of Defense See Also mu2lin 2138 Name playsnd sound player facility playsndy playsndyratebits command Parameters y A matrix Each line descibe a channel fs real number sampling frequency default value is 22050 bits real number number of bits usually 8 or 16 Unused yet command Only used on Unix systems it gives the name of the command to use for playing sound wav files The defaut value is play If set devaudio then a 8 bits mulaw raw sound file is created and send to devaudio Description Plays a multi channel signal given by a Scilab matrix were sound is sampled at rate given by rate Examples a two channel signal yloadwaveSCImodulessounddemoschimeswav playsndy See Also lin2mu wavread 2139 Name savewave save data into a sound wav file savewavefilenamex rate nbits Parameters filename a string The path of the output wav file x a mxn matrix where m is the number of channels and n the number of samples for each channel rate a scalar giving the sampling rate number of sample per second 22050 is the default value Description save x into a wav sound file you can transform other sound files into wav file with the sox program Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound ssin2pi440tsin2pi220t2sin2pi880t2 nrncsizet snc2ncsin2pi330tnc2nc savewaveTMPDIRfoowavs See Also loadwave analyze mapsound 2140 Name sound sound player facility soundy fsbitscommand Parameters y real vector fs real number sampling frequency in sample per second default value is 22050 bits real number number of bits unused command Only used on Unix systems it gives the name of the command to use for playing sound wav files The defaut value is aplay If set devaudio then a 8 bits mulaw raw sound file is created and send to devaudio Description soundyfsplays the sound signal given by matrix y with sample frequency fs In fact this func tion is just a wrapper for playsnd Values in y are assumed to be in the range 10 y 10 Values outside that range are truncated The number of rows of y gives the number of channels soundy plays the sound at the default sample rate of 22050 sample per second soundyfsnbits plays the sound using nbits bitssample if possible it is in fact unused Most platforms support bits8 or 16 Examples a two channel signal yloadwaveSCImodulessounddemoschimeswav soundy See Also playsnd 2141 Name soundsec generates n sampled seconds of time parameter tsoundsecn rate Parameters n an integer the number of seconds to generate rate an integer the number of samples per second Description generates a vector coding time from 0 to nseconds at sampled rate rate Examples At first we create 05 seconds of sound parameters tsoundsec05 Then we generate the sound ssin2pi440t analyzes20060022050 See Also playsnd analyze 2142 Name wavread load wav sound file ywavreadwavfile ywavreadwavfileext yFsbitswavreadwavfile yFsbitswavreadwavfileext Parameters wavfile string The wav extension is appended if no extension is given Fs integer frequency sampling in Hz number of samples per second ext string size or stringinfo or integer to read n samples or 1 x 2 integer vector n1n2 to read from n1 to n2 Description Utility function to read wav sound file wavreadwavfile loads a sound file specified by the string wavfile returning the sampled data in y Amplitude values are in the range 11 Supports multichannel data in the following formats 8bit mulaw 8 16 and 32bit linear and floating point yFsbitswavreadwavfile returns the sample rate Fs in Hertz and the number of bits per sample used to encode the data in the file wavreadwavfilen returns the first n samples from each channel wavreadwavfilen1n2 returns samples n1 to n2 wavreadwavfilesize returns the size of the audio data contained in the file in place of the actual audio data returning the vector as channels samples wavreadwavfileinfo returns information about the audio data contained in the file in place of the actual audio data returning the vector as data format number of channels samples per second per channel estimate of bytes per second needed byte alignment of a basic sample block bits per sample length of sound data in bytes bytes per sample per channel Examples wavreadSCImodulessounddemoschimeswavsize yFsbitswavreadSCImodulessounddemoschimeswavFsbits subplot211 plot2dy1 first channel subplot212 plot2dy2 second channel ywavreadSCImodulessounddemoschimeswav1 5 the first five samples See Also auread savewave analyze mapsound 2143 Name wavwrite writes wav sound file wavwritey wavfile wavwritey Fs wavfile wavwritey Fs nbits wavfile Parameters y real vector or matrix with entries in 11 wavfile string The wav extension is appended if no extension is given Fs integer frequency sampling in Hz 22500 is the default value nbits bitdepth 8 16 24 32 bits it describes the number of bits of information recorded for each sample 16 is the default value Description Utility function to save wav sound file wavwriteywavfile writes a sound file specified by the string wavfile The data should be arranged with one channel per column Amplitude values outside the range 11 are ignored wavwriteyFswavfile specifies in Fs the sample rate of the data in Hertz Examples Amatrix1623 wavwriteA6TMPDIRfoowav BwavreadTMPDIRfoowav See Also auread wavread savewave analyze mapsound Parte XLIII Randlib 2145 Name grand Random number generators Ygrandm n disttype p1pk YgrandX disttype p1pk Ygrandn disttype p1pk Sgrandaction q1ql Parameters m n integers size of the wanted matrix Y X a matrix whom only the dimensions say m x n are used disttype a string given the distribution which independants variates are to be generated bin nor poi etc p1 pk the parameters reals or integers required to define completly the distribution disttype Y the resulting m x n random matrix action a string given the action onto the base generators setgen to change the current base generator getgen to retrieve the current base generator name getsd to retrieve the state seeds of the current base generator etc q1 ql the parameters generally one string needed to define the action S output of the action generaly a string or a real column vector Description This function may be used to generate random numbers from various distributions In this case you must apply one of the three first forms of the possible calling sequences to get an m x n matrix The two firsts are equivalent if X is a m x n matrix and the third form corresponds to multivalued distributions eg multinomial multivariate gaussian etc where a sample is a column vector says of dim m and you get then n such random vectors as an m x n matrix The last form is used to undertake various manipulations onto the base generators like changing the base generator since v 27 you may choose between several base generators changing or retrieving its internal state seeds etc These base generators give random integers following a uniform dis tribution on a large integer interval lgi all the others distributions being gotten from it in general via a scheme lgi U01 wanted distribution Getting random numbers from a given distribution beta YgrandmnbetAB generates random variates from the beta distribution with pa rameters A and B The density of the beta is 0 x 1 grand 2146 A1 B1 x 1x betaAB A and B must be reals 1037 Related functions cdfbet binomial YgrandmnbinNp generates random variates from the binomial distribution with parameters N positive integer and p real in 01 number of successes in N independant Bernouilli trials with probability p of success Related functions binomial cdfbin negative binomial YgrandmnnbnNp generates random variates from the negative binomial distribu tion with parameters N positive integer and p real in 01 number of failures occurring before N successes in independant Bernouilli trials with probability p of success Related functions cdfnbn chisquare Ygrandmnchi Df generates random variates from the chisquare distribution with Df real 00 degrees of freedom Related functions cdfchi non central chisquare YgrandmnnchDfXnon generates random variates from the non central chisquare distribution with Df degrees of freedom real 10 and noncentrality parameter Xnonc real 00 Related functions cdfchn exponential YgrandmnexpAv generates random variates from the exponential distribution with mean Av real 00 F variance ratio YgrandmnfDfnDfd generates random variates from the F variance ratio distri bution with Dfn real 00 degrees of freedom in the numerator and Dfd real 00 degrees of freedom in the denominator Related functions cdff non central F variance ratio YgrandmnnfDfnDfdXnon generates random variates from the noncentral F variance ratio distribution with Dfn real 1 degrees of freedom in the numerator and Dfd real 0 degrees of freedom in the denominator and noncentrality parameter Xnonc real 0 Related functions cdffnc gamma Ygrandmngamshapescale generates random variates from the gamma distri bution with parameters shape real 0 and scale real 0 The density of the gamma is shape shape1 scale x scale x e gammashape Related functions gamma cdfgam Gauss Laplace normal YgrandmnnorAvSd generates random variates from the normal distribution with mean Av real and standard deviation Sd real 0 Related functions cdfnor multivariate gaussian multivariate normal YgrandnmnMeanCov generates n multivariate normal random variates Mean must be a m x 1 matrix and Cov a m x m symmetric positive definite matrix Y is then a m x n matrix grand 2147 geometric Ygrandmngeom p generates random variates from the geometric distribution with parameter p number of Bernouilli trials with probability succes of p until a succes is met p must be in pmin1 with pmin 13 10307 Y contains positive real numbers with integer values with are the number of trials to get a suc cess markov YgrandnmarkovPx0 generate n successive states of a Markov chain described by the transition matrix P Initial state is given by x0 If x0 is a matrix of size msizex0 then Y is a matrix of size m x n Yi is the sample path obtained from initial state x0i multinomial YgrandnmulnbP generates n observations from the Multinomial distribution class nb events in m categories put nb balls in m boxes Pi is the probability that an event will be classified into category i P the vector of probabilities is of size m1 the probability of category m being 1sumP Y is of size m x n each column Yj being an observation from multinomial distribution and Yij the number of events falling in category i for the j th observation sumYj nb Poisson Ygrandmnpoimu generates random variates from the Poisson distribution with mean mu real 00 Related functions cdfpoi random permutations Ygrandnprmvect generate n random permutations of the column vector m x 1 vect uniform def Ygrandmndef generates random variates from the uniform distribution over 01 1 is never return uniform unf YgrandmnunfLowHigh generates random reals uniformly distributed in Low High uniform uin YgrandmnuinLowHigh generates random integers uniformly distributed be tween Low and High included High and Low must be integers such that HighLow1 2147483561 uniform lgi Ygrandmnlgi returns the basic output of the current generator random integers following a uniform distribution over 0 232 1 for mt kiss and fsultra 0 2147483561 for clcg2 0 231 2 for clcg4 0 231 1 for urand Setget the current generator and its state Since Scilab27 you have the possibility to choose between different base generators which give random integers following the lgi distribution the others being gotten from it grand 2148 mt the MersenneTwister of M Matsumoto and T Nishimura period about 219937 state given by an array of 624 integers plus an index onto this array this is the default generator kiss The Keep It Simple Stupid of G Marsaglia period about 2123 state given by 4 integers clcg2 a Combined 2 Linear Congruential Generator of P LEcuyer period about 261 state given by 2 integers this was the only generator previously used by grand but slightly modified clcg4 a Combined 4 Linear Congruential Generator of P LEcuyer period about 2121 state given by 4 integers this one is splitted in 101 different virtual non overlapping generators which may be useful for different tasks see Actions specific to clcg4 and Test example for clcg4 urand the generator used by the scilab function rand state given by 1 integer period of 231 based on theory and suggestions given in de knuth 1969 vol 2 State This is the faster of this list but a little outdated dont use it for serious simulations fsultra a SubtractwithBorrow generator mixing with a congruential generator of Arif Zaman and George Marsaglia period more than 10356 state given by an array of 37 integers plus an index onto this array a flag 0 or 1 and another integer The differents actions common to all the generators are action getgen Sgrandgetgen returns the current base generator S is a string among mt kiss clcg2 clcg4 urand fsultra action setgen grandsetgengen sets the current base generator to be gen a string among mt kiss clcg2 clcg4 urand fsultra notes that this call returns the new current generator ie gen action getsd Sgrandgetsd gets the current state the current seeds of the current base generator S is given as a column vector of integers of dimension 625 for mt the first being an index in 1624 4 for kiss 2 for clcg2 40 for fsultra 4 for clcg4 for this last one you get the current state of the current virtual generator and 1 for urand action setsd grandsetsdS grandsetsds1s2s3s4 sets the state of the current base generator the new seeds for mt S is a vector of integers of dim 625 the first component is an index and must be in 1624 the 624 last ones must be in 0232 but must not be all zeros a simpler initialisation may be done with only one integer s1 s1 must be in 0232 for kiss 4 integers s1s2 s3s4 in 0232 must be provided for clcg2 2 integers s1 in 12147483562 and s2 in 12147483398 must be given for clcg4 4 integers s1 in 12147483646 s2 in 12147483542 s3 in 12147483422 s4 in 12147483322 are required CAUTION with clcg4 you set the seeds of the current virtual generator but you may lost the synchronisation between grand 2149 this one and the others virtuals generators ie the sequence generated is not warranty to be non overlapping with a sequence generated by another virtual generator use instead the setall option for urand 1 integer s1 in 0231 must be given for fsultra S is a vector of integers of dim 40 the first component is an index and must be in 037 the 2d component is a flag 0 or 1 the 3d an integer in 1232 and the 37 others integers in 0232 a simpler and recommanded initialisation may be done with two integers s1 and s2 in 0232 action phr2sd Sdgrandphr2sd phrase given a phrase character string generates a 1 x 2 vector Sd which may be used as seeds to change the state of a base generator initialy suited for clcg2 Options specific to clcg4 The clcg4 generator may be used as the others generators but it offers the advantage to be splitted in several 101 virtual generators with non overlapping sequences when you use a classic generator you may change the initial state seeds in order to get another sequence but you are not warranty to get a complete different one Each virtual generator corresponds to a sequence of 272 values which is further split into V231 segments or blocks of length W241 For a given virtual generator you have the possibility to return at the beginning of the sequence or at the beginning of the current segment or to go directly at the next segment You may also change the initial state seed of the generator 0 with the setall option which then change also the initial state of the other virtual generators so as to get synchronisation ie in function of the new initial state of gen 0 the initial state of gen 1100 are recomputed so as to get 101 non overlapping sequences action setcgn grandsetcgnG sets the current virtual generator for clcg4 when clcg4 is set this is the virtual clcg4 generator number G which is used the virtual clcg4 generators are numbered from 01100 and so G must be an integer in 0100 by default the current virtual generator is 0 action getcgn Sgrandgetcgn returns the number of the current virtual clcg4 generator action initgn grandinitgnI reinitializes the state of the current virtual generator I 1 sets the state to its initial seed I 0 sets the state to its last previous seed ie to the beginning of the current segment I 1 sets the state to a new seed W values from its last seed ie to the beginning of the next segment and resets the current segment parameters action setall grandsetalls1s2s3s4 sets the initial state of generator 0 to s1s2s3s4 The initial seeds of the other generators are set accordingly to have synchronisation For con straints on s1 s2 s3 s4 see the setsd action action advnst grandadvnstK advances the state of the current generator by 2K values and resets the initial seed to that value grand 2150 Test example for clcg4 An example of the need of the splitting capabilities of clcg4 is as follows Two statistical techniques are being compared on data of different sizes The first technique uses bootstrapping and is thought to be as accurate using less data than the second method which employs only brute force For the first method a data set of size uniformly distributed between 25 and 50 will be generated Then the data set of the specified size will be generated and analyzed The second method will choose a data set size between 100 and 200 generate the data and analyze it This process will be repeated 1000 times For variance reduction we want the random numbers used in the two methods to be the same for each of the 1000 comparisons But method two will use more random numbers than method one and without this package synchronization might be difficult With clcg4 it is a snap Use generator 0 to obtain the sample size for method one and generator 1 to obtain the data Then reset the state to the beginning of the current block and do the same for the second method This assures that the initial data for method two is that used by method one When both have concluded advance the block for both generators See Also rand Authors randlib The codes to generate sequences following other distributions than def unf lgi uin and geom are from Library of Fortran Routines for Random Number Generation by Barry W Brown and James Lovato Department of Biomathematics The University of Texas Houston mt The code is the mt19937intc by M Matsumoto and T Nishimura Mersenne Twister A 623 dimensionally equidistributed uniform pseudorandom number generator ACM Trans on Mod eling and Computer Simulation Vol 8 No 1 January pp330 1998 kiss The code was given by G Marsaglia at the end of a thread concerning RNG in C in several news groups whom scimathnumanalysis My offer of RNGs for C was an invitation to dance only kiss have been included in Scilab kiss is made of a combinaison of severals others which are not visible at the scilab level clcg2 The method is from P LEcuyer but the C code is provided at the Luc Devroye home page http cgmcsmcgillcalucrnghtml clcg4 The code is from P LEcuyer and Terry HAndres and provided at the P LEcuyer home page httpwwwiroumontrealcalecuyerpapershtml A paper is also provided and this new pack age is the logical successor of an old s one from P LEcuyer and S Cote Implementing a Ran dom Number Package with Splitting Facilities ACM Transactions on Mathematical Software 171pp 98111 fsultra code from Arif Zaman arifstatfsuedu and George Marsaglia geostatfsuedu scilab packaging By JeanPhilippe Chancelier and Bruno Pincon Parte XLIV Ferramentas de Desenvolvimento 2152 Name benchrun Launch benchmark tests benchrun benchrunmoduletestnameoptions Parameters module a vector of string It can be the name of a module or the absolute path of a toolbox testname a vector of string options a vector of string list list of the benchmark tests available in a module help displays some examples of use in the Scilab console nbrunvalue repeat the benchmark test value times Description Search for tst files in benchmark test library execute them and display a report about execution time The tst files are searched in directories SCImodulestestsbenchmark Special tags may be inserted in the tst file which help to control the processing of the corresponding test These tags are expected to be found in Scilab comments These are the available tags BENCH NB RUN 10 This test will be repeated 10 times BENCH START BENCH END The interesting part of the benchmark must be en closed by these tags Examples Some simple examples of invocation of benchrun Launch all tests benchrun benchrun benchrun Test one or several module benchruncore benchruncore benchruncorestring Launch one or several test in a specified module benchruncoretrycatchopcode benchrun 2153 With options benchrunlist benchrunhelp benchrunnbrun2000 An example of a benchmark file This file corresponds to the file SCImoduleslinearalgebratests benchmarksbenchcholtst Scilab httpwwwscilaborg This file is part of Scilab Copyright C 20072008 INRIA This file is distributed under the same license as the Scilab package Benchmark for chol function BENCH NB RUN 10 stacksize30000000 a 0 b 0 a rand900 900 n a aa BENCH START b chola BENCH END The result of the test benchrunlinearalgebrabenchchol Boucle For 019 µs 1000000 x 001001 linearalgebra benchchol 15157671 µs 10 x See Also testrun Authors Yann Collette 2154 Name tbxbuildcleaner Generate a cleanersce script toolbox compilation process tbxbuildloadertoolboxname tbxbuildloadertoolboxname toolboxpath Parameters toolboxname Toolbox short name that is the prefix of the start file of the toolbox which shall be in the etc subdirectory toolboxpath Root directory of toolbox sources the script will be generated here default current directory Examples Recommended usage tbxbuildcleanermytoolbox getabsolutefilepathbuildersce Authors Allan CORNET 2155 Name tbxbuildgateway Build a gateway toolbox compilation process tbxbuildgatewaylibname names files gatewaypath libs ldflags cflags fflags cc makename ismex Parameters libname a character string the generic name of the library without path and extension names 2 column string matrix giving the table of pairs scilabname interface name files string matrix giving objects files needed for shared library creation gatewaypath Path to the sources of the gateway in a normal toolbox it should be the directory containing the buildergatewaylangsce script which should be the script calling this function Default is current directory libs string matrix giving extra libraries needed for shared library creation ldflagscflagsfflags character strings to provide options for the loader the C compiler and the Fortran compiler cc character string The name of or path to the compiler makename character string The path of the Makefile file without extension ismex Internal variable to specify if we are working with mex or not Examples Recommended usage tbxbuildgatewaymytoolbox csumscicsumcsubscicsub scicsumcscicsubc getabsolutefilepathbuildergatewaycsce srcclibcsum See Also ilibbuild Authors SL 2156 Name tbxbuildgatewayclean Generate a cleanergatewaysce script toolbox compilation process tbxbuildgatewayloaderlangs tbxbuildgatewayloaderlangs gatewaypath Parameters langs Languages of source files gatewaypath Path to the sources of the gateway in a normal toolbox it should be the directory containing the buildergatewaysce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildgatewaycleanc fortran getabsolutefilepathbuildergatewaysce Authors Allan CORNET 2157 Name tbxbuildgatewayloader Generate a loadergatewaysce script toolbox compilation process tbxbuildgatewayloaderlangs tbxbuildgatewayloaderlangs gatewaypath Parameters langs Languages of source files gatewaypath Path to the sources of the gateway in a normal toolbox it should be the directory containing the buildergatewaysce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildgatewayloaderc fortran getabsolutefilepathbuildergatewaysce Authors SL 2158 Name tbxbuildhelp Generate help files toolbox compilation process tbxbuildhelptitle tbxbuildhelptitle helppath Parameters title Title of the chapter helppath Directory where the files will be generated in a normal toolbox it should be the directory con taining the buildhelpsce script which should be the script calling this function Default is cur rent directory Examples Recommended usage tbxbuildhelpToolbox Example getabsolutefilepathbuildhelpsce Authors SL 2159 Name tbxbuildhelploader Generate a addchaptersce script toolbox compilation process tbxbuildhelploadertitle tbxbuildhelploadertitle helppath Parameters title Title of the chapter helppath Directory where the script will be generated in a normal toolbox it should be the directory con taining the buildhelpsce script which should be the script calling this function Default is cur rent directory Examples Recommended usage tbxbuildhelploaderToolbox Example getabsolutefilepathbuildhelpsce Authors SL 2160 Name tbxbuildloader Generate a loadersce script toolbox compilation process tbxbuildloadertoolboxname tbxbuildloadertoolboxname toolboxpath Parameters toolboxname Toolbox short name that is the prefix of the start file of the toolbox which shall be in the etc subdirectory toolboxpath Root directory of toolbox sources the script will be generated here default current directory Examples Recommended usage tbxbuildloadermytoolbox getabsolutefilepathbuildersce Authors SL 2161 Name tbxbuildmacros Compile macros toolbox compilation process tbxbuildmacrostoolboxname tbxbuildmacrostoolboxname macrospath Parameters toolboxname Toolbox short name that is the prefix of the start file of the toolbox which shall be in the etc subdirectory macrospath Directory where the macros files can be found and where the compiled macros will be placed into in a normal toolbox it should be the directory containing the buildmacrossce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildmacrostoolboxexample getabsolutefilepathbuildmacrossce Authors SL 2162 Name tbxbuildsrc Build sources toolbox compilation process tbxbuildsrcnames files flag srcpath libs ldflags cflags fflags cc libname loadername makename Parameters names a string matrix giving the entry names which are to be linked files string matrix giving objects files needed for shared library creation flag a string flag c or f for C or Fortran entry points srcpath Path to the source files in a normal toolbox it should be the directory containing the buildersrclangsce script which should be the script calling this function Default is current directory libs string matrix giving extra libraries needed for shared library creation ldflags optional character string It can be used to add specific linker options in the generated Makefile Default value is cflags optional character string It can be used to add specific C compiler options in the generated Make file Default value is fflags optional character string It can be used to add specific Fortran compiler options in the generated Makefile Default value is cc optional character string It can be used to specify a C compiler Default value is libname optional character string The name of the generated shared library default value is and in this case the name is derived from names1 loadername character string The pathname of the loader file default value is loadersce makename character string The pathname of the Makefile file without extension default value Makelib Examples Recommended usage tbxbuildsrccsumcsub csumccsubc c getabsolutefilepathbuildercsce tbxbuildsrc 2163 See Also ilibforlink Authors SL 2164 Name tbxbuildergateway Run buildergatewaysce script if it exists toolbox compilation process tbxbuildergatewaytoolboxpath Parameters toolboxpath Root directory of toolbox sources buildergatewaysce script will be searched in the scigateway subdirectory of this directory Examples Recommended usage tbxbuildergatewaygetabsolutefilepathbuildersce Authors SL 2165 Name tbxbuildergatewaylang Run buildergatewaylanguagesce script if it exists toolbox compi lation process tbxbuildergatewaylanglang tbxbuildergatewaylanglang gwpath Parameters lang Language of sources files the buildergatewaylangsce script will be searched in the subdi rectory lang eg fortran of the gwpath directory gwpath Path to the sources of the gateway in a normal toolbox it should be the directory containing the buildergatewaysce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildergatewaylangfortran getabsolutefilepathbuildergatewaysce Authors SL 2166 Name tbxbuilderhelp Run builderhelpsce script if it exists toolbox compilation process tbxbuilderhelptoolboxpath Parameters toolboxpath Root directory of toolbox sources builderhelpsce script will be searched in the help subdirec tory of this directory Examples Recommended usage tbxbuilderhelpgetabsolutefilepathbuildersce Authors SL 2167 Name tbxbuilderhelplang Run buildhelpsce script if it exists toolbox compilation process tbxbuilderhelplanglang tbxbuilderhelplanglang helppath Parameters lang Language of help files to use the buildhelpsce script will be searched in the subdirectory lang eg enUS of the helppath directory helppath Path to help directory in a normal toolbox it should be the directory containing the builderhelpsce script which should be the script calling this function Default is current direc tory Examples Recommended usage tbxbuilderhelplangenUS getabsolutefilepathbuilderhelpsce Authors SL 2168 Name tbxbuildermacros Run buildmacrossce script if it exists toolbox compilation process tbxbuildermacrostoolboxpath Parameters toolboxpath Root directory of toolbox sources buildmacrossce script will be searched in the macros subdi rectory of this directory Examples Recommended usage tbxbuildermacrosgetabsolutefilepathbuildersce Authors SL 2169 Name tbxbuildersrc Run buildersrcsce script if it exists toolbox compilation process tbxbuildersrctoolboxpath Parameters toolboxpath Root directory of toolbox sources buildersrcsce script will be searched in the src subdirectory of this directory Examples Recommended usage tbxbuildersrcgetabsolutefilepathbuildersce Authors SL 2170 Name tbxbuildersrclang Run builderlanguagesce script if it exists toolbox compilation process tbxbuildersrclanglang tbxbuildersrclanglang srcpath Parameters lang Language of sources files the builderlangsce script will be searched in the subdirectory lang eg fortran of the srcpath directory srcpath Path to the sources in a normal toolbox it should be the directory containing the buildersrcsce script which should be the script calling this function Default is current directory Examples Recommended usage tbxbuildersrclangfortran getabsolutefilepathbuildersrcsce Authors SL 2171 Name testrun Launch tests N testrun N testrunmoduletestnameoptions Parameters module a vector of string It can be the name of a module or the absolute path of a toolbox testname a vector of string options a vector of string nocheckref does not check if the dia and diaref are equal nocheckerroroutput createref create the diaref file and does not check if the dia and diaref are equal list does not perform the tests but displays a list of available tests help display some examples about how to use this command modenw add the nw option to the launch modenwni add the nwni option to the launch nonregtest runs only the nonregression tests skipping unit tests unittest runs only the unit tests skipping nonregression tests skiptests Description Search for tst files in the unit test and nonregression test library execute them and display a report about success of failures The tst files are searched in directories SCImodulestestsunittests and SCImodulestestsnonregtests Whenever a test is executed a dia file is generated which contains the full list of commands executed along with message which appears in the console When the script is done the dia file is compared with the diaref file which is expected to be in the same directory as the tst file If the two file are different the test fails Special tags may be inserted in the tst file which help to control the processing of the corresponding test These tags are expected to be found in Scilab comments These are the available tags INTERACTIVE TEST This test will be skipped because it is interactive NOT FIXED This test will be skipped because it is a known but unfixed bug TEST WITH GRAPHIC This test will not be executed if the option modenwni is used NO TRY CATCH testrun 2172 NO CHECK ERROR OUTPUT The error output file is not checked NO CHECK REF The dia and the diaref files are not compared ENGLISH IMPOSED This test will be executed with the l enUS option FRENCH IMPOSED This test will be executed with the l frFR option JVM NOT MANDATORY This test will be executed with the nwni mode by default WINDOWS ONLY If the operating system isnt Windows the test is skipped UNIX ONLY If the operating system isnt an unix OS the test is skipped LINUX ONLY If the operating system isnt Linux the test is skipped MACOSX ONLY If the operating system isnt MacOSX the test is skipped Each test is executed in a separated process created with the host command That enables the current command to continue even if the test as created an unstable environment It also enables the tests to be independent from one another Platformspecific tests It may happen that the output of a test depends on the platform on which it is executed In this case the ref file cannot be correct for all platforms and unit tests may fail for some platform In this case we can create a default ref and create additionnal ref file for each platform The various platformspecific ref files must have one of the following extensions unixdiaref for Unix platform linuxdiaref for Linux platform windiaref for Windows platform macosxdiaref for Mac OS X platform The algorithm is the following First the ref is considered If this file does not exist the plat formspecific ref file is examined depending on the current platform on windows platforms windiaref on Max OS X platforms unixdiaref macosxdiaref on Linux platforms unixdiaref linuxdiaref Examples Launch all tests testrun testrun testrun Test one or several module Test one module testrun 2173 testruntime Test several modules testruntimestring Test a submodule testrunoptimizationneldermead Refer to a module by its path testrunSCImodulescore Launch a specific test One specific test testruntimedatenum Several tests testruntimedatenumcalendar Skip some tests testruntimedatenumcalendarskiptests Options does not check if the dia and diaref are equal testruntimedatenumnocheckref Create the diaref file and does not check if the dia and diaref are equal testruncreateref Does not perform the tests but displays a list of available tests testrunlist Display some examples about how to use this command testrunhelp Runs only the nonregression tests skipping unit tests testrunnonregtest Runs only the unit tests skipping nonregression tests testrununittest Do not check the error output std err testrunbooleanbug2799nocheckerroroutput Combine several options testrunnocheckrefmodenw Internal Design The tests are performed in the temporary directory not in the directory which originaly contain the tests files The tst file is copied into the temporary directory the test is performed and the diaref is copied back into the original location testrun 2174 The tst script is not run as is Instead a header and a footer are inserted at the beginning and at the end of the tst at the time the script is copied into the temporary directory The role of this modification is to redirect the output messages into the dia file so that the user can have a log file once the test is performed Authors Pierre Maréchal Michael Baudin Parte XLV Ferramentas de Demonstração 2176 Nom demobegin begin a demonstration demobegin Description The function demobegin is used to begin a demonstration It sets the script and the values in mode of non display on the console save the environment variables in a temporary file and save the width of the console This function shall be used with the function demoend Voir Aussi demoend demorun demomessage Auteurs GH 2177 Name demochoose create a dialog box for the choice of options num demochoosefil Description The function demochoose create a dialog box for the choice of options It takes as argument the binary file fil This file is built by a sce file written like below It shall contain the variables choice an array of text within bracket the different options and titl the title of the dialog box After that the sce file shall save both variables in the binary file in argument Before the use of demochoose the sce file shall be executed The function demochoose returns the number of line chosen in the options array Examples execSCIdemoscontrolpidpidch2sce ndemochooseSCIdemoscontrolpidpidch2bin select n case 0 break case 1 mode1 case 2 mode1 end See Also xchoose demomdialog Authors GH 2178 Name democompiler test the presence of a compileur status democompiler Description The function democompiler asks the computer if it owns a compileur C or not It returns a boolean indicating wether the compiler exists or not Examples select num case 0 return case 2 then st democompiler The compiler will be used if stt then mode0 wheelbuildandload end case 1 then A precomputed value xreadpathxwrt8301 wheelgwheelgs showx end See Also findmsvccompiler Authors GH 2179 Nom demoend completes a demonstration demoend Description The function demoend is used to complete a demonstration It shall be used complementarily with the function demobegin It resets the state of the environment as it was before to use the function demobegin width of the console and the variables value Voir Aussi demobegin demorun demomessage Auteurs GH 2180 Name demofilechoice choose and executes an item within a list demofilechoicepathch Description The function demofilechoice choose and executes an item chosen in the demolist variable that shall be written above The variable demolist is a text matrix whose first column contains names of items displayed in an options window and whose second column contains the names of the files that will be executed The title of the options window is Choose a demo The path variable is the access to the files called in the second column The ch variable allows to avoid the special cases root and anim that are used in peculiar demonstrations of Scilab Then you have to enter another word than root or ch no for example If you choose to cancel the options window the console is put back to its previous width Examples demolistnpendulumnpendnpendgatewaysce Wheel simulationwheel2wheelgatewaysce Bike Simulationbikebikegatewaysce ODESodeodedem DAESdaedaedem demofilechoiceSCIdemossimulationno See Also demofunctionchoice Authors GH 2181 Name demofunctionchoice choose and execute an item within a list demofunctionchoice Description The function demofunctionchoice choose and execute an item chosen in the variable demolist that shall appear above The variable demolist is a text matrix whose first column contains item names displayed in an options window and whose second column contains the function that will be called The title of the options window is Choose a demo If the options window is cancelled the console is put back to its previous width Examples demolist Simulation of a binomial random variableset figurestyle newclfBinomialT Simulation of a discrete random variableset figurestyle newclfRndDiscT Simulation of a geometric random variableset figurestyle newclfGeomT1000 Simulation of a Poisson random variableset figurestyle newclfPoissonT Simulation of an exponential random variableset figurestyle newclfExpT Simulation of a Weibull random variableset figurestyle newclfWeibullT Simulation of an hyper geometric random variableset figurestyle newclfHyperGeomT Simulation of an Erlang random variableset figurestyle newclfErlangT demofunctionchoice See Also demofilechoice Authors GH 2182 Name demomdialog create a dialog box resp demomdialogfil Description The function demomdialog create a dialog box It takes as argument a binary file This file is built by a sce file written like below It shall contain the variables titl the title a the dialog box namevar the name of the fields to fill and value the values written by default After this these three variables shall be saved in the binary file The use of demomdialog shall be preceded by the execution of the sce associated The function demomdialog returns resp the values chosen by the user Examples execSCIdemoscontrolpidpiddial4sce defvdemomdialogSCIdemoscontrolpidpiddial4bin if defv then warningDemo stopsreturnend See Also demochoose xmdialog xdialog Authors GH 2183 Name demomessage display a message demomessagefil Description The function demomessage displays the text message within the file fil given in argument Examples demomessageSCIdemoscontrolpidpid3sce See Also demorun messagebox demobegin demoend Authors GH 2184 Name demorun script file execution demorunfil Description The function demorun executes a script in the file fil given in argument See Also exec demomessage demobegin demoend Authors GH Parte XLVI Planilhas 2186 Name readxls lê um arquivo Excel sheets readxlsfilepath Parâmetros filepath string o endereço do arquivo Excel sheets um mlist de tipo xls com um campo chamado sheets Descrição Dado um endereço de um arquivo Excel esta função retorna uma estrutura de dados mlist do tipo xls com um campo chamado sheets O campo sheets contém uma lista da estutura de dados folha sheetmlistxlssheetnametextvaluesheetnameTextValue onde sheetname é um string contendo o nome da folha Text é uma matriz de strings que contém os strings e todas as células Value é uma matriz de números que contém todos os valores das células AVISO apenas arquivos Excel BIFF8 última versão do Excel são manipulados Exemplos Sheets readxlsSCImodulesspreadsheetdemosxlst1xls algumas operações básicas sobre Sheets typeofSheets s1Sheets1 obtendo a primeira folha typeofs1 s1value obtendo o campo do valor da primeira folha s1text obtendo o campo do texto da primeira folha s12 obtendo a segunda linha da folha typeofs12 editvar s1 Ver Também xlsopen xlsread Autores Pierrick Mode INRIA Serge Steer INRIA Funções Utilizadas Esta função é baseada nas funções Scilab xlsopen e xlsread 2187 Name xlsopen abre um arquivo Excel para leitura fdSSTSheetnamesSheetpos xlsopenfilepath Parâmetros filepath string o endereço do arquivo Excel fd número a unidade lógica do fluxo de dados do Excel SST vetor de todos os strings que aparecem na folha do Excel Sheetnames vetor de strings os nomes das folhas Sheetpos vetor de númerosas posições dos inícios das folhas no fluxo de dados do Excel Descrição Esta função primeiro analisa a estrutura de dados ole2 associada ao dado arquivo para extrair o fluxo de dado do Excel no qual está contido Após isso o fluxo de dados do Excel é salvo no diretório TMDIR e aberto Uma unidade lógica fd aponta para este arquivo temporário Então a primeira folha neste fluxo é lida para se obter informações globais como o número de folhas o nome das folhas Sheetnames endereços das folhas dentro do fluxo Sheetpos e SST que contém todos os strings utilizados nas folhas Os dados fd e Sheetpos devem ser passados para xlsread para se ler as folhas de dados A função readxls pode ser usada para se ler todo um arquivo Excel em uma função através de uma única chamada de função AVISO apenas arquivos Excel BIFF8 última versão do Excel 2003 são manipulados Exemplos Decodificando o arquivo ole extraindo e abrindo o fluxo de dados do Excel fdSSTSheetnamesSheetpos xlsopenSCImodulesspreadsheetdemosxlsTest1xls Lendo a primeira folha de dados ValueTextInd xlsreadfdSheetpos1 fechando o fluxo da planilha mclosefd Ver Também xlsread readxls Autores Pierrick Mode INRIA xlsopen 2188 Serge Steer INRIA Bibliografia Esta função é baseada na documentação do arquivo ole2 da Microsoft httpchicagosourceforgenet develdocsole e na descrição do OpenOffice sobre fluxo de dados do Excel httpscopenofficeorg spreadsheetfileformatpdf Funções Utilizadas O procedure ripole014 httpwwwpldanielscomripole é utilizado para extrair do arquivo ole o fluxo de dados da planilha 2189 Name xlsread lê uma folha em um arquivo Excel ValueTextInd xlsreadfdSheetpos Parâmetros fd um número a unidade lógica do fluxo de dados do Excel retornado por xlsopen Sheetpos um número a posição do início da folha no fluxo de dados Excel Esta posição é uma daquelas retornadas por xlsopen Value matriz de números os dados numéricos encontrados na folha A célula sem valores numéricos é representada por valores NaN TextInd uma matriz de índices com o mesmo tamanho que Value Os índices zeros indicam que não ex istem strings na celula Excel correspondente Um índice positivo i aponta para o string SSTi onde SST é dado por xlsopen Descrição Esta função lê uma folha do Excel dada uma unidade lógica em um fluxo de dados do Excel e a posição do início da folha neste fluxo de dados Ela retorna os dados numéricos e os strings contidos nas células do Excel A função readxls pode ser utilizada para ler todo um arquivo Excel em uma função utilizando apenas uma chamada a função AVISO apenas arquivos Excel BIFF8 última versão do Excel são manipulados Exemplos decodificando um arquivo ole extraindo e abrindo um fluxo de dados do Excel fdSSTSheetnamesSheetpos xlsopenSCImodulesspreadsheetdemosxlsTest1xls lendo a primeira folha de dados ValueTextInd xlsreadfdSheetpos1 fechando o fluxo de dados da planilha mclosefd Ver Também xlsopen readxls Autores Pierrick Mode INRIA Serge Steer INRIA xlsread 2190 Bibliografia Esta função é baseada na descrição do OpenOffice sobre fluxo de dados httpscopenofficeorg spreadsheetfileformatpdf Funções Utilizadas Esta função utiliza o arquivo xlsc que pode ser encontrado em uma versãofonte do Scilab no diretório directory SCIDIRmodulesspreadsheetsrcc 2191 Name excel2sci obsolete see readcsv See Also readcsv writecsv 2192 Name readcsv Read commaseparated value file M readcsvfname sep Parameters fname a character string The file path sep a character string Field separator used default value is M a matrix of strings Description Given an ascii file with delimited fields for instance created by a spreadsheet using Text and comma format readcsvfname returns the corresponding Scilab matrix of strings Use readcsvfnamesep for another choice of separator Note You may eval all or part of M using function evstr in order to convert string variables into numeric variables Examples create a file with some data separated with tab A 150 mputlstrcatstringAascii9 TMPDIR foocsv read csv file B readcsvTMPDIR foocsv eval B C evstrB compares original data and result andA C See Also writecsv evstr Authors Allan CORNET 2193 Name writecsv Read commaseparated value file writecsvM filename Parameters filename a character string The file path M a matrix of strings Description writecsvM filename writes matrix M into filename as commaseparated values The filename input is a string Examples save a matrix as csv file format A 110 01 writecsvA TMPDIR datascsv read as text mgetlTMPDIR datascsv r readcsvTMPDIR datascsvascii9 r strsubstr evstrr See Also readcsv evstr mgetl Authors Allan CORNET Parte XLVII callscilab API 2195 Name Boolean management How to manage Scilabs boolean read and write process using callscilab and apiscilab Description This help describes how boolean and matrix of booleans can be handle through the Call Scilab API and api Scilab There are several functions which can be used to read write from the memory of Scilab These functions are described in dedicated pages Note Access to variables is done through api Scilab named variable Examples Write a matrix of boolean into Scilab BF F T F F F F T Note that it is done column by column int B00001001 Declare the matrix int rowB2 colB4 Size of the matrix char variableNameB B Write it into Scilabs memory createNamedMatrixOfBooleanpvApiCtx variableNameB rowB colB B Prior to Scilab 52 C2FcwritebmatvariableNameB rowB colB B strlenvariableNameB printfDisplay from Scilab of B SendScilabJobdispB Display B Read the previously declared matrix of boolean B int rowB 0 colB 0 lp 0 int i 0 j 0 int matrixOfBooleanB NULL Int instead of double char variableToBeRetrievedB B First retrieve the size of the matrix readNamedMatrixOfBooleanpvApiCtx variableToBeRetrievedB rowB colB NULL Prior to Scilab 52 C2FcmatbptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfBooleanBintmallocrowBcolBsizeofint Load the matrix Boolean management 2196 readNamedMatrixOfBooleanpvApiCtx variableToBeRetrievedB rowB colB matrixOfBooleanB Prior to Scilab 52 C2FcreadbmatvariableToBeRetrievedBrowBcolBmatrixOfBooleanBstrlenvariableToBeRetrievedB printf printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expects printfd matrixOfBooleanBi rowB j printf New row of the matrix See Also APIScilab Boolean reading APIScilab Boolean writing SendScilabJob StartScilab CallScilab Double Management CallScilab Complex Management CallScilab String Management APIScilab Double Reading APIScilab Double Writing APIScilab String Reading APIScilab String Writing Authors Sylvestre Ledru 2197 Name Complex management How to manage Scilabs complex variable read and write process using callscilab Description This help describes how doubles and matrix of complex can be handle through the Call Scilab API There are several functions which can be used to read write from the memory of Scilab These functions are described in dedicated pages Note Access to variables is done through api Scilab named variable Examples Write a matrix into Scilab B1i 4i 212i 3 3 9 842i 2 Note that it is done column by column double B13492832 double Bimg10233102054223123 Declare the matrix Prior to Scilab 52 double B1349283210233102054223123 int rowB2 colB4 Size of the matrix char variableNameB B Write it into Scilabs memory createNamedComplexMatrixOfDoublepvApiCtxvariableNameBrowBcolB B Bimg Prior to Scilab 52 2FcwritecmatvariableNameB rowB colB B strlenvariableNameB printf printfDisplay from Scilab of B SendScilabJobdispB Display B int rowB 0 colB 0 lp 0 int i 0j 0 double matrixOfComplexB NULL double matrixOfComplexBimg NULL char variableToBeRetrievedB B First retrieve the size of the matrix readNamedComplexMatrixOfDoublepvApiCtx variableToBeRetrievedB rowB colB NULL NULL Complex management 2198 Prior to Scilab 52 C2FcmatcptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfComplexB doublemallocrowBcolBsizeofdouble matrixOfComplexBimg doublemallocrowBcolBsizeofdouble Load the matrix readNamedComplexMatrixOfDoublepvApiCtx variableToBeRetrievedB rowB colB matrixOfComplexB matrixOfComplexBimg Prior to Scilab 52 C2FcreadcmatvariableToBeRetrievedBrowBcolBmatrixOfComplexBstrlenvariableToBeRetrievedB printf printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printf52f 52fi matrixOfComplexBi rowB jmatrixOfComplexBimgi rowB j printf New row of the matrix See Also CallScilabapi Scilabcwritecmat creadcmat SendScilabJob StartScilab CallScilab Complex Management CallScilab Boolean Management CallScilab String Management APIScilab Boolean Reading APIScilab Boolean Writing APIScilab String Reading APIScilab String Writing Authors Sylvestre Ledru 2199 Name DisableInteractiveMode Disables some features plotting gui creation TclTk and leaves only the computing engine Synopsis void DisableInteractiveModevoid Description Calling this fonction will disable some features of Scilab Examples A simple DisableInteractiveMode example DisableInteractiveMode int codeSendScilabJobplot3d This will failed since plot3d is among the disable features if code0 char lastjob4096 if GetLastJoblastjob4096 printfFailed command s lastjob See Also CallScilabapi ScilabCompile and run with callscilab SendScilabJob TerminateScilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2200 Name Double management How to manage Scilabs variable read and write process using callscilab and apiscilab Description This help describes how doubles and matrix of doubles can be handle through the Call Scilab API and api Scilab There are several functions which can be used to read write from the memory of Scilab These functions are described in dedicated pages Note that the default type of a numeric value in Scilab is double For example in a1 or a12 a will be consider as a double Note Access to variables is done through api Scilab named variable Examples Write a matrix into Scilab B1 4 2 3 3 9 8 2 Note that it is done column by column double B 13492832 Declare the matrix int rowB 2 colB 4 Size of the matrix char variableNameB B Write it into Scilabs memory createNamedMatrixOfDoublepvApiCtxvariableNameBrowBcolB B pvApiCtx is a global variable Prior to Scilab 52 C2FcwritematvariableNameB rowB colB B strlenvariableNameB printf printfDisplay from Scilab of B SendScilabJobdispB Display B Read the previously declared matrix of double B int rowB 0 colB 0 lp 0 double matrixOfDoubleB NULL int i 0 j 0 char variableToBeRetrievedB B First retrieve the size of the matrix readNamedMatrixOfDoublepvApiCtx variableToBeRetrievedB rowB colB NULL Prior to Scilab 52 C2FcmatptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Double management 2201 Alloc the memory matrixOfDoubleB doublemallocrowBcolBsizeofdouble Load the matrix readNamedMatrixOfDoublepvApiCtx variableToBeRetrievedB rowB colB matrixOfDoubleB Prior to Scilab 52 C2FcreadmatvariableToBeRetrievedBrowBcolBmatrixOfDoubleBstrlenvariableToBeRetrievedB printf printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printf52f matrixOfDoubleBi rowB j printf New row of the matrix See Also CallScilabapi ScilabAPIScilab Double reading APIScilab Double writing SendScilabJob StartScilab CallScilab BooleanManagement CallScilab ComplexManagement CallScilab StringManagement APIScilab Boolean Reading APIScilab Boolean Writing APIScilab String Reading APIScilab String Writing Authors Sylvestre Ledru 2202 Name GetLastJob Returns the latest job sent to Scilab engine Synopsis BOOL GetLastJobchar JOBint nbcharsJOB Description This fonction returns the latest job sent to Scilab engine with the command SendScilabJob or Send ScilabJobs This can be used to display a command which failed BOOL is just a simple typedef on int typedef int BOOL TRUE is defined on 1 define TRUE 1 and FALSE is defined on 0 define FALSE 0 Parameters JOB a standard C char which will be filled with the latest job nbcharsJOB The number of char of JOB returns 1 TRUE if the operation is successfull 0 FALSE if an error during initialization occured Examples A simple GetLastJob example See SCImodulescallscilabexamplesbasicExamplesGetLastJobc for the full code int codeSendScilabJobfailedMyCurrentJobpi30 if code0 char lastjob4096 if GetLastJoblastjob4096 printfFailed command s lastjob See Also CallScilabapi ScilabCompile and run with callscilab SendScilabJob TerminateScilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2203 Name ScilabHaveAGraph Check if any Scilab graphics have been opened Synopsis int ScilabHaveAGraphvoid Description Returns if there is any Scilab graphics opened Examples A simple ScilabHaveAGraph example int codeSendScilabJobplot3d This will failed since plot3d is among the disable features if ScilabHaveAGraph printfGraphics else printfNO Graphics See Also CallScilabapi ScilabCompile and run with callscilab SendScilabJob TerminateScilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2204 Name SendScilabJob Send a Scilab task from a CC code callscilab Synopsis int SendScilabJobchar job Description This fonction is provided in callscilab This function send a task which will be proccessed by the Scilab engine Parameters job a standard C char containing the Scilab instructions returns 0 is the operation is successfull 1 if Call Scilab has not been able to write the job into Scilab 2 or 3 if Call Scilab has not been able to read the error code from Scilab 4 if Call Scilab has not been able to allocate the job Examples A simple SendScilabJob example if SendScilabJobdispunfinished quote0 This will fail printfAn error occured SendScilabJobmyMatrixsamplefor the help See Also CallScilabapi ScilabCompile and run with callscilab SendScilabJob Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2205 Name SendScilabJobs Send Scilab tasks from a CC code callscilab Synopsis int SendScilabJobschar jobs int numberjobs Description This fonction is provided in callscilab This function send many tasks which will be proccessed by the Scilab engine Note that the ending is not mandatory at the end of a command Parameters jobs an array of standard C char containing the Scilab instructions numberjobs The number of the Scilab instructions returns 0 is all the operations are successful 10 if 0 and 10 when an error occurred in the execution Examples A simple SendScilabJobs example char jobs3 jobs0a 1 jobs1b 3 jobs2c a b SendScilabJobsjobs3 SendScilabJobdispc Will display 4 See Also CallScilabapi ScilabSendScilabJob Compile and run with callscilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2206 Name StartScilab Initializes and starts Scilab engine in Call Scilab Synopsis BOOL StartScilabchar SCIpath char ScilabStartup int Stacksize Description This fonction starts the Scilab engine This is mandatory to use SendScilabJob functions and to manage Scilabs data BOOL is just a simple typedef on int typedef int BOOL TRUE is defined on 1 define TRUE 1 and FALSE is defined on 0 define FALSE 0 Parameters SCIpath a standard C char containing the path to Scilab data This argument is mandatory under Linux Unix or Mac OS X Under Windows if SCIpath is NULL Scilab will find the path ScilabStartup a standard C char containing the path to Scilab startup script scilabstart If ScilabStartup is NULL Scilab will use the default path detected from SCIpath Stacksize a standard int defining the size of the Scilab stack If Stacksize is NULL Scilab will use the default stacksize of Scilab returns 1 TRUE if the operation is successfull 0 FALSE if an error during initialization occured Examples A simple StartScilab example if StartScilabgetenvSCINULLNULL FALSE fprintfstderrError while calling StartScilab return 1 See Also CallScilabapi Scilab Compile and run with callscilab SendScilabJob TerminateScilab Double Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2207 Name String management How to manage Scilabs String read and write process using callscilab and apiscilab Description This help describes how strings and matrix of strings can be handle through the Call Scilab API and api Scilab There are several functions which can be used to read write from the memory of Scilab These functions are described in dedicated pages Note Access to variables is done through api Scilab named variable Examples This example shows how to write a Scilab string in Scilab engine It is the equivalent to Amy Message in Scilab interpretor See modulescallscilabexamplesbasicExamplesreadwritestringc StartScilab int row 1 col 1 Size of the matrix Declare the string char myMatrixOfString charmallocsizeofchar row col myMatrixOfString0my Message char variableName A Write it into Scilabs memory createNamedMatrixOfStringpvApiCtx variableName row col myMatrixOfString Prior to Scilab 52 C2FcwritechainvariableName sizeOfMyString myString strlenvariableName sizeOfMyString printfDisplay from Scilab of A SendScilabJobdispA Display A Load the previously set variable A See modulescallscilabexamplesbasicExamplesreadwritestringc char variableToBeRetrievedA int iRows 0 int iCols 0 int ij int piAddr NULL int piLen NULL char pstData NULL fisrt call to retrieve dimensions readNamedMatrixOfStringpvApiCtxvariableToBeRetrievediRows iCols NULL NULL piLen intmallocsizeofint iRows iCols second call to retrieve length of each string readNamedMatrixOfStringpvApiCtxvariableToBeRetrieved iRows iCols piLen NULL String management 2208 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination third call to retrieve data readNamedMatrixOfStringpvApiCtx variableToBeRetrieved iRows iCols piLen pstData printf printfLoad and display of A forj 0 j iCols j fori 0 i iRows i Display the formated matrix with same scilab indice printfdd s j1i1pstDataj iRows i printf freepiLen fori 0 i iRows iCols i freepstDatai freepstData See Also CallScilabapi Scilab cwritechain creadchain SendScilabJob StartScilab CallScilab Boolean Management CallScilab Double Management APIScilab Boolean Reading APIScilab Boolean Writing APIScilab Double Reading APIScilab Double Writing Complex Management Authors Sylvestre Ledru 2209 Name TerminateScilab Stops and terminates Scilab engine in Call Scilab Synopsis BOOL TerminateScilabchar ScilabQuit Description This fonction stops the Scilab engine It is strongly recommanded to call this function at the end when using Call Scilab BOOL is just a simple typedef on int typedef int BOOL TRUE is defined on 1 define TRUE 1 and FALSE is defined on 0 define FALSE 0 Parameters ScilabQuit a standard C char containing the path to Scilab quit script scilabquit If ScilabStartup is NULL Scilab will use the default path detected from SCIpath returns 1 TRUE if the operation is successfull 0 FALSE if an error during initialization occured Examples A simple TerminateScilab example if TerminateScilabNULL FALSE fprintfstderrError while calling TerminateScilab return 2 See Also CallScilabapi Scilab Compile and run with callscilab StartScilab SendScilabJob Double Man agement Boolean Management Complex Management String Management Authors Sylvestre Ledru 2210 Name callscilab callscilab is an interface which provides the ability to call Scilab engine from CC code Description Scilab offers the possibility to be called from a native CC application Thanks to this module it is possible to call Scilab from CC in order to interface Scilabs features from an other codeapplication or to be able to interface Scilabs features from an other language Since Scilab 520 all Scilab datatype can be handle by callscilab This is done thanks to APIScilab This help describes the features of the callscilab API Note The javasci module is based on callscilab Note old APIs stackXh will not be available after Scilab 60 included Examples A simple callscilab example include stdioh stderr include stackch Provide functions to access to the memory of Scilab include callscilabh Provide functions to call Scilab engine Filename simplecallscilabc int mainvoid INITIALIZATION ifdef MSCVER if StartScilabNULLNULLNULL FALSE else if StartScilabgetenvSCINULLNULL FALSE endif fprintfstderrError while calling StartScilab return 1 ACTUAL Scilab TASKS SendScilabJobmyMatrixsamplefor the help SendScilabJobdispmyMatrix Will display sample for the help SendScilabJobdisp234439 Will display 42 42 TERMINATION if TerminateScilabNULL FALSE fprintfstderrError while calling TerminateScilab return 2 return 0 callscilab 2211 See Also api ScilabCompile and run with callscilab Matrix Management Boolean Management Complex Management String Management Authors Sylvestre Ledru 2212 Name Compile and run with Call Scilab How to compile a native application based on or using Scilab Compilation To compile a native code based on Call Scilab it is necessary to define some arguments variables and paths CFLAGS Call Scilab needs to have access to the headers of Scilab core and call Scilab module LinuxUnixMacOSX In the binary version of Scilab CFLAGS must be set to pathtoscilabincludescilabcore and pathtoscilabincludescilabcallscilab In the source tree of Scilab CFLAGS must be set to pathtoscilabmodulescoreincludes and pathtoscilabmodulescallscilabincludes Windows LDLIBRARYPATH Paths to libscilabso and libjavasciso or dll jnilib LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilablibscilab In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabmod ulescallscilablibs and pathtoscilablibs LDFLAGS The name of the library to link against LinuxUnixMacOSX It is only mandatory to link against scilab This should include the other libraries A sample Makefile building a C code using Call Scilab using Scilab built in it source tree PATHSCILAB pathtoscilabsources SCILABCFLAGS IPATHSCILABmodulescoreincludes IPATHSCILABmodulescallscilabincludes SCILABLDFLAGS lscilab PATHTOLIBSCILAB PATHSCILABmoduleslibs PATHTOLIBCALLSCILAB PATHSCILABmodulescallscilablibs all simplecallscilabc export LDLIBRARYPATHPATHTOLIBSCILABPATHTOLIBCALLSCILAB gcc o myExample SCILABLDFLAGS LPATHTOLIBSCILAB LPATHTOLIBCALLSCILAB SCILABCFLAGS simplecallscilabc Running To run an application based on Call Scilab there are a few other things to set up Some global variables must me set SCI Path to Scilab files LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilabsharescilab Compile and run with Call Scilab 2213 In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabsource tree Windows LDLIBRARYPATH Paths to libscilabso and libjavasciso or dll jnilib LinuxUnixMacOSX In the binary version of Scilab SCI will point to pathtoscilablibscilab In the source tree of Scilab SCI will point to the root of the source tree pathtoscilabmod ulesjavascilibs and pathtoscilablibs LDLIBRARYPATH Java Paths to Java native libraries libjavaso libjvmso libhpiso It is usually provided by the operating system or by Scilab distribution Please note that wont be necessary in Scilab 52 LinuxUnix JAVAHOMEjrelibarch JAVAHOMEjrelibarchserver JAVAHOMEjrelib archnativethreads arch can be i386 etc Mac OS X Windows Note that two environnement variables are taken in account for specific needs SCIDISABLETK1 Disables Tk Tcls GUI SCIJAVAENABLEHEADLESS1 Launch Java in headless mode no AWTSwing Examples Serie of declarations to execute my binary With a Scilab source tree SCIpath to Scilab source tree export LDLIBRARYPATHSCImoduleslibsSCImodulescallscilablibsSCImodulesapiscilablibs With a Scilab binary SCIpath to Scilab binary export LDLIBRARYPATHSCIlibscilab Dont forget to update i386 to whatever is necessary export LDLIBRARYPATHLDLIBRARYPATHusrlibjvmjava6openjdkjrelibi386usrlibjvmjava6openjdkjrelibi386server export LDLIBRARYPATHLDLIBRARYPATHusrlibjvmjava6openjdkjrelibi386nativethreads export SCIpathtoscilab myExample sample for the help 42 42 See Also api Scilabcallscilab StartScilab SendScilabJob SendScilabJobs Double Management Boolean Management Complex Management String Management Compile and run with Call Scilab 2214 Authors Allan Cornet Sylvestre Ledru 2215 Name creadbmat obsolete Read a single boolean or a matrix of boolean from Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab Boolean reading for remplacement Synopsis int C2Fcreadbmatchar name int m int n int scimat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns scimat The actual matrix of boolean array of int Note that it is going to be stored in Scilab columnwise namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function creadbmat Using this function will retrieve a variable called name from Scilab memory into a standard C int Examples Load the previously set variable B See modulescallscilabexamplesbasicExamplesreadwritebooleanc int rowB 0 colB 0 lp 0 int i 0 j 0 int matrixOfBooleanB NULL Int instead of double char variableToBeRetrievedB B First retrieve the size of the matrix C2FcmatbptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfBooleanBintmallocrowBcolBsizeofint Load the matrix C2FcreadbmatvariableToBeRetrievedBrowBcolBmatrixOfBooleanBstrlenvariableToBeRetrievedB printf printfDisplay from B formated size d d rowB colB creadbmat obsolete 2216 forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printfd matrixOfBooleanBi rowB j printf New row of the matrix See Also CallScilabapi ScilabAPIScilab Boolean reading APIScilab Boolean writing SendScilabJob StartScilab cwritebmat Boolean Management Authors Sylvestre Ledru 2217 Name creadchain obsolete Read a single string from Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab String reading for remplacement Synopsis int C2Fcreadchainchar name int itslen char myString unsigned long namelen unsigned long myStringlen Parameters name The name of the future Scilab variable itslen The length of the future buffer usually use bsiz it skips the need to detect the size of a char This variable will be altered to contain the actual size of myString myString The actual String char which is going to content the content of the Scilab variable name namelen The length of the variable name fortran compatibility myStringlen The length of the string fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function creadchain Using this function will retrieve a variable called name from Scilab memory into a standard C char Examples Load the previously set variable A See modulescallscilabexamplesbasicExamplesreadwritestringc int sizeA 0 char myStringFromScilabbsiz Static char int lengthmyStringFromScilab bsiz Max size it is going to be changed by creadchain char variableToBeRetrievedA We are loading a single string from Scilab C2FcreadchainvariableToBeRetrievedlengthmyStringFromScilabmyStringFromScilabstrlenvariableToBeRetrievedstrlenmyStringFromScilab printf printfDisplay of A size d s lengthmyStringFromScilab myStringFromScilab See Also CallScilabapi ScilabAPIScilab String reading APIScilab String writing SendScilabJob StartScilab cwritechain String Management creadchain obsolete 2218 Authors Sylvestre Ledru 2219 Name creadcmat obsolete Read a single complex or a matrix of complex from Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab Complex double read ing for remplacement Synopsis int C2Fcreadcmatchar name int m int n double scimat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns scimat The actual matrix of complex array of double Note that it is going to be stored in Scilab colum nwise and the second half of the array is used for complex values namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function creadcmat Using this function will retrieve a variable called name from Scilab memory into a standard C double Examples Load the previously set variable B See modulescallscilabexamplesbasicExamplesreadwritecomplexmatrixc int rowB 0 colB 0 lp 0 int i 0j 0 double matrixOfComplexB NULL char variableToBeRetrievedB B First retrieve the size of the matrix C2FcmatcptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfComplexB doublemallocrowBcolB2sizeofdouble Load the matrix C2FcreadcmatvariableToBeRetrievedBrowBcolBmatrixOfComplexBstrlenvariableToBeRetrievedB printf creadcmat obsolete 2220 printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printf52f 52fi matrixOfComplexBi rowB jmatrixOfComplexBrowBcolBi rowB j printf New row of the matrix See Also CallScilabapi ScilabAPIScilab Complex double reading APIScilab Double writing SendScil abJob StartScilab cwritecmat Complex Management Authors Sylvestre Ledru 2221 Name creadmat obsolete Read a single double or a matrix of double from Scilab memory using callscilab Note that it is the default datatype in Scilab Starting with Scilab 52 this function is ob solete See APIScilab Double reading for remplacement Synopsis int C2Fcreadmatchar name int m int n double scimat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns scimat The actual matrix of double array of double Note that it is going to be stored in Scilab colum nwise namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function creadmat Using this function will retrieve a variable called name from Scilab memory into a standard C double Examples Load the previously set variable B See modulescallscilabexamplesbasicExamplesreadwritematrixc int rowB 0 colB 0 lp 0 double matrixOfDoubleB NULL int i 0 j 0 char variableToBeRetrievedB B First retrieve the size of the matrix C2FcmatptrvariableToBeRetrievedB rowB colB lp strlenvariableToBeRetrievedB Alloc the memory matrixOfDoubleB doublemallocrowBcolBsizeofdouble Load the matrix C2FcreadmatvariableToBeRetrievedBrowBcolBmatrixOfDoubleBstrlenvariableToBeRetrievedB printf creadmat obsolete 2222 printfDisplay from B formated size d d rowB colB forj 0 j rowB j fori 0 i colB i Display the formated matrix the way the user expect printf52f matrixOfDoubleBi rowB j printf New row of the matrix See Also CallScilabapi ScilabAPIScilab Double readingAPIScilab Double writing SendScilabJob StartScilab cwritemat Double Management Authors Sylvestre Ledru 2223 Name cwritebmat obsolete Write a single boolean or a matrix of boolean into Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab Boolean writing for remplacement Synopsis int C2Fcwritebmatchar name int m int n int mat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns mat The actual matrix of boolean array of int Note that it is going to be stored in Scilab columnwise namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function cwritebmat Using this function will basically do the same as A T F F T but straight into Scilab memory with callscilab Examples This example shows how to write a Scilab matrix of boolean in Scilab engine It is the equivalent to BF F T F F F F T in Scilab interpretor See modulescallscilabexamplesbasicExamplesreadwritebooleanc StartScilab int B00001001 Declare the matrix int rowB2 colB4 Size of the matrix char variableNameB B C2FcwritebmatvariableNameB rowB colB B strlenvariableNameB Write it into Scilabs memory printf printfDisplay from Scilab of B SendScilabJobdispB Display B See Also CallScilabapi ScilabAPIScilab Boolean reading APIScilab Boolean writing SendScilabJob StartScilab creadbmat Boolean Management cwritebmat obsolete 2224 Authors Sylvestre Ledru 2225 Name cwritechain obsolete Write a single string into Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab String writing for remplacement Synopsis int C2Fcwritechainchar name int myStringSize char myString unsigned long namelen unsigned long myStringlen Parameters name The name of the future Scilab variable myStringSize The length of the string which is going to be write into Scilab memory myString The actual String char namelen The length of the variable name fortran compatibility myStringlen The length of the string fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function cwritechain Using this function will basically do the same as A my own String but straight into Scilab memory with callscilab Examples This example shows how to write a Scilab string in Scilab engine It is the equivalent to Amy Message in Scilab interpretor See modulescallscilabexamplesbasicExamplesreadwritestringc StartScilab char myString my Message Declare the string char variableName A The name of the future variable in Scilab int sizeOfMyStringstrlenmyString C2FcwritechainvariableName sizeOfMyString myString strlenvariableName sizeOfMyString Write it into Scilabs memory printfDisplay from Scilab of A SendScilabJobdispA Display A See Also CallScilabapi ScilabAPIScilab String reading APIScilab String writing SendScilabJob StartScilab creadchains String Management cwritechain obsolete 2226 Authors Sylvestre Ledru 2227 Name cwritecmat obsolete Write a single complex or a matrix of complex into Scilab memory using callscilab Starting with Scilab 52 this function is obsolete See APIScilab Complex double writing for remplacement Synopsis int C2Fcwritecmat char name int m int n double mat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns mat The actual matrix of complex array of double Note that it is going to be stored in Scilab colum nwise and the second half of the array is used for complex values namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function cwritecmat Using this function will basically do the same as A 1i 3i 4 22i but straight into Scilab memory with callscilab Examples This example shows how to write a Scilab matrix of complex in Scilab engine Write a matrix into Scilab B1i 4i 212i 3 3 9 842i 2 Note that it is done column by column double B134928321010054200 Declare the matrix int rowB2 colB4 Size of the matrix char variableNameB B C2FcwritecmatvariableNameB rowB colB B strlenvariableNameB Write it into Scilabs memory printf printfDisplay from Scilab of B SendScilabJobdispB Display B cwritecmat obsolete 2228 See Also CallScilabapi ScilabAPIScilab Complex double reading APIScilab Complex double writing SendScilabJob StartScilab Complex Management creadcmat Authors Sylvestre Ledru 2229 Name cwritemat obsolete Write a single double or a matrix of double into Scilab memory using callscilab Note that it is the default datatype in Scilab Starting with Scilab 52 this function is ob solete See APIScilab Double writing for remplacement Synopsis int C2Fcwritematchar name int m int n int mat unsigned long namelen Parameters name The name of the future Scilab variable m Number of rows n Number of columns mat The actual matrix of double array of double Note that it is going to be stored in Scilab colum nwise namelen The length of the variable name fortran compatibility C2F C2F is just a macro which provides to this function the ability to be called from fortran Description This help describes how to use the function cwritemat Using this function will basically do the same as A 1 3 4 2 but straight into Scilab memory with callscilab Examples This example shows how to write a Scilab matrix of double in Scilab engine Write a matrix into Scilab B1 4 2 3 3 9 8 2 Note that it is done column by column See modulescallscilabexamplesbasicExamplesreadwritematrixc StartScilab double B 13492832 Declare the matrix int rowB 2 colB 4 Size of the matrix char variableNameB B C2FcwritematvariableNameB rowB colB B strlenvariableNameB Write it into Scilabs memory printf printfDisplay from Scilab of B SendScilabJobdispB Display A cwritemat obsolete 2230 See Also CallScilabapi Scilab APIScilab Double readingAPIScilab Double writing SendScilabJob StartScilab Double Management creadmat Authors Sylvestre Ledru 2231 Name fromc Checks if current Scilab is called from an external C program by StartScilab rfromc Parameters r a boolean Description Returns tChecks if current Scilab is called from an external C program or f if not See Also CallScilabapi Scilabfromjava 2232 Name fromjava Checks if current Scilab is called from javasci r fromjava Parameters r a boolean Description Returns t if Scilab is called from javasci or f if not See Also CallScilabapi Scilabfromc Parte XLVIII FFTW 2234 Name fftw Fast fourier transform based on the fftw library yfftwx yfftwxsign yfftwxsigndimincr yfftwxsigndim1 dim2 dimNincr1 incr2 incrN Parameters yx matrixvector of realcomplex data Inputoutput data to be transformed sign Integer 1 or 1 Set direct or inverse transform dim integer Set the dimension the length of the transform incr integer Set the stride the span of the transform Description This function realizes directinverse Discrete Fourier Transform DFT with the help of the FFTW library One can compute vector 2D MD transform with this function For more details of fftw syntax see fft scilab function For more details about FFTW library see FFTW Web site httpwwwfftworg Remark fftw function automatically stores his last parameters in memory to reuse it in a second time This improves greatly the time computation when consecutives calls with same parameters are per formed Examples simple vector direct transform a rand501irand501 y fftwa y fftwa1 inverse transform b fftwy1 2D transform a rand512512irand512512 y fftwa MD transform old calling sequence a rand1201 y a dim5 6 4incr1 5 30 for i13 fftw 2235 y fftwy1dimiincri end MD transform new calling sequence More efficient than old y fftwa15 6 41 5 30 b fftwy15 6 41 5 30 See Also fftwflags getfftwwisdom setfftwwisdom fftwforgetwisdom Bibliography Matteo Frigo and Steven G Johnson FFTW Manual fo version 312 June 2006 Available http wwwfftworg 2236 Name fftwflags set computation method of fast fourier transform of the fftw function aSfftwflagsx1x2 Parameters x1x2 Matrix of string or integers Entry to switch the method of fft computation for fftw a Integer Give the current value of the flag of the fftw function S String matrix Give the string value of the fftw flag Description This function enables the change of the unsigned flags parameter of the fftwplangurusplitdft function that is used in fftw function Default value is FFTWESTIMATE Accepted entries are FFTWMEASURE or 0 FFTWDESTROYINPUT or 1 FFTWUNALIGNED or 2 FFTWCONSERVEMEMORY or 4 FFTWEXHAUSTIVE or 8 FFTWPRESERVEINPUT or 16 FFTWPATIENT or 32 FFTWESTIMATE or 64 FFTWESTIMATEPATIENT or 128 FFTWBELIEVEPCOST or 256 FFTWNODFTR2HC or 512 FFTWNONONTHREADED or 1024 FFTWNOBUFFERING or 2048 FFTWNOINDIRECTOP or 4096 FFTWALLOWLARGEGENERIC or 8192 FFTWNORANKSPLITS or 16384 FFTWNOVRANKSPLITS or 32768 FFTWNOVRECURSE or 65536 fftwflags 2237 FFTWNOSIMD or 131072 FFTWNOSLOW or 262144 FFTWNOFIXEDRADIXLARGEN or 524288 FFTWALLOWPRUNING or 1048576 Rmk when using FFTWMEASUREFFTWPATIENTFFTWEXHAUSTIVE you must call two times fftw first call for initialisation second and others calls for computation Examples return the integer value of the flag fftwflags change flags fftwflagsFFTWMEASUREFFTWCONSERVEMEMORY change flags and display current value of fftw flags both integer and strings aSfftwflagsFFTWPATIENT See Also fftw 2238 Name fftwforgetwisdom Reset fftw wisdom fftwforgetwisdom Description This function reset the current fftw wisdom Examples return fftw wisdom txtgetfftwwisdom set fftw wisdom setfftwwisdomtxt reset fftw wisdom fftwforgetwisdom See Also fftw getfftwwisdom setfftwwisdom 2239 Name getfftwwisdom return fftw wisdom txtgetfftwwisdom Parameters txt String matrix that contains fftw wisdom Description This function return the fftw wisdom in a string matrix Examples return fftw wisdom txtgetfftwwisdom set fftw wisdom setfftwwisdomtxt reset fftw wisdom fftwforgetwisdom See Also fftw setfftwwisdom fftwforgetwisdom 2240 Name setfftwwisdom set fftw wisdom setfftwwisdomtxt Parameters txt String matrix that contains fftw wisdom Description This function set the fftw wisdom with a string matrix Examples return fftw wisdom txtgetfftwwisdom set fftw wisdom setfftwwisdomtxt reset fftw wisdom fftwforgetwisdom See Also fftw getfftwwisdom fftwforgetwisdom Parte XLIX Interfaces com UMFPACK 2242 Name PlotSparse plot the pattern of non nul elements of a sparse matrix PlotSparseA style Parameters A a sparse matrix style optional a string given the color andor the marker type of the form colormark where color may be a number referring the color you want to use in the current colormap If you use the std colormap then color may be one of the following letters k for black b for blue r for red g for green c for cyan m for magenta y for yellow t for turquoise G a dark green mark must be one of the following point plus x cross circled plus D filled diamond d diamond upper triangle v down triangle o circle by default you have b in fact the 2d color and this is also forced in case of error Description plot the pattern of non nul elements of a sparse matrix each non nul element is drawn with a marker For big matrix use essentially the point as marker Examples Adescriptionrefmtype ReadHBSparseSCImodulesumfpackexamplesarc130rua set figurestyle old PlotSparseAy xtitleref mtype description See Also ReadHBSparse Authors Bruno Pincon BrunoPinconiecnunancyfr 2243 Name ReadHBSparse read a HarwellBoeing sparse format file A description ref mtype ReadHBSparsefilename Parameters filename optional a string given the filename eventually preceeding by the path if filename is not given then the function use uigetfile to get filename interactively A the sparse matrix description a string given some information about the matrix ref a string given the reference of the matrix mtype a string given the type of the matrix Description An utility to read the HarwellBoeing sparse matrix format Currently dont work for unassembled matrix Also the eventual rhs vectors of the file are not returned Generally the file name is of the form refmtype where mtype is a 3 letters word abc given some information already inside the file on the matrix a RCP for realcomplexpattern no values given b SHZU for symmetrichermitianskew symmetricasymmetric c AE for assembledunassembled matrix case E is not treated by this func References Users Guide for the HarwellBoeing Sparse Matrix Collection Iain S Duff Roger G Grimes John G Lewis You may found this guide and numerous sparse matrices in the HarwellBoeing format at the University of Florida Sparse Matrix Collection web site httpwwwciseufleduresearchsparsematrices maintained by Tim Davis httpwwwciseufledudavis Examples A ReadHBSparseSCImodulesumfpackexamplesarc130rua See Also PlotSparse ReadHBSparse 2244 Authors Bruno Pincon BrunoPinconiecnunancyfr 2245 Name cond2sp computes an approximation of the 2norm condition number of a spd sparse matrix K2 lm vm lM vM cond2spA Cptr rtol itermax verb Parameters A a real symmetric positive definite sparse matrix Cptr a pointer to a Cholesky factorization got with taucschfact rtol optional relative tolerance default 1e3 see details in DESCRIPTION itermax optional maximum number of iterations in the underlying algorithms default 30 verb optional boolean must be t for displaying the intermediary results and f default if you dont want K2 estimated 2norm condition number K2 A2 A12 lMlm lm real positive scalar minimum eigenvalue vm associated eigenvector lM real positive scalar maximum eigenvalue vM associated eigenvector Description This quick and dirty function computes lMvM using the iterative power method and lmvm with the inverse iterative power method then K2 lMlm For each method the iterations are stopped until the following condition is met lnew loldlnew rtol but 4 iterations are nevertheless required and also the iterations are stopped if itermax is reached and a warning message is issued As the matrix is symmetric this is the rayleigh quotient which gives the estimated eigenvalue at each step lambda vAv You may called this function with named parameter for instance if you want to see the intermediary result without setting yourself the rtol and itermax parameters you may called this function with the syntax K2 lm vm lM vM cond2spA Cptr verbt cond2sp 2246 Caution Currently there is no verification for the input parameters Remark This function is intended to get an approximation of the 2norm condition number K2 and with the methods used the precision on the obtained eigenvectors vM and vm are generally not very good If you look for a smaller residual Av lv you may apply some inverse power iterations from v0 with the matrix B A l0speyeA For instance applied 5 such iterations for lmvm is done with l0 lm v0 vm or l0 lM v0 vM to polish lMvM B A l0speyeA LUp umflufactB vr v0 nstep 5 for i1nstep vr umflusolveLUp vr Axb B vr vrnormvr end umfludelLUp if you dont use anymore this factorization lr vrAvr normr0 normAv0 l0v0 normrr normAvr lrvr BauerFike error bound mprintf first estimated eigenvalue l0 e l0 mprintf ll0 Av0l0v0 e ll0l0 e r normr0 normr0l0 mprintf raffined estimated eigenvalue lr e lr mprintf llr Avrlrvr e llrlr e r normrr normrrlr Examples A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa Cptr taucschfactA K2 lm vm lM vM cond2spA Cptr 1e5 50 t taucschdelCptr See Also condestsp taucschfact rcond Authors Bruno Pincon BrunoPinconiecnunancyfr 2247 Name condestsp estimate the condition number of a sparse matrix K1 condestspA LUp t K1 condestspA LUp K1 condestspA t K1 condestspA Parameters A a real or complex square sparse matrix LUp optional a pointer to umf LU factors of A obtained by a call to umflufact if you have already computed the LU PAQ factors it is recommanded to give this optional parameter as the factorization may be time consuming t optional a positive integer default value 2 by increasing this one you may hope to get a better even exact estimate K1 estimated 1norm condition number of A Description Give an estimate of the 1norm condition number of the sparse matrix A by Algorithm 24 appearing in A block algorithm for matrix 1norm estimation with an application to 1norm pseudospectra Nicholas J Higham and Francoise Tisseur Siam J Matrix Anal Appl vol 21 No 4 pp 11851201 Noting the exact condition number K1e A1 A11 we have allways K1 K1e and this estimate gives in most case something superior to 12 K1e Examples A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 K1 condestspA verif by direct computation K1e normA1norminvfullA1 another example A ReadHBSparseSCImodulesumfpackexamplesarc130rua K1 condestspA this example is not so big so that we can do the verif condestsp 2248 K1e normA1norminvfullA1 if you have already the lu factors condestspALup is faster because lu factors are then not computed inside condestsp Lup umflufactA K1 condestspALup umfludelLup clear memory See Also umflufact rcond Authors Bruno Pincon BrunoPinconiecnunancyfr 2249 Name rafiter obsolete iterative refinement for a spd linear system xn rn rafiterA Cptr b x0 nbiter verb Parameters A a real symmetric positive definite sparse matrix Cptr a pointer to a Cholesky factorization got with taucschfact b column vector rhs of the linear system but matrix multiple rhs are allowed x0 first solution obtained with taucschsolveCptr b nbiter optional number of raffinement iterations default 2 verb optional boolean must be t for displaying the intermediary results and f default if you dont want xn new refined solution rn residual Axn b Description This function is somewhat obsolete use x taucschsolveCptrbA see taucschsolve which do one iterative refinement step To use if you want to improve a little the solution got with taucschsolve Note that with verbt the displayed internal steps are essentially meaningful in the case where b is a column vector Caution Currently there is no verification for the input parameters Examples A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa Cptr taucschfactA b randsizeA11 x0 taucschsolveCptr b normAx0 b xn rn rafiterA Cptr b x0 verbt normAxn b taucschdelCptr rafiter 2250 See Also taucschsolve taucschfact Authors Bruno Pincon BrunoPinconiecnunancyfr 2251 Name reswithprec computes the residual r Axb with precision rnorm2r reswithprecA x b Parameters A real or complex sparse matrix m x n x column vector n x 1 or matrix n x p b column vector m x 1 or matrix m x p r column vector m x 1 or matrix m x p norm2r scalar or vector 1 x p when b is a m x p matrix Description This function computes the residual of a linear system r Ax b together with its 2norm with the additionnal precision provided on Intel like FPU 80 bits in place of 64 if the compiler translate long double to use it Else one must get the same than using Ax b at the scilab level In both cases using r nr reswithprecAxb is faster than r Ax b and faster than r Ax b nr normr When p 1 norm2ri is the 2norm of the vector ri Examples A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa Cptr taucschfactA b randsizeA11 x0 taucschsolveCptr b normAx0 b normreswithprecA x0 b See Also rafiter Authors Bruno Pincon BrunoPinconiecnunancyfr 2252 Name taucschdel utility function used with taucschfact taucschdelCptr or taucschdel Parameters Cptr a pointer to a Cholesky factorization Description This function is used in conjunction with taucschfact and taucschsolve It clears the internal memory space used to store the Cholesky factorization got with taucschfact Use without argument it frees the memory for all the current scilab taucs Cholesky factorizations Examples see the example section of taucschfact See Also taucschfact taucschsolve taucschinfo taucschget Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2253 Name taucschfact cholesky factorisation of a sparse spd matrix Cptr taucschfactA Parameters A a sparse real symmetric positive definite spd matrix Cptr a pointer to the Cholesky factors Cp AppCC Description This function computes a Cholesky factorization of the sparse symmetric positive definite spd matrix A and retrieves at the scilab level a pointer Cptr to an handle of the Cholesky factors Cp the memory used for them is outside scilab space If your matrix is spd this function must be used in place of umflufact or in place of the scilab function chfact for a gain in speed also as chfact uses the scilab memory for the factors the user must set the stacksize with a large value because of the fillin occuring in computing the factor C which then may take more memory than the initial matrix A When such a factorisation have been computed a linear system must be solved with taucschsolve To free the memory used by the Cholesky factors use taucschdelCptr to retrieve the Cholesky factors at the scilab level for example to display their sparse patterns use taucschget to get some information number of non zeros in C use taucschinfo To compute an approximation of the con dition number in norm 2 use cond2sp Remarks taucschfact works only with the upper triangle of A and the matrix A must be provided either in its complete form that is with the lower triangle also or only with its upper triangle currently taucschfact uses the genmmd generalized minimum degree algorithm of Liu to find in a first step the permutation p so as to minimize the fillin in the factorization future versions will let the user choose hisher own reordering by providing a supplementary argument p Examples Example 1 a small linear test system whom solution must be 12345 A sparse 2 1 0 0 0 1 2 1 0 0 0 1 2 1 0 0 0 1 2 1 0 0 0 1 2 b 0 0 0 0 6 Cp taucschfactA x taucschsolveCpb dont forget to clear memory with taucschdelCp Example 2 a real example taucschfact 2254 first load a sparse matrix A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa compute the factorisation Cp taucschfactA b randsizeA11 a random rhs use taucschsolve for solving Axb x taucschsolveCpb normAx b the same with one iterative refinement step x taucschsolveCpbA normAx b dont forget to clear memory taucschdelCp See Also taucschsolve taucschdel taucschinfo taucschget cond2sp Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2255 Name taucschget retrieve the Cholesky factorization at the scilab level Ctp taucschgetCptr Parameters Cptr a pointer to the Cholesky factorization Cp AppCC Ct a scilab sparse matrix you get the upper triangle ie Ct is equal to C p column vector storing the permutation Description This function may be used if you want to plot the sparse pattern of the Cholesky factorization or if you code something which use the factors Traditionnaly the factorization is written P A P C C with P the permutation matrix associated to the permutation p As we get the upper triangle Ct C in scilab syntax we can write App Ct Ct Examples Example 1 a small linear test system A sparse 2 1 0 0 0 1 2 1 0 0 0 1 2 1 0 0 0 1 2 1 0 0 0 1 2 Cp taucschfactA Ct p taucschgetCp fullApp CtCt this must be near the null matrix taucschdelCp Example 2 a real example stacksize3000000 the last PlotSparse need memory first load a sparse matrix A ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa compute the factorisation Cptr taucschfactA retrieve the factor at scilab level Ct p taucschgetCptr plot the initial matrix xsetwindow0 clf taucschget 2256 PlotSparseA xtitleInitial matrix A bcsstk24rsa plot the permuted matrix B App xsetwindow1 clf PlotSparseB xtitlePermuted matrix B App plot the upper triangle Ct xsetwindow2 clf PlotSparseCt xtitleThe pattern of Ct App CCt retrieve cnz OK n cnz taucschinfoCptr cnz is superior to the realnumber of non zeros elements of C cnzexact nnzCt dont forget to clear memory taucschdelCptr See Also taucschfact taucschsolve taucschdel taucschinfo taucschget cond2sp Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2257 Name taucschinfo get information on Cholesky factors OK n cnz taucschinfoCptr Parameters Cptr a pointer to a Cholesky factorization OK a scalar boolean n a scalar integer cnz a scalar integer Description This function may be used to know basic information about the Cholesky factor created with taucschfact first OK is t if Cptr is a valid pointer to an Cholesky factorization and f else if OK is t then n and cnz are respectively the matrix order and the number of non zeros elements in the supernodal structure storing C if OK is f n and cnz are set to the void matrix Details Due to the supernodal structure used for C cnz is larger than the exact number of nonzeros elements in C and so this cnz is a mesure of the memory used internally To get the exact cnz you may retrieve the Cholesky factor with taucschget then apply the nnz scilab function see the 2d example in taucschget See Also taucschfact taucschsolve taucschdel taucschget Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2258 Name taucschsolve solve a linear sparse spd system given the Cholesky factors x taucschsolveCptr b A Parameters Cptr a pointer to a handle of the Cholesky factors Cp with AppCC b a real column vector or a matrix multiple rhs x a real column vector or a matrix in case of multiple rhs xi is solution of A xi bi A optional the real spd matrix A to use for iterative refinement step Description This function must be used in conjonction with taucschfact which computes the Cholesky factoriza tion of a sparse real spd matrix When the matrix A is provided one iterative refinement step is done the refined solution is accepted if it improves the 2norm of the residual Axb Like in taucschfact the matrix A may be provided either in its complete form that is with the lower triangle also or only with its upper triangle Examples see the example section of taucschfact See Also taucschfact taucschdel taucschinfo taucschget cond2sp Authors taucs by Sivan Toledo see taucslicense scilab interface by Bruno Pincon 2259 Name taucslicense display the taucs license Copyright TAUCS Version 10 November 29 2001 Copyright c 2001 by Sivan Toledo TelAviv Univesity stoledotauacil All Rights Reserved TAUCS License Your use or distribution of TAUCS or any derivative code implies that you agree to this License THIS MATERIAL IS PROVIDED AS IS WITH ABSOLUTELY NO WARRANTY EXPRESSED OR IMPLIED ANY USE IS AT YOUR OWN RISK Permission is hereby granted to use or copy this program provided that the Copyright this License and the Availability of the original version is retained on all copies User documentation of any code that uses this code or any derivative code must cite the Copyright this License the Availability note and Used by permission If this code or any derivative code is accessible from within MATLAB then typing help taucs must cite the Copyright and type taucs must also cite this License and the Availability note Permission to modify the code and to distribute modified code is granted provided the Copyright this License and the Availability note are retained and a notice that the code was modified is included This software is provided to you free of charge Availability httpwwwtauacilstoledotaucs 2260 Name umflicense display the umfpack license Copyright UMFPACK Copyright c 19952006 by Timothy A Davis All Rights Reserved UMFPACK is available under alternate licences contact T Davis for details UMFPACK License Your use or distribution of UMFPACK or any modified version of UMFPACK implies that you agree to this License This library is free software you can redistribute it andor modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation either version 21 of the License or at your option any later version This library is distributed in the hope that it will be useful but WITHOUT ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE See the GNU Lesser General Public License for more details You should have received a copy of the GNU Lesser General Public License along with this library if not write to the Free Software Foundation Inc 51 Franklin St Fifth Floor Boston MA 021101301 USA Permission is hereby granted to use or copy this program under the terms of the GNU LGPL provided that the Copyright this License and the Availability of the original version is retained on all copies User documentation of any code that uses this code or any modified version of this code must cite the Copyright this License the Availability note and Used by permission Permission to modify the code and to distribute modified code is granted provided the Copyright this License and the Availability note are retained and a notice that the code was modified is included Availability httpwwwciseufleduresearchsparse 2261 Name umfludel utility function used with umflufact umfludelLUptr or umfludel Parameters LUptr a pointer to an handle of umf lu factors LUpqR Description This function must be used in conjunction with umflufact and umflusolve It clears the internal memory space used to store the LU factors got with umflufact Use without argument it frees the memory for all the current scilab umfpack LU factors Examples see the example section of umflufact See Also umfpack umflufact umflusolve umfluget umfluinfo Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon 2262 Name umflufact lu factorisation of a sparse matrix LUptr umflufactA Parameters A a sparse real or complex square or rectangular matrix LUptr a pointer to umf lu factors LUpqR Description This function computes a LU factorisation of the sparse matrix A and return at the scilab level a pointer LUptr to an handle of the LU factors LUpqR the memory used for them is outside scilab stack This function must be used in place of umfpack if you have multiple linear systems with the same matrix to solve when the rhs are not known at the same time for instance A x1 b1 and A x2 b2 but b2 depends on x1 etc When such a factorisation have been computed a linear system must be solved with umflusolve in general x umflusolveLUptr b but others options are possible see umflusolve To free the memory used by the LU factors use umfludelLUptr umfludel to retrieve the LU factors at the scilab level for example to display their sparse patterns use umfluget to get some information number of non zeros in L and U use umfluinfo To compute an approximation of the condition number use condestsp Examples this is the small linear test system from UMFPACK whom solution must be 12345 A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 b 8 45 3 3 19 Lup umflufactA x umflusolveLupb solve now Axb x umflusolveLupbAxb normAx b dont forget to clear memory with umfludelLup a real but small example first load a sparse matrix A ReadHBSparseSCImodulesumfpackexamplesarc130rua compute the factorisation Lup umflufactA umflufact 2263 b randsizeA11 a random rhs use umflusolve for solving Axb x umflusolveLupb normAx b now the same thing with iterative refiment x umflusolveLupbAxbA normAx b solve now the system Axb x umflusolveLupbAxb without refinement normAx b x umflusolveLupbAxbA with refinement normAx b dont forget to clear memory umfludelLup See Also umfpack umfluget umflusolve umfludel umfluinfo condestsp Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon with contributions from Antonio Frasson 2264 Name umfluget retrieve lu factors at the scilab level LUpqRd umflugetLUptr Parameters LUptr a pointer to umf lu factors LUpqR LU scilab sparse matrix pq column vectors storing the permutations Rd vector storing the row scaling factors Description This function may be used if you want to plot the sparse pattern of the lu factors or if you code something which use the lu factors The factorization provided by umfpack is of the form P R1 A Q LU where P and Q are permutation matrices R is a diagonal matrix row scaling L a lower triangular matrix with a diagonal of 1 and U an upper triangular matrix The function provides the matrices L and U as Sparse scilab matrices but P and Q are given as permutation vectors p and q in fact p is the permutation associated to P and Rd is the vector corresponding to the diagonal of R Examples this is the test matrix from UMFPACK A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 Lup umflufactA LUpqR umflugetLup B A for i15 Bi BiRi end apply the row scaling Bpq LU must be a quasi nul matrix umfludelLup clear memory the same with a complex matrix A sparse 2i 32i 0 0 0 3i 0 4i 0 63i 0 1i 36i 2i 0 0 0 15i 0 0 0 4 2i 0 1 Lup umflufactA LUpqR umflugetLup umfluget 2265 B A for i15 Bi BiRi end apply the row scaling Bpq LU must be a quasi nul matrix umfludelLup clear memory See Also umfpack umflufact umflusolve umfludel umfluinfo Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon 2266 Name umfluinfo get information on LU factors OK nrow ncol lnz unz udiagnz it umfluinfoLUptr Parameters LUptr a pointer to umf lu factors LUpq R OK a scalar boolean nrow ncol lnz unz udiagnz it scalars integers Description This function may be used to know basic information about LU factors created with umflufact first OK is t if LUptr is a valid pointer to an umfpack LU numeric handle and f else if OK is t then nrow ncol are the matrix size L is nrow x n and U is n x ncol where n minnrowncol lnz unz are the number of non zeros elements in L and in U udiagnz are the number of non zeros elements on the diagonal of U if the matrix is square nrow ncol n then it is not inversible if udiagnz n more precisely it appears to be numericaly not inversible through the LU factorization it 0 if the factors are real and 1 if they are complex if OK is f then all the others outputs are set to the empty matrix Examples this is the test matrix from UMFPACK A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 Lup umflufactA OK nrow ncol lnz unz udiagnz it umfluinfoLup OK must be t nrowncol 5 LUpqR umflugetLup nnzL must be equal to lnz nnzU must be equal to unz umfludelLup clear memory umfluinfo 2267 See Also umfpack umflufact umflusolve umfludel umfluget Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon 2268 Name umflusolve solve a linear sparse system given the LU factors x umflusolveLUptr b st A Parameters LUptr a pointer to umf lu factors LUpqR b a real or complex column vector or a matrix multiple rhs st optional a string Axb default or Axb to be written Axb in scilab langage a quote in a string must be doubled A optional the sparse square matrix corresponding to the LU factors LUptr must be got with LUptr umflufactA x a column vector or a matrix in case of multiple rhs xi is solution of A xi bi or Axi bi Description This function must be used in conjonction with umflufact which computes the LU factors of a sparse matrix The optional st argument lets us choose between the solving of Axb general case or of Axb sometimes useful If you give the 4th argument then iterative refinement will be also proceceed as in umfpack to give a better numerical solution Examples see the example section of umflufact See Also umfpack umflufact umfluget umfludel umfluinfo Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon with contributions from Antonio Frasson 2269 Name umfpack solve sparse linear system x umfpackAb x umfpackbA Parameters A a sparse real or complex square matrix n x n b in the first case a column vector n x 1 or a n x m matrix in the second case a row vector 1 x n or a m x n matrix x in the first case a column vector n x 1 or a n x m matrix in the second case a row vector 1 x n or a m x n matrix 2d arg string specifier or Description This function is intended to work like the classic operators and x Ab and x bA ie it solves a linear system Ax b or xA b with a sparse square says n x n real or complex matrix and with a compatible rhs b n x m in the first case and m x n in the second Details First an LU factorisation of the matrix is computed P R1 A Q LU where P and Q are permutation matrices R is a diagonal matrix row scaling L a lower triangular matrix with a diago nal of 1 and U an upper triangular matrix then a first solution is computed with forwardbackward subtitutions finaly the solution is improved by iterative refinement Examples this is the small linear test system from UMFPACK whom solution must be 12345 A sparse 2 3 0 0 0 3 0 4 0 6 0 1 3 2 0 0 0 1 0 0 0 4 2 0 1 b 8 45 3 3 19 x umfpackAb test the other form x A b b 8 20 13 6 17 x umfpackbA solution must be 1 2 3 4 5 test multiple rhs b rand53 x umfpackAb normAx b umfpack 2270 test multiple rhs for x A b b rand35 x umfpackbA normxA b solve a complex system A sparse 2i 32i 0 0 0 3i 0 4i 0 63i 0 1i 36i 2i 0 0 0 15i 0 0 0 4 2i 0 1 b 313i 5832i 1913i 1812i 2216i x umfpackAb x must be 1i 22i 33i 4 4i 55i A benchmark of several linear solvers Adescrrefmtype ReadHBSparseSCImodulesumfpackexamplesbcsstk24rsa b 0onessizeA11 tic res umfpackAb printf time needed to solve the system with umfpack 3f toc tic res linsolveAb printf time needed to solve the system with linsolve 3f toc tic res Ab printf time needed to solve the system with the backslash operator 3f toc See Also umflufact umflusolve umfludel umfluinfo umfluget linsolve backslash Authors umfpack by Timothy A Davis see umflicense scilab interface by Bruno Pincon with contributions from Antonio Frasson Parte L Algoritmos Genéticos 2272 Name codinggabinary A function which performs conversion between binary and continuous repre sentation popout codinggabinarypopindirectionparam Parameters popin a list which contains all the individuals in the current population direction code or decode If direction code then we perform a continuous to binary encoding Else we convert from binary to continuous param a parameter list binarylength the number of bits by variables If binarylength 8 and the variable X is of dimension 2 then the binary code will be 16 bits length minboun a vector of minimum bounds for the variable X maxbound a vector of maximum bounds for the variable X popout the population coded to binary or decoded to continuous values Description This function allows to code or decode a population of individuals from resp to continuous vari ables to resp from binary See Also optimga mutationgabinary crossovergabinary Authors Yann COLLETTE ycolletfreesurffr 2273 Name codinggaidentity A nooperation conversion function popout codinggaidentitypopindirectionparam Parameters popin the population to be converted direction code or decode This value has no influence of the state of popin param a parameter list For this function there are no useful parameters set popout a population identical to popin Description This function is a donothing function It is essentially useful to implement an evolutionnary algo rithm In an evolutionnary algorithm we work directly on the variable and not on a binary code See Also mutationfuncdefault crossoverfuncdefault initfuncdefault optimga Authors Yann COLLETTE ycolletfreesurffr 2274 Name crossovergabinary A crossover function for binary code CrossedIndiv1CrossedIndiv2 crossovergabinaryIndiv1Indiv2param Parameters Indiv1 the first individual here a binary code to be crossedover Indiv2 the second individual to be crossedover param a list of parameters binarylength the length of the binary code multicross a boolean If T then we allow several cuts in the binary code multicrossnb the number of cuts in the binary code Only used when multicross is set to T CrossedIndiv1 The first individual obtained by the crossover function CrossedIndiv2 The second individual obtained by the crossover function Description This function implements a classical binary crossover See Also crossovergabinary crossovergadefault mutationgabinary optimga Authors Yann COLLETTE ycolletfreesurffr 2275 Name crossovergadefault A crossover function for continuous variable functions CrossedIndiv1CrossedIndiv2 crossovergadefaultIndiv1Indiv2param Parameters Indiv1 The first individual to be crossedover Indiv2 The second individual to be crossedover param a list of parameters beta the range of the random generator A random value will be sampled between beta and 1beta This sampled value will be used to perform a convex combination between Indiv1 and Indiv2 minbound a vector of minimum bounds for the variable X maxbound a vector of maximum bounds for the variable X CrossedIndiv1 The first individual resulting from the crossover CrossedIndiv2 The second individual resulting from the crossover Description crossovergadefault is a crossover function for functions with continuous variables This crossover function is an extension of a convexe combination The crossed individuals are computed with the following equations mix 1 2Betarand11 Beta CrossedIndiv1 mixIndiv1 1mixIndiv2 CrossedIndiv2 1mixIndiv1 mixIndiv2 The Beta parameter should be set to a positive value If Beta is set to 0 the resulting crossover is a simple convexe combination between the two parents That may lead to a too fast convergence of the genetic algorithm and may decrease the diversity of the individuals of the population If Beta is chosen strictly positive that may allow children to explore the domain beyond the domain explored by their parents See Also crossovergabinary mutationgadefault initgadefault optimga References Michalewicz Zbigniew Genetic Algorithms Data Structures Evolution Programs crossovergadefault 2276 Authors Yann COLLETTE ycolletfreesurffr 2277 Name initgadefault A function a initialize a population Popinit initgadefaultpopsizeparam Parameters popsize the number of individuals to generate param a list of parameters dimension the size of the vector X minbound a vector of minimum bounds for the variable X maxbound a vector of maximum bounds for the variable X Popinit a list which contains the initial population of individuals Description This function generate an initial population containing popsize individuals See Also crossovergadefault mutationgadefault mutationgabinary optimga Authors Yann COLLETTE ycolletfreesurffr 2278 Name mutationgabinary A function which performs binary mutation MutIndiv mutationgabinaryIndivparam Parameters Indiv the individual on which we will perform the mutation param a list of parameters binarylength the size of the binary code multimut a boolean If T several random bits will be flipped multimutnd the number of bits to be flipped Works only when multimut is set to T MutIndiv The mutated individual Description This function performs a classical multibits binary mutation See Also mutationgadefault crossovergabinary initfuncdefault optimga Authors Yann COLLETTE ycolletfreesurffr 2279 Name mutationgadefault A continuous variable mutation function MutIndiv mutationgadefaultIndivparam Parameters Indiv The individual to be mutated param a list of parameters delta a random perturbation will be sampled via an uniform distribution between delta and delta minbound a vector of minimum bound for the variable X maxbound a vector of maximum bound for the variable X MutIndiv The resulting mutated individual Description This function performs the classical continuous variable mutation function See Also mutationgabinary crossovergadefault initgadefault optimga Authors Yann COLLETTE ycolletfreesurffr 2280 Name optimga A flexible genetic algorithm popoptfobjpopoptpopinitfobjpopinit optimgagafpopsizenbgenerationpmutpcrossLogparam Parameters gaf the function to be optimized The prototype if y fx or y listfp1p2 popsize the size of the population of individuals default value 100 nbgeneration the number of generations equivalent to the number of iterations in classical optimization to be computed default value 10 pmut the mutation probability default value 01 pcross the crossover probability default value 07 Log if T we will display to information message during the run of the genetic algorithm param a list of parameters codagefunc the function which will perform the coding and decoding of individuals default function codageidentity initfunc the function which will perform the initialization of the population default function initgadefault crossoverfunc the function which will perform the crossover between two individuals de fault function crossovergadefault mutationfunc the function which will perform the mutation of one individual default func tion mutationgadefault selectionfunc the function whcih will perform the selection of individuals at the end of a generation default function selectiongaelitist nbcouples the number of couples which will be selected so as to perform the crossover and mutation default value 100 pressure the value the efficiency of the worst individual default value 005 popopt the population of optimal individuals fobjpopopt the set of objective function values associated to popopt optional popinit the initial population of individuals optional fobjpopinit the set of objective function values associated to popinit optional optimga 2281 Description This function implements the classical genetic algorithm Examples deffyfxy sumx2 PopSize 100 Probacross 07 Probamut 01 NbGen 10 NbCouples 110 Log T nbdisp 10 Nb point to display from the optimal population pressure 005 gaparams initparam Parameters to adapt to the shape of the optimization problem gaparams addparamgaparamsminbound2 2 gaparams addparamgaparamsmaxbound2 2 gaparams addparamgaparamsdimension2 gaparams addparamgaparamsbeta0 gaparams addparamgaparamsdelta01 Parameters to fine tune the Genetic algorithm All these parameters are optional for continuous optimization If you need to adapt the GA to a special problem you gaparams addparamgaparamsinitfuncinitgadefault gaparams addparamgaparamscrossoverfunccrossovergadefault gaparams addparamgaparamsmutationfuncmutationgadefault gaparams addparamgaparamscodagefunccodagegaidentity gaparams addparamgaparamsselectionfuncselectiongaelitist gaparams addparamgaparamsselectionfuncselectiongarandom gaparams addparamgaparamsnbcouplesNbCouples gaparams addparamgaparamspressurepressure Min getparamgaparamsminbound Max getparamgaparamsmaxbound x0 Max Min randsizeMin1sizeMin2 Min popopt fobjpopopt popinit fobjpopinit optimgaf PopSize NbGen Probamut Probacross Log gaparams See Also optimmoga optimnsga optimnsga2 References Michalewicz Zbigniew Genetic Algorithms Data Structures Evolution Programs Authors Yann COLLETTE ycolletfreesurffr 2282 Name optimmoga multiobjective genetic algorithm popoptfobjpopoptpopinitfobjpopinit optimmogagafpopsizenbgenerationpmutpcrossLogparam Parameters gaf the function to be optimized The header of the function is the following y fx or y listfp1p2 popsize the size of the population of individuals default value 100 nbgeneration the number of generations equivalent to the number of iterations in classical optimization to be computed default value 10 pmut the mutation probability default value 01 pcross the crossover probability default value 07 Log if T we will display to information message during the run of the genetic algorithm param a list of parameters codagefunc the function which will perform the coding and decoding of individuals default function codageidentity initfunc the function which will perform the initialization of the population default function initgadefault crossoverfunc the function which will perform the crossover between two individuals de fault function crossovergadefault mutationfunc the function which will perform the mutation of one individual default func tion mutationgadefault selectionfunc the function whcih will perform the selection of individuals at the end of a generation default function selectiongaelitist nbcouples the number of couples which will be selected so as to perform the crossover and mutation default value 100 pressure the value the efficiency of the worst individual default value 005 optimmoga 2283 popopt the population of optimal individuals fobjpopopt the set of multiobjective function values associated to popopt optional popinit the initial population of individuals optional fobjpopinit the set of multiobjective function values associated to popinit optional Description This function implements the classical MultiObjective Genetic Algorithm For a demonstration see SCImodulesgeneticalgorithmsexamplesMOGAdemosce See Also optimga optimnsga optimnsga2 Authors Yann COLLETTE ycolletfreesurffr 2284 Name optimnsga A multiobjective Niched Sharing Genetic Algorithm popoptfobjpopoptpopinitfobjpopinit optimnsgagafpopsizenbgenerationpmutpcrossLogparamsigmapow Parameters gaf the function to be optimized The prototype if y fx or y listfp1p2 popsize the size of the population of individuals default value 100 nbgeneration the number of generations equivalent to the number of iterations in classical optimization to be computed default value 10 pmut the mutation probability default value 01 pcross the crossover probability default value 07 Log if T we will display to information message during the run of the genetic algorithm param a list of parameters codagefunc the function which will perform the coding and decoding of individuals default function codageidentity initfunc the function which will perform the initialization of the population default function initgadefault crossoverfunc the function which will perform the crossover between two individuals de fault function crossovergadefault mutationfunc the function which will perform the mutation of one individual default func tion mutationgadefault selectionfunc the function whcih will perform the selection of individuals at the end of a generation default function selectiongaelitist nbcouples the number of couples which will be selected so as to perform the crossover and mutation default value 100 pressure the value the efficiency of the worst individual default value 005 sigma the radius of the sharing area pow the power coefficient of the penalty formula popopt the population of optimal individuals fobjpopopt the set of objective function values associated to popopt optional optimnsga 2285 popinit the initial population of individuals optional fobjpopinit the set of objective function values associated to popinit optional Description This function implements the classical Niched Sharing Genetic Algorithm For a demonstration see SCImodulesgeneticalgorithmsexamplesNSGAdemosce See Also optimmoga optimga optimnsga2 Authors Yann COLLETTE ycolletfreesurffr 2286 Name optimnsga2 A multiobjective Niched Sharing Genetic Algorithm version 2 popoptfobjpopoptpopinitfobjpopinit optimnsga2gafpopsizenbgenerationpmutpcrossLogparam Parameters gaf the function to be optimized The prototype if y fx or y listfp1p2 popsize the size of the population of individuals default value 100 nbgeneration the number of generations equivalent to the number of iterations in classical optimization to be computed default value 10 pmut the mutation probability default value 01 pcross the crossover probability default value 07 Log if T we will display to information message during the run of the genetic algorithm param a list of parameters codagefunc the function which will perform the coding and decoding of individuals default function codageidentity initfunc the function which will perform the initialization of the population default function initgadefault crossoverfunc the function which will perform the crossover between two individuals de fault function crossovergadefault mutationfunc the function which will perform the mutation of one individual default func tion mutationgadefault selectionfunc the function whcih will perform the selection of individuals at the end of a generation default function selectiongaelitist nbcouples the number of couples which will be selected so as to perform the crossover and mutation default value 100 pressure the value the efficiency of the worst individual default value 005 popopt the population of optimal individuals fobjpopopt the set of objective function values associated to popopt optional popinit the initial population of individuals optional fobjpopinit the set of objective function values associated to popinit optional optimnsga2 2287 Description This function implements the classical Niched Sharing Genetic Algorithm For a demonstration see SCImodulesgeneticalgorithmsexamplesNSGA2demosce See Also optimmoga optimga optimnsga Authors Yann COLLETTE ycolletfreesurffr 2288 Name paretofilter A function which extracts non dominated solution from a set FoutXoutIndout paretofilterFinXin Parameters Fin the set of multiobjective function values from which we want to extract the non dominated so lutions Xin the associated values in the parameters space Fout the set of non dominated multiobjective function values Xout the associated values in the parameters space Indout the set of indexes of the non dominated individuals selected from the set Xin Description This function applies a Pareto filter to extract non dominated solutions from a set of values See Also optimmoga optimnsga optimnsga2 Authors Yann COLLETTE ycolletfreesurfFr 2289 Name selectiongaelitist An elitist selection function PopoutFObjPopoutEfficiencyMOTotalFObjout selectiongaelitistPopinIndiv1Indiv2FObjPopinFObjIndiv1FObjIndiv2MOTotalFObjinMOFObjIndiv1MOFObjIndiv2param Parameters Popin The initial population of individuals Indiv1 a first set of childs generated via crossover mutation Indiv2 a second set of childs generated via crossover mutation FObjPopin a vector of objective function values associated to each individuals of Popin FObjIndiv1 a vector of objective function values associated to each individuals of Indiv1 FObjIndiv2 a vector of objective function values associated to each individuals of Indiv2 MOTotalFObjin a matrix of multiobjective function values associated to each individuals of Popin MOFObjIndiv1 a matrix of multiobjective function values associated to each individuals of Indiv1 MOFObjIndiv2 a matrix of multiobjective function values associated to each individuals of Indiv2 param a list of parameters pressure the selection pressure coefficient Each individuals with 0 effi ciency will have an efficiency value equal to pressure Popout all the selected individuals in a population of size popsize FObjPopout all the objective function values associated to each individuals of Popout Efficiency all the efficiency values associated to each individuals of Popout MOTotalFObjout all the multiobjective function values associated to each individuals of Popout Description This function performs the elitist selection function We select the best individuals in the set of parents and childs individuals See Also selectiongarandom mutationgadefault crossovergadefault initgadefault optimga selectiongaelitist 2290 Authors Yann COLLETTE ycolletfreesurffr 2291 Name selectiongarandom A function which performs a random selection of individuals PopoutFObjPopoutEfficiencyMOTotalFObjout selectiongarandomPopinIndiv1Indiv2FObjPopinFObjIndiv1FObjIndiv2MOTotalFObjinMOFObjIndiv1MOFObjIndiv2param Parameters Popin The initial population of individuals Indiv1 a first set of childs generated via crossover mutation Indiv2 a second set of childs generated via crossover mutation FObjPopin a vector of objective function values associated to each individuals of Popin FObjIndiv1 a vector of objective function values associated to each individuals of Indiv1 FObjIndiv2 a vector of objective function values associated to each individuals of Indiv2 MOTotalFObjin a matrix of multiobjective function values associated to each individuals of Popin MOFObjIndiv1 a matrix of multiobjective function values associated to each individuals of Indiv1 MOFObjIndiv2 a matrix of multiobjective function values associated to each individuals of Indiv2 param a list of parameters pressure the selection pressure coefficient Each individuals with 0 efficiency will have an efficiency value equal to pressure Popout all the selected individuals in a population of size popsize FObjPopout all the objective function values associated to each individuals of Popout Efficiency all the efficiency values associated to each individuals of Popout MOTotalFObjout all the multiobjective function values associated to each individuals of Popout Description This function performs the random selection function We select popsize individuals in the set of parents and childs individuals at random See Also selectiongaelitist mutationgadefault crossovergadefault initgadefault optimga selectiongarandom 2292 Authors Yann COLLETTE ycolletfreesurffr Parte LI Arrefecimento Simulado 2294 Name computeinitialtemp A SA function which allows to compute the initial temperature of the sim ulated annealing Tinit computeinitialtempx0fprobainitItMXneighfuncparamneighfunc Parameters x0 the starting point f the objective function which will be send to the simulated annealing for optimization probainit the initial probability of accepting a bad solution usually around 07 ItMX the number of iterations of random walk usually around 100 neighfunc a function which returns a neighbor of a given point see the help page of neighfunc to see the prototype of this function paramneighfunc some parameters can be a list which will be sent as parameters to neighfunc Tinit The initial temperature corresponding to the given probability of accepting a bad solution Description This function computes an initial temperature given an initial probability of accepting a bad solution This computation is based on some iterations of random walk Examples deffyfxysumx2 x0 2 2 Probastart 07 ItPre 100 xtest neighfuncdefaultx0 comptparams initparam comptparams addparamcomptparamsneighfunc neighfuncdefault T0 computeinitialtempx0 rastrigin Probastart ItPre comptsa See Also optimsa neighfuncdefault templawdefault Authors collette Yann COLLETTE ycolletfreesurffr 2295 Name neighfunccsa The classical neighborhood relationship for the simulated annealing xneigh neighfunccsaxcurrentTparam Parameters xcurrent the point for which we want to compute a neighbor T the current temperature param a vector with the same size than xcurrent A normalisation vector which allows to distort the shape of the neighborhood This parameter allows to take into account the differences of interval of variation between variables By default this parameter is set to a vector of ones xneigh the computed neighbor Description This function implements the classical neighborhood relationship for the simulated annealing The neighbors distribution is a gaussian distribution which is more and more peaked as the temperature decrease See Also neighfuncdefault templawhuang optimsa Authors collette Yann COLLETTE ycolletfreesurffr 2296 Name neighfuncdefault A SA function which computes a neighbor of a given point xneigh neighfuncdefaultxcurrentTparam Parameters xcurrent the point for which we want to compute a neighbor T the current temperature param a two columns vector The first column correspond to the negative amplitude of variation and the second column corresponds to the positive amplitude of variation of the neighborhood By default the first column is a column of 01 and the second column is a column of 01 xneigh the computed neighbor Description This function computes a neighbor of a given point For example for a continuous vector a neighbor will be produced by adding some noise to each component of the vector For a binary string a neighbor will be produced by changing one bit from 0 to 1 or from 1 to 0 Examples We produce a neighbor by adding some noise to each component of a given vector function xneigh neighfuncdefaultxcurrent T samindelta 01onessizexcurrent1sizexcurrent2 samaxdelta 01onessizexcurrent1sizexcurrent2 xneigh xcurrent samaxdelta samindeltarandsizexcurrent1sizexcurrent2 samindelta endfunction See Also optimsa computeinitialtemp templawdefault Authors collette Yann COLLETTE ycolletfreesurffr 2297 Name neighfuncfsa The Fast Simulated Annealing neghborhood relationship xneigh neighfuncfsaxcurrentTparam Parameters xcurrent the point for which we want to compute a neighbor T the current temperature param a vector with the same size than xcurrent A normalisation vector which allows to distort the shape of the neighborhood This parameter allows to take into account the differences of interval of variation between variables By default this parameter is set to a vector of ones xneigh the computed neighbor Description This function computes the FSA neighborhood of a given point The corresponding distribution is a Cauchy distribution which is more and more peaked as the temperature decrease See Also optimsa templawfsa neighfuncdefault Authors collette Yann COLLETTE ycolletfreesurffr 2298 Name neighfuncvfsa The Very Fast Simulated Annealing neighborhood relationship xneigh neighfuncvfsaxcurrentTparam Parameters xcurrent the point for which we want to compute a neighbor T the current temperature param a ones column vector The column correspond to the amplitude of variation of the neighborhood By default the column is a column of 01 xneigh the computed neighbor Description This function implements the Very Fast Simulated Annealing relationship This distribution is more and more peaked as the temperature decrease See Also optimsa neighfuncvfsa templawhuang Authors collette Yann COLLETTE ycolletfreesurffr 2299 Name optimsa A Simulated Annealing optimization method xbestfbestmeanlistvarlistfhistorytemplistxhistory optimsax0fItExtItIntT0Logtemplawparamtemplawneighfuncparamneighfunc Parameters x0 the initial solution f the objective function to be optimized the prototype if fx ItExt the number of temperature decrease ItInt the number of iterations during one temperature stage T0 the initial temperature see computeinitialtemp to compute easily this temperature Log if T some information will be displayed during the run of the simulated annealing templaw the temperature decrease law see templawdefault for an example of such a function paramtemplaw a structure of any kind it depends on the temperature law used which is transmitted as a pa rameter to templaw neighfunc a function which computes a neighbor of a given point see neighfuncdefault for an example of such a function paramneighfunc a structure of any kind like vector list it depends on the neighborhood function used which is transmitted as a parameter to neighfunc xbest the best solution found so far fbest the objective function value corresponding to xbest meanlist the mean of the objective function value for each temperature stage A vector of float optional varlist the variance of the objective function values for each temperature stage A vector of float op tional fhistory the computed objective function values for each iteration Each input of the list corresponds to a temperature stage Each input of the list is a vector of float which gathers all the objective function values computed during the corresponding temperature stage optional templist the list of temperature computed for each temperature stage A vector of float optional optimsa 2300 xhistory the parameter values computed for each iteration Each input of the list corresponds to a temper ature stage Each input of the list is a vector of input variables which corresponds to all the vari ables computed during the corresponding temperature stage optional can slow down a lot the execution of optimsa Description A Simulated Annealing optimization method Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 2 2 Probastart 07 ItPre 100 Itextern 100 Itintern 1000 xtest neighfuncdefaultx0 comptparams initparam comptparams addparamcomptparamsneighfunc neighfuncdefault T0 computeinitialtempx0 rastrigin Probastart ItPre comptsa xopt fopt sameanlist savarlist optimsax0 rastrigin Itextern Itintern T0 Log T printfoptimal solution dispxopt printfvalue of the objective function f fopt t 1lengthsameanlist plottsameanlistrtsavarlistg See Also computeinitialtemp neighfuncdefault templawdefault Authors collette Yann COLLETTE ycolletfreesurffr 2301 Name templawcsa The classical temperature decrease law Tout templawcsaTinstepmeanstepvartempstagenparam Parameters Tin the temperature at the current stage stepmean the mean value of the objective function computed during the current stage stepvar the variance value of the objective function computed during the current stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param not used for this temperature law Tout the temperature for the temperature stage to come Description This function implements the classical annealing temperature schedule the one for which the con vergence of the simulated annealing has been proven Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 1 1 Probastart 08 Itintern 1000 Itextern 30 ItPre 100 printfSA the CSA algorithm T0 computeinitialtempx0 rastrigin Probastart ItPre neighfuncdefault printfInitial temperatore T0 f T0 xopt fopt sameanlist savarlist templist optimsax0 rastrigin Itextern Itintern T0 Log T templawcsa neighfunccsa printfoptimal solution dispxopt printfvalue of the objective function f fopt scf templawcsa 2302 subplot211 xtitleClassical simulated annealingIterationMean Variance t 1lengthsameanlist plottsameanlistrtsavarlistg legendMeanVariance subplot212 xtitleTemperature evolutionIterationTemperature plotttemplistk See Also optimsa templawhuang neighfuncdefault Authors collette Yann COLLETTE ycolletfreesurffr 2303 Name templawdefault A SA function which computed the temperature of the next temperature stage Tnext templawdefaultTstepmeanstepvartempstagenparam Parameters T the temperature applied during the last temperature stage stepmean the mean of the objective function values computed during the last temperature stage stepvar the variance of the obejective function values computed during the last temperature stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param a float between 0 and 1 Corresponds to the decrease in temperature of the geometric law 09 by default Tnext the new temperature to be applied for the next temperature stage Description A SA function which computed the temperature of the next temperature stage Examples This function implements the simple geometric temperature law function T templawdefaultT stepmean stepvar alpha 09 T alphaT endfunction See Also optimsa computeinitialtemp neighfuncdefault Authors collette Yann COLLETTE ycolletfreesurffr 2304 Name templawfsa The Szu and Hartley Fast simulated annealing Tout templawfsaTinstepmeanstepvartempstagenparam Parameters Tin the temperature at the current stage stepmean the mean value of the objective function computed during the current stage stepvar the variance value of the objective function computed during the current stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param not used for this temperature law Tout the temperature for the temperature stage to come Description This function implements the Fast simulated annealing of Szu and Hartley Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 1 1 Probastart 08 Itintern 1000 Itextern 30 ItPre 100 printfSA the FSA algorithm T0 computeinitialtempx0 rastrigin Probastart ItPre neighfuncdefault printfInitial temperatore T0 f T0 xopt fopt sameanlist savarlist templist optimsax0 rastrigin Itextern Itintern T0 Log T templawfsa neighfuncfsa printfoptimal solution dispxopt printfvalue of the objective function f fopt scf subplot211 templawfsa 2305 xtitleFast simulated annealingIterationMean Variance t 1lengthsameanlist plottsameanlistrtsavarlistg legendMeanVariance subplot212 xtitleTemperature evolutionIterationTemperature plotttemplistk See Also optimsa templawhuang neighfuncdefault Authors collette Yann COLLETTE ycolletfreesurffr 2306 Name templawhuang The Huang temperature decrease law for the simulated annealing Tout templawhuangTinstepmeanstepvartempstagenparam Parameters Tin the temperature at the current stage stepmean the mean value of the objective function computed during the current stage stepvar the variance value of the objective function computed during the current stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param a float corresponding to the lambda parameter of the Huang temperature decrease law 001 by default Tout the temperature for the temperature stage to come Description This function implements the Huang temperature decrease law for the simulated annealing Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 1 1 Probastart 08 Itintern 1000 Itextern 30 ItPre 100 printfSA the Huang temperature decrease law T0 computeinitialtempx0 rastrigin Probastart ItPre neighfuncdefault printfInitial temperatore T0 f T0 xopt fopt sameanlist savarlist templist optimsax0 rastrigin Itextern Itintern T0 Log T templawhuang neighfuncdefault printfoptimal solution dispxopt printfvalue of the objective function f fopt scf templawhuang 2307 subplot211 xtitleHuang simulated annealingIterationMean Variance t 1lengthsameanlist plottsameanlistrtsavarlistg legendMeanVariance subplot212 xtitleTemperature evolutionIterationTemperature plotttemplistk See Also optimsa templawcsa neighfunccsa Authors collette Yann COLLETTE ycolletfreesurffr 2308 Name templawvfsa This function implements the Very Fast Simulated Annealing from L Ingber Tout templawvfsaTinstepmeanstepvartempstagen param Parameters Tin the temperature at the current stage stepmean the mean value of the objective function computed during the current stage stepvar the variance value of the objective function computed during the current stage tempstage the index of the current temperature stage n the dimension of the decision variable the x in fx param a float the c parameter of the VFSA method 001 by default Tout the temperature for the temperature stage to come Description This function implements the Very Fast Simulated Annealing from L Ingber Examples function y rastriginx y x12x22cos12x1cos18x2 endfunction x0 1 1 Probastart 08 Itintern 1000 Itextern 30 ItPre 100 printfSA the VFSA algorithm T0 computeinitialtempx0 rastrigin Probastart ItPre neighfuncdefault printfInitial temperatore T0 f T0 xopt fopt sameanlist savarlist templist optimsax0 rastrigin Itextern Itintern T0 Log T templawvfsa neighfuncvfsa printfoptimal solution dispxopt printfvalue of the objective function f fopt scf subplot211 templawvfsa 2309 xtitleVFSA simulated annealingIterationMean Variance t 1lengthsameanlist plottsameanlistrtsavarlistg legendMeanVariance subplot212 xtitleTemperature evolutionIterationTemperature plotttemplistk See Also optimsa neighfuncvfsa templawhuang Authors collette Yann COLLETTE ycolletfreesurffr Parte LII Parâmetros 2311 Name addparam Add a parameter to a list of parameters paramlisterr addparamlistnameparamnameparamvalue Parameters listname the list of parameters This list must have been initialize by a call to initparam paramname a string The name of the parameter to be added in the list of parameters paramvalue the value associated to the parameter paramname This parameter is optional You can set the value of this parameter via a call to setparam paramlist the updated list of parameters err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function creates a new parameter in a list of parameters You can set the value of the parameter using this function or you can set it via a call to setparam Examples mylist initparam mylist addparammylistminbound0 0 0 See Also initparam setparam getparam removeparam isparam Authors collette ycolletfreesurffr 2312 Name getparam Get the value of a parameter in a parameter list reserr getparamlistnameparamnamedefaultvalue Parameters listname the list of parameters This list must have been initialized by a call to initparam paramname a string The name of the parameter to be add in the list of parameters defaultvalue the default value to be stored in the parameter if paramname has not been found res the value of the parameter If the parameter doesnt exist res err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function returns the value of the parameter paramname in a parameter list If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 dispgetparammylistminbound1 1 1 dispgetparammylistmaxbound 1 1 1 See Also initparam setparam addparam removeparam isparam Authors collette ycolletfreesurffr 2313 Name initparam Initialize the structure which will handles the parameters list paramlist initparam Parameters paramlist an initialized list of parameters this list is empty and is of type plist Description This function initialize an empty list of parameters You must initialize the list of parameters before using it Examples mylist initparam mylist addparammylistminbound0 0 0 See Also addparam setparam getparam removeparam isparam Authors collette ycolletfreesurffr 2314 Name isparam Check if a parameter is present in a parameter list reserr isparamlistnameparamname Parameters listname the list of parameters This list must have been initialize by a call to initparam paramname a string The name of the parameter to be add in the list of parameters res the result T is the parameter is present F otherwise err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function checks if a parameter is present in a parameter list If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 dispisparammylistminbound dispisparammylistmaxbound See Also initparam setparam getparam removeparam addparam Authors collette ycolletfreesurffr 2315 Name listparam List all the parameters name in a list of parameters stringlisterr listparamlistname Parameters listname the list of parameters This list must have been initialize by a call to initparam stringlist the list of parameters name err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description List all the parameters name in a list of parameters If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 mylist addparammylistmaxbound1 1 1 displistparammylist See Also initparam setparam getparam removeparam isparam Authors collette ycolletfreesurffr 2316 Name removeparam Remove a parameter and its associated value from a list of parameters paramlisterr removeparamlistnameparamname Parameters listname the list of parameters This list must have been initialize by a call to initparam paramname a string The name of the parameter to be removed from the list of parameters If the parameter doesnt exist nothing happens paramlist the updated list of parameters err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function allows to remove a parameter and its associated value from a list of parameters If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 mylist addparammylistmaxbound0 0 0 mylist removeparammylistminbound See Also initparam setparam getparam addparam isparam Authors collette ycolletfreesurffr 2317 Name setparam Set the value of a parameter in a parameter list paramlisterr setparamlistnameparamnameparamvalue Parameters listname the list of parameters This list must have been initialize by a call to initparam paramname a string The name of the parameter to be added in the list of parameters paramvalue the value to be associated to the parameter paramname paramlist the updated list of parameters err an error flag which is set to T if listname is not of type plist this list hasnt been initialized by a call to initparam Description This function sets the value of an already existing parameter If the parameter doesnt exist err is set to T If the err output parameter is not present when an error occurs a message is printed in the console Examples mylist initparam mylist addparammylistminbound0 0 0 mylisterr setparammylistminbound1 1 1 disperr mylisterr setparammylistmaxbound1 1 1 disperr See Also initparam addparam getparam removeparam isparam Authors collette ycolletfreesurffr Parte LIII Atoms 2319 Name Getting started Introduction This page teaches how to get started with ATOMS module manager on the scilab platform towards a session example It describes how one can install a module and load it in Scilab environment Atoms Configure ATOMS to display extrainformations atomsSetConfigVerboseTrue List available modules atomsList ampltoolbox An interface to load nl files created by AMPL ANNToolbox ANN Toolbox conmin A Scilab interface to the conmin optimization method CUTEr Testing environment for optimization and linear algebra solvers dacescilab This is a conversion of the well known DACE kriging toolbox for Matlab ddetoolbox Dynamic Data Exchange client for Scilab HYDROGRv50 Models and function for operational hydrology lolimot A fast neural network LOcal LInear MOdel Tree modulelycee Scilab pour les lycées NISP Non Intrusive Spectral Projection plotlib Matlablike Plotting library for Scilab scilab2c Translate Scilab code into C code scipad Scipad 720 simplex This package contains the simplex optimization method sndfiletoolbox Read write sound files stixbox Statistics toolbox for Scilab 52 Install a module Installing a module download and extract it atomsInstallNISP NISP 21 will be installed in the allusers section Installing NISP 21 success Load a module The module is installed but its not loaded in the scilab environment and its func tionnalities are not available yet Getting started 2320 By default a module is added to the list of modules to load at Scilab start when its installed More information on the autoload system atomsAutoloadList atomsAutoloadAdd atom sAutoloadDel atomsLoadNISP Start NISP Toolbox Load gateways Load help Load demos Remove a module atomsRemove NISP NISP 21 will be removed from the allusers section the package NISP 21 is currently loaded It will removed at next Scilab restart Authors Pierre MARECHAL DIGITEO 2321 Name Functions Summary InstallRemoveUpdate modules atomsInstall Install one or several modules atomsUpdate Update one or several modules atomsRemove Remove one or several modules atomsGetInstalled Get the list of installed external modules atomsIsInstalled Determines whether the module is installed or not Load modules atomsLoad Load one or several modules atomsGetLoaded Get the list of loaded modules atomsIsLoaded Determines whether the module is loaded or not atomsAutoloadList Get the list of modules registered to autoload at Scilab start atomsAutoloadAdd Add one or several modules to autoload system atomsAutoloadDel Remove one or several modules from autoload system Get information atomsList List available modules atomsSearch Searches for modules atomsShow Show the caracteristics of a module atomsDepTreeShow Show the dependency tree of a module Manage repositories atomsRepositoryList Get the list of managed repositories atomsRepositoryAdd Add one or several URLs to the list of managed repositories atomsRepositoryDel Remove one or several URLs from the list of man aged repositories Manage ATOMS system atomsSystemUpdate Update the list of available modules atomsSetConfig Manage ATOMS parameters Authors Pierre MARECHAL DIGITEO 2322 Name atomsAutoloadAdd Add one or several modules to autoload nbAdd atomsAutoloadAddmodulessection Parameters modules mx1 mx2 or mx3 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present the most recent version is used 3rd Col Installed section Optionnal If this field is emp ty or is not present and module is in stalled in both user and allusers sections the section of autoload list is used section This argument controls which autoload list is changed section is a singlestring and its value should be allusers modules are added to the allusers autoload list and all users of scilab are affected user modules are added to the user autoload list and only the current user is affected If SCIcontrib is write accessible allusers is the default value Otherwise the default value is user nbAdd An integer the number of modules successfully added Description Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsSetConfigautoloadAddAfterInstallFalse atomsInstalltoolbox5user atomsAutoloadList atomsAutoloadAddtoolbox5user atomsAutoloadList atomsAutoloadAdd 2323 atomsAutoloadDeltoolbox5 atomsAutoloadAddtoolbox5 10user atomsAutoloadList atomsAutoloadDeltoolbox5 atomsAutoloadAddtoolbox5 10 useruser atomsAutoloadList atomsRemovetoolbox5user atomsSetConfigautoloadAddAfterInstallTrue atomsRepositoryDelhttpscene1testatomsscilaborg atomsAutoloadList See Also atomsAutoloadDel atomsAutoloadList Authors Pierre MARECHAL DIGITEO 2324 Name atomsAutoloadDel Remove one or several modules from the autoload system nbDel atomsAutoloadDelmodulessection Parameters modules mx1 mx2 or mx3 character string matrix 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present all ver sions of the module are removed from the au toload system 3rd Col Installed section Optionnal If this field is empty or is not present modules installed in both user and allusers sections are searched section This argument controls the list of sections where search moduless to remove from autoload system section is a singlestring and its value should be all modules to remove from autotoload list are searched in both user and allusers sections allusers modules to remove from autotoload system are only searched in the allusers autoload list user modules to remove from autotoload system are only searched in the user autoload list If SCI is write accessible all is the default value Otherwise the default value is user nbDel An integer the number of modules successfully removed from the autoload system Description atomsAutoloadDel remove one or several modules from the autoload system Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox5user atomsAutoloadList atomsAutoloadDel 2325 atomsAutoloadDeltoolbox5 atomsAutoloadList atomsAutoloadAddtoolbox5 10 useruser atomsAutoloadList atomsAutoloadDeltoolbox5 10 atomsAutoloadList atomsAutoloadAddtoolbox5 10 useruser atomsAutoloadList atomsAutoloadDeltoolbox5 10 user atomsAutoloadList atomsAutoloadAddtoolbox5 10 useruser atomsAutoloadList atomsAutoloadDeltoolbox5 10 useruser atomsAutoloadList atomsRemovetoolbox5user atomsRepositoryDelhttpscene1testatomsscilaborg See Also atomsAutoloadAdd atomsAutoloadList Authors Pierre MARECHAL DIGITEO 2326 Name atomsAutoloadList Get the list of modules registered to autoload modules atomsAutoloadListsection Parameters section This argument controls the list of section where search URLs section is a singlestring and its value should be all modules present on both user and allusers autoload lists are returned allusers only modules present on the allusers autoload lists are returned user only modules present on the user autoload lists are returned The default value is all modules 4xn character string matrix 1st Col Modules technical name 2nd Col Modules version 3rd Col Modules installed section 4th Col Autoload list section Description atomsAutoloadList returns the list of modules registered to autoload Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox1 atomsAutoloadListuser atomsAutoloadListallusers atomsAutoloadListall atomsRemovetoolbox1 atomsRepositoryDelhttpscene1testatomsscilaborg See Also atomsAutoloadAdd atomsAutoloadDel Authors Pierre MARECHAL DIGITEO 2327 Name atomsDepTreeShow Show the dependency tree of a module atomsDepTreeShowmodule Parameters module 1x1 or 1x2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present the most recent version is used Description atomsDepTreeShow shows the dependency tree of an external module Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsDepTreeShowtoolbox6 See Also atomsShow atomsList Authors Pierre MARECHAL DIGITEO 2328 Name atomsGetInstalled Get the list of installed external modules installed atomsGetInstalledsection Parameters installed 5xn String matrix 1st column External modules technical name 2nd column External modules version 3rd column allusersuser this parameter tell if the external module has been installed for all users or only for the current user 4th column External modules installation path 5th column IA this parameter tell if the external module has been automatically or in tentionnaly installed section This argument filter the output list section is a singlestring and its value should be all atomsGetInstalled lists external modules installed in both user and allusers sec tions allusers atomsGetInstalled only lists external modules installed in the allusers sec tion user atomsGetInstalled only lists external modules installed in the user section The default value is all Description atomsGetInstalled returns the list of installed external modules Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox5 atomsGetInstalled atomsRemovetoolbox5 See Also atomsInstall atomsIsInstalled atomsGetInstalled 2329 Authors Pierre MARECHAL DIGITEO 2330 Name atomsGetLoaded Get the list of loaded external modules loaded atomsGetLoaded Parameters loaded 5xn String matrix 1st column External modules technical name 2nd column External modules version 3rd column allusersuser this parameter tell if the external module has been installed for all users or only for the current user 4th column External modules installation path 5th column IA this parameter tell if the external module has been automatically or in tentionnaly installed Description atomsGetLoaded returns the list of loaded external modules Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox5 atomsLoadtoolbox5 atomsGetLoadedtoolbox5 atomsRemovetoolbox5 See Also atomsLoad atomsIsLoaded Authors Pierre MARECHAL DIGITEO 2331 Name atomsInstall Install one or several external modules result atomsInstallmodulessection result atomsInstallfile Parameters modules mx1 mx2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present the most recent version is used file mx1 Matrix of strings 1st Col Filesystem path Mandatory section This argument controls where the external module is installed section is a singlestring and its value should be allusers the external module is installed for all users of the computer and is located in SCIcontrib allusers zone user the external module is only installed for the current user and is located in SCI HOMEatoms user zone If SCIcontrib is write accessible allusers is the default value Otherwise the default value is user result 5xn character string matrix 1st Col Technical name 2nd Col Version 3rd Col Installation section this parameter determines whether the module has been installed for all users or only for the current user 4th Col Installation path 5th Col Status I stands for Intentionnaly A stands for Automatically Description atomsInstall install one or more external modules atomsInstall 2332 Examples Example 1 Installing a module from a repository Display some additionnal informations atomsSetConfigVerboseTrue Load the test repository atomsRepositoryAddhttpscene1testatomsscilaborg Install a module atomsInstalltoolbox1 Install a specific version atomsInstalltoolbox2 20 Install several modules atomsInstalltoolbox4 10 toolbox2 10 Install a module in the user section atomsInstalltoolbox5user Install a module in the allusers section write access on SCI directory is needed atomsInstalltoolbox6 10toolbox3 10 allusers Get the list of installed modules disp atomsGetInstalled Cleaning atomsRemovetoolbox1 toolbox2 toolbox3 toolbox4 toolbox5 toolbox6 Example 2 Installing a local module As well as installing modules from the central repository you can also install modules directly from your own machine Display some additionnal informations atomsSetConfigVerboseTrue Install a module atomsInstallSCImodulesatomstestsunitteststoolbox7101binzip Get the list of installed modules disp atomsGetInstalled Cleaning atomsRemovetoolbox7 atomsInstall 2333 See Also atomsIsInstalled atomsGetInstalled atomsRemove Authors Pierre MARECHAL DIGITEO 2334 Name atomsIsInstalled Determines whether the module is installed Returns true if the module is installed false otherwise res atomsIsInstalledmodulessection Parameters modules mx1 mx2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present modules version is ignored 3rd Col Section Optionnal If this field is empty or is not present modules section is ignored section This argument controls the list of searched modules section is a singlestring and its value should be all atomsIsInstalled searchs external modules installed in both user and allusers sections allusers atomsIsInstalled searchs external modules installed in the allusers section user atomsIsInstalled searchs external modules installed in the user section The default value is all res Description Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg Install the needed module for the purpose of the example atomsInstalltoolbox5user simplest way atomsIsInstalledtoolbox5 Check several modules atomsIsInstalledtoolbox5 toolbox4 atomsIsInstalled 2335 with a specific version atomsIsInstalledtoolbox5 10 toolbox4 10 toolbox5 11 installed in a specific section atomsIsInstalledtoolbox5 10 toolbox4 10 toolbox5 11user atomsIsInstalledtoolbox5 10 toolbox4 10 toolbox5 11allusers Some cleaning atomsRepositoryDelhttpscene2testatomsscilaborg atomsRemovetoolbox2 See Also atomsInstall atomsGetInstalled Authors Pierre MARECHAL DIGITEO 2336 Name atomsIsLoaded determines whether a module is loaded or not result atomsIsLoadedmodules Parameters modules mx1 mx2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present modules version is ignored 3rd Col Section Optionnal If this field is empty or is not present modules section is ignored result mx1 boolean matrix Description atomsIsLoaded determines whether a module is loaded or not Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene2testatomsscilaborg Install toolbox4 both 10 and 11 version atomsInstalltoolbox4 10user Load the version 10 atomsLoadtoolbox4 10 Ignore the modules version atomsIsLoadedtoolbox4 With a specific version atomsIsLoadedtoolbox4 10 Check several modules atomsIsLoaded toolbox4 10 toolbox4 11 toolbox1 10 Some cleaning atomsRepositoryDelhttpscene2testatomsscilaborg atomsRemovetoolbox2 atomsIsLoaded 2337 See Also atomsLoad atomsGetLoaded Authors Pierre MARECHAL DIGITEO 2338 Name atomsList List available external modules atomsList Description List available external modules Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsList See Also atomsShow atomsDepTreeShow Authors Pierre MARECHAL DIGITEO 2339 Name atomsLoad Install one or several external modules result atomsLoadnameversion Parameters name Matrix of strings External module name version Matrix of strings External module version This is an optional parameter If its not defined the most recent version of the module is used result Description atomsLoad install one or more external modules Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg atomsInstalltoolbox2 10 atomsInstalltoolbox2 20 atomsLoadtoolbox2 10 t2version t2function1 atomsRemovetoolbox2 See Also atomsIsLoaded atomsGetLoaded Authors Pierre MARECHAL DIGITEO 2340 Name atomsRemove Remove one or several modules result atomsRemovemodulessection Parameters modules mx1 or mx2 character string matrix 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present all ver sions of the module are removed section This argument controls the list of sections where search modules to remove section is a singlestring and its value should be all Modules to remove are searched in both user and allusers sections allusers Modules to remove are only searched in the allusers section user Modules to remove are only searched in the user section If SCI is write accessible all is the default value Otherwise the default value is user result 5xn character string matrix 1st Col Technical name 2nd Col Version 3rd Col Installation section this parameter determines whether the module has been installed for all users or only for the current user 4th Col Installation path 5th Col Status I stands for Intentionnaly A stands for Automatically Description atomsRemove remove one or more modules Examples Display some additionnal informations atomsSetConfigVerboseTrue atomsRemove 2341 Load the test repository atomsRepositoryAddhttpscene2testatomsscilaborg install toolbox4 both 10 and 11 versions Remove all versions of a module atomsInstalltoolbox4 10toolbox4 11user atomsRemovetoolbox4 Remove a specific version atomsInstalltoolbox4 10toolbox4 11user atomsRemovetoolbox4 10 atomsRemovetoolbox4 11 Remove several modules atomsInstalltoolbox4toolbox3user atomsRemovetoolbox4toolbox3 Remove a module from a specific section This example needs write access on SCI directory atomsInstalltoolbox4user atomsInstalltoolbox4allusers dispatomsGetInstalled atomsRemovetoolbox4user dispatomsGetInstalled atomsRemovetoolbox4allusers dispatomsGetInstalled Unload the test repository atomsRepositoryDelhttpscene2testatomsscilaborg See Also atomsRemove atomsIsInstalled atomsGetInstalled Authors Pierre MARECHAL DIGITEO 2342 Name atomsRepositoryAdd Add one or several URLs to the list of managed repositories nbAdd atomsRepositoryAddurlsection Parameters url Matrix of strings list of the URLs to add section This argument controls where the repository is added section is a singlestring and its value should be allusers the repository is added to the allusers list and all user of scilab are affected user the repository is added to the user list and only the current user is affected If SCIcontrib is write accessible allusers is the default value Otherwise the default value is user nbAdd An integer the number of repositories successfully added Description Examples atomsRepositoryList atomsRepositoryAddhttpscene1testatomsscilaborg atomsRepositoryList See Also atomsRepositoryDel atomsRepositoryList Authors Pierre MARECHAL DIGITEO 2343 Name atomsRepositoryDel Remove one or several URLs from the list of managed repositories nbDel atomsRepositoryDelurlsection Parameters url character string matrix list of the URLs to remove section This argument controls the list of sections where search URLs to remove section is a singlestring and its value should be all URLs to remove are searched in both user and allusers sections allusers URLs to remove are only searched in the allusers section user URLs to remove are only searched in the user section If SCI is write accessible all is the default value Otherwise the default value is user nbDel An integer the number of repositories successfully removed Description Examples atomsRepositoryList atomsRepositoryAddhttpscene1testatomsscilaborg atomsRepositoryList atomsRepositoryDelhttpscene1testatomsscilaborg atomsRepositoryList See Also atomsRepositoryAdd atomsRepositoryList Authors Pierre MARECHAL DIGITEO 2344 Name atomsRepositoryList Get the list of managed repositories repositories atomsRepositoryListsection Parameters section This argument controls the list of section where search URLs section is a singlestring and its value should be all URLs present in the user allusers and official section are listed allusers only URLs present in the allusers section are listed user only URLs present in the user section are listed official only URLs present in the official section are listed The default value is all repositories Matrix of strings the first column give the list of repositories managed by ATOMS and the second column indicate if the repository is a official repository if the repository has been added for all users or only for the current user Description atomsRepositoryList return a matrix that give the list of available repositories Examples atomsRepositoryAddhttpscene1atomsscilaborg atomsRepositoryList atomsRepositoryListall atomsRepositoryListofficial atomsRepositoryListallusers atomsRepositoryListuser atomsRepositoryDelhttpscene1atomsscilaborg See Also atomsRepositoryAdd atomsRepositoryDel Authors Pierre MARECHAL DIGITEO 2345 Name atomsSearch Searches for external modules result atomsSearchpattern Parameters pattern String The pattern to search for result Description atomsSearch searches for packages matching one of the patterns supplied as input argument Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg atomsSearchtoolbox See Also atomsList Authors Pierre MARECHAL DIGITEO 2346 Name atomsSetConfig Manage ATOMS system parameters result atomsSetConfigparametervalue Parameters parameter singlestring matrix value singlestring matrix result Number of changed parameters Proxy Parameter Description Values useProxy UseDont use proxies TrueFalse proxyHost the hostname IP or DNS name proxyPort the port proxyUser Specify the username for authen tication on a proxy server proxyPassword Specify the password for authen tication on a proxy server Network Parameter Description Values offLine If set to True the system on ly works with local repositories The offline mode permits the us er to install modules from a lo cal repository or a local package hard disk USB keys even if the network is unreachable TrueFalse Autoload System Parameter Description Values autoload EnableDisable autoload system TrueFalse autoloadAddAfterInstall Automatically add a module to the list of module to autoload at Scilab start TrueFalse Miscellenous Parameter Description Values atomsSetConfig 2347 verbose Display or not extrainforma tions TrueFalse Description atomsSetConfig returns the list of modules registered to autoload Examples Display extrainformations atomsSetConfigVerboseTrue Disable autoload system atomsSetConfigautoloadFalse Authors Pierre MARECHAL DIGITEO 2348 Name atomsShow Show the caracteristics of a module atomsShowmodule Parameters module 1x1 or 1x2 Matrix of strings 1st Col Technical name Mandatory 2nd Col Version Optionnal If this field is empty or is not present the most recent version is used Description Show the caracteristics of a module Examples atomsRepositoryAddhttpscene1testatomsscilaborg atomsShowtoolbox5 See Also atomsList atomsDepTreeShow Authors Pierre MARECHAL DIGITEO 2349 Name atomsSystemUpdate Update the list of available modules atomsSystemUpdate Description atomsSystemUpdate update the list of available modules Examples atomsSystemUpdate Authors Pierre MARECHAL DIGITEO 2350 Name atomsUpdate Update one or several external modules result atomsUpdate result atomsUpdatenamesection Parameters name 1xn character string matrix modules technical name section This argument controls the list of sections where search modules to update section is a singlestring and its value should be all Modules to remove are searched in both user and allusers sections allusers Modules to remove are only searched in the allusers section user Modules to remove are only searched in the user section If SCI is write accessible all is the default value Otherwise the default value is user result Description atomsUpdate update one or more external modules Examples atomsSetConfigVerboseTrue atomsRepositoryAddhttpscene1testatomsscilaborg Install toolbox5 atomsInstalltoolbox5 dispatomsGetInstalled Load the 2nd scenario in which toolbox4 has been updated toolbox4 version 11 has been added toolbox4 is a dependency of toolbox5 atomsRepositoryDelhttpscene1testatomsscilaborg atomsRepositoryAddhttpscene2testatomsscilaborg Update toolbox5 atomsUpdatetoolbox5 dispatomsGetInstalled Some cleaning atomsUpdate 2351 atomsRepositoryDelhttpscene2testatomsscilaborg atomsRemovetoolbox5 See Also atomsInstall atomsRemove atomsGetInstalled Authors Pierre MARECHAL DIGITEO Parte LIV EntradaSaída de Arquivos Matlab Binários 2353 Name loadmatfile loads a Matlab V6 MATfile binary or ASCII into Scilab loadmatfileformatfilenamevar1var2 loadmatfilefilenameformatvar1var2 loadmatfilefilenamevar1var2format Parameters filename character string containing the path of the file needed format file format if not given and file has extension mat file is considered to be binary mat binary file ascii option to force Scilab to read file as an ASCII file var1 var2 character strings containing the name of the variables to load only for binary files Description loads a Matlab MATfile into Scilab The Matlab data types are converted into the Scilab equivalents Examples A rand1010 B sprand10010001 savematfiletestmatfilematABv6 clear loadmatfiletestmatfilemat dispA dispB See Also load savematfile save mfile2sci matfile2sci Authors Serge Steer INRIA VC Bibliography This function has been developped following the MATFile Format description MatFile Format httpwwwmathworkscomaccesshelpdeskhelppdfdocmat labmatfileformatpdf 2354 Name matfileclose Closes a Matlab V5 binary MATfile status matfileclosefd Parameters fd Real file descriptor returned by matfileopen status Boolean T if closure succeeds F otherwise Description Closes a Matlab binary MATfile opened by matfileopen See Also matfileopen matfilevarreadnext matfilevarwrite matfilelistvar Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2355 Name matfilelistvar Lists variables of a Matlab V5 binary MATfile names classes types matfilelistvarfd Parameters fd Real file descriptor returned by matfileopen names String vector names of the variables classes Real vector classes of the variables types Real vector data types of the variables Description Lists variables of a Matlab binary MATfile opened by matfileopen See Also matfileopen matfileclose matfilevarwrite matfilevarreadnext Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2356 Name matfileopen Opens a Matlab V5 binary MATfile fd matfileopenfilename mode Parameters filename String the path of the file Must contain only ANSI character mode String file access type r by default r opens the file for reading w opens the file for writing fd Real file descriptor 1 if opening failed Description Opens a Matlab binary MATfile for reading or writing data See Also matfileclose matfilevarreadnext matfilevarwrite matfilelistvar Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2357 Name matfilevarreadnext Reads next variable in a Matlab V5 binary MATfile name value vartype matfilevarreadnextfd Parameters fd Real file descriptor returned by matfileopen name String name of the variable read or if reading failed value Any Scilab type value of the variable read or an empty matrix if reading failed vartype Real type of the variable if reading succeeds or 0 if the variable type is unknown 1 if end of file has been reached Description Reads next variable in a Matlab binary MATfile opened by matfileopen See Also matfileopen matfileclose matfilevarwrite matfilelistvar Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2358 Name matfilevarwrite Write a variable in a Matlab V5 binary MATfile status matfilevarreadnextfd name value compressionflag Parameters fd Real file descriptor returned by matfileopen name String name of the variable to write in the file value Any Scilab type value of the variable to write in the file compressionflag Boolean indicate if data compression has to be used flag equaled to T or not status Boolean T if writing succeeds F otherwise Description Writes a variable in a Matlab binary MATfile opened by matfileopen See Also matfileopen matfileclose matfilevarreadnext matfilelistvar Authors VC Bibliography This function uses MATIO library httpsourceforgenetprojectsmatio 2359 Name savematfile write a Matlab MATfile binary or ASCII savematfilefilename savematfilefilename var1 var2 savematfilefilename struct s savematfilefilename struct s f1 f2 savematfile v4 savematfile v6 savematfile v7 savematfile v73 savematfile filename var1 var2 Parameters filename character string containing the path of the file needed format data format to use mat binary MATfile default ascii 8bit ASCII format ascii double 16bit ASCII format ascii tabs delimits with tabs ascii double tabs 16digit ASCII format tab delimited v4 A format that MATLAB Version 4 can open v6 A format that MATLAB Version 6 and earlier can open v7 A format that MATLAB Version 7 and earlier can open default v73 A format that MATLAB Version 73 and earlier can open var1 var2 character strings containing the name of the variables to load only for binary files struct s saves all fields of the scalar structure s as individual variables within the file filename struct s f1 f2 saves as individual variables only those structure fields specified sf1 sf2 savematfile 2360 Description saves variables in a Matlab MATfile from Scilab The Scilab data types are converted into the Matlab equivalents Examples A rand1010 B sprand10010001 savematfiletestmatfilematABv6 clear loadmatfiletestmatfilemat dispA dispB See Also load save loadmatfile mfile2sci Authors Serge Steer INRIA VC Bibliography This function has been developped following the MATFile Format description MatFile Format httpwwwmathworkscomaccesshelpdeskhelppdfdocmat labmatfileformatpdf Parte LV xcos 2362 Índice 6 Batch functions 2363 lincos 2364 scicos 2365 scicossimulate 2366 scicosim 2368 steadycos 2370 7 palettes 2372 1 Annotations palette 2372 2 Commonly used blocks palette 2375 3 Continuous time systems palette 2383 4 Demonstrations blocks palette 2408 5 Discontinuities palette 2425 6 Discrete time systems palette 2438 7 Electrical palette 2455 8 Event handling palette 2513 9 Implicit palette 2559 10 Integer palette 2564 11 Lookup tables palette 2595 12 Math operations palette 2602 13 Matrix operation palette 2649 14 Port Subsystem palette 2712 15 Signal processing palette 2719 16 Signal routing palette 2724 17 Sinks palette 2760 18 Sources palette 2815 19 Thermohydraulics palette 2868 20 User defined functions palette 2882 21 Zero crossing detection palette 2908 8 Programming xcos Blocks 2918 1 C Computational Functions 2918 2 Scilab Computational Functions 2932 3 Utilities Functions 2936 9 Scilab Data Structures 2947 1 Blocks 2947 2 CompilationSimulation 2958 3 Diagram 2966 4 Links 2971 10 Scilab Utilities Functions 2974 buildouttb 2975 createpalette 2976 getscicosversion 2977 scicosdebug 2978 var2vec 2979 vec2var 2980 Capítulo 6 Batch functions Batch functions 2364 Nome lincos Constructs by linearization a linear statespace model from a general dynamical system described by a xcos diagram sys lincosscsm x0u0 param Module xcos Description Construct a linear statespace system by linearizing a model given as a xcos diagram The output is a Scilab data structure of type continuoustime statespace linear system sys lincosscsm x0u0 param Parameters scsm a xcos data structure x0 column vector Continuous state around which linearization to be done default 0 u0 column vector Input around which linearization to be done default 0 param param list with two elements default list1d60 param1 scalar Perturbation level for linearization the following variation is used delxui param1param11d4absxui param2 scalar Time t sys statespace system File content SCImodulesscicosmacrosscicosautolincossci See Also steadycos Finds an equilibrium state of a general dynamical system described by a xcos diagram Scilab Function scicossimulate Function for running xcos simulation in batch mode Scilab Function Authors Ramine Nikoukhah INRIA Batch functions 2365 Nome scicos OBSOLETE see xcos scsm scicostoto Module xcos See Also xcos Batch functions 2366 Nome scicossimulate Function for running xcos simulation in batch mode InfoscicossimulatescsmInfoscicoscontextflag Module xcos Description This function is used to simulate xcos diagrams in batch mode It requires the scsm structure which can be obtained by loading in Scilab the cos file eg load mydiagramcos Contrary to the function the diagram need not be compiled before being saved InfoscicossimulatescsmInfoscicoscontextflag Parameters scsm xcos diagram obtained by load filecos Note that the version of filecos must be the current version If not load into xcos and save Info a list It must be list at the first call then use output Info as input Info for the next calls Info contains compilation and simulation information and is used to avoid recompilation when not needed scicoscontext a Scilab struct containing values of symbolic variables used in the context and xcos blocks This is often used to change a parameter in the diagram context In that case make sure that in the diagram context the variable is defined such that it can be modified Say a variable a is to be defined in the context having value 1 and later in batch mode we want to change the value of a In that case in the context of the diagram place if existsa then a1end If you want then to run the simulation in batch mode using the value a2 set scicoscontexta2 flag string If it equals nw no window then blocks using graphical windows are not executed Note that the list of such blocks must be updated as new blocks are added Info contains compilation and simulation information and is used to avoid recompilation when not needed Normally it should not be modified File content SCImodulesscicosmacrosscicosautoscicossimulatesci See Also scicosim Scicos batch simulation function Scilab Function xcos Block diagram editor and GUI for the hybrid simulator Scilab Function steadycos Finds an equilibrium state of a general dynamical system described by a xcos diagram Scilab Function Batch functions 2367 lincos Constructs by linearization a linear statespace model from a general dynamical system described by a xcos diagram Scilab Function Authors Ramine Nikoukhah INRIA Batch functions 2368 Nome scicosim xcos batch simulation function statet scicosimstatetcurtfsimstrtol Module xcos Description Simulator for xcos compiled diagram Usually scicosim is called by xcos to perform simulation of a diagram But scicosim may also be called outside xcos Typical usage in such a case may be For advanced user it is possible to manually change some parameters or state values statet scicosimstatetcurtfsimstrtol Parameters state Scilab tlist containing initial state Usually generated by xcos Compile After loading a com piled cos file it can be found in cprstate tcur starting time of simulation At the beginning it must be zero tf final simulation time sim Scilab tlist containing compilation results Usually generated by xcos Compile After loading a compiled cos file it can be found in cprsim str start run or finish Function must be first called with start then with run one or more times and finally with finish tol vector atolrtolttoldeltatrealtimescalesolverhmax where atol rtol are respectively the ab solute and relative tolerances for ode or dae solver ttol is the precision on event dates must be very small deltat is maximum integration interval for each call to ode solver sometimes needed to force restaring the call to solver realtimescale is the correspondance between simulation time and real time 0 means no slowing down solver is the choice of solver 0 lsodar 100 daskr hmax max step size used by solver Default 000011000E061000E1010000100 state state after simulation t final reached time Usually tf but not always See Also scicossimulate Function for running xcos simulation in batch mode Scilab Function xcos Block diagram editor and GUI for the hybrid simulator Scilab Function Batch functions 2369 Authors Ramine Nikoukhah INRIA Alan Layec INRIA Batch functions 2370 Nome steadycos Finds an equilibrium state of a general dynamical system described by a xcos diagram XUYXPsteadycosscsmXUYIndxInduIndy Indxp param Module xcos Description This function finds the steady state for a given system described by a xcos diagram The diagram consists in general of a Super block with input and output port blocks The steady state concern only the continuoustime dynamics XUYXPsteadycosscsmXUYIndxInduIndy Indxp param Parameters scsm a xcos data structure X column vector Continuous state Can be set to if zero U column vector Input Can be set to if zero Y column vector Output Can be set to if zero Indx index of entries of X that are not fixed If all can vary set to 1 Indu index of entries of U that are not fixed If all can vary set to 1 Indy index of entries of Y that are not fixed If all can vary set to 1 Indxp index of entries of XP derivative of x that need not be zero If all can vary set to 1 Default param list with two elements default list1d60 param1 scalar Perturbation level for line arization the following variation is used delxui param1param11d4absxui pa ram2 scalar Time t X steady state X U stationary input U Y output corresponding to steady state found XP derivative of the state corresponding to steady state found File content SCImodulesscicosmacrosscicosautosteadycossci See Also lincos Constructs by linearization a linear statespace model from a general dynamical system described by a xcos diagram Scilab Function Batch functions 2371 scicossimulate Function for running xcos simulation in batch mode Scilab Function xcos Block diagram editor and GUI for the hybrid simulator Scilab Function Authors Ramine Nikoukhah INRIA 2372 Capítulo 7 palettes 1 Annotations palette palettes 2373 Nome Annotationspal Annotations palette Block Screenshot Module xcos Description This palette includes blocks used for annotations Blocks TEXTf Text palettes 2374 Nome TEXTf Text Block Screenshot Contents Text Palette Description Dialog box Default properties Interfacing function Authors Palette Annotations palette Description This special block is only use to add text at any point of the diagram window It has no effect on the simulation Dialog box Text a character string Text to be displayed Properties Type str of size 1 Font number a positive integer less than 6 number of selected font seexset palettes 2375 Properties Type vec of size 1 Font size a positive integer selected font size seexset Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function text Interfacing function SCImodulesscicosblocksmacrosMiscTEXTfsci Authors Ramine Nikoukhah INRIA 2 Commonly used blocks palette palettes 2376 Nome Commonlyusedblockspal Commonly used blocks palette Block Screenshot Module xcos Description In the Commonly used blocks palette you can find blocks from other palettes that most models use Blocks ANDBLK Activation and BIGSOMf Sum CMSCOPE Multi display scope CONSTm Constant CONVERT CONVERT Data Type Conversion CSCOPXY yfx permanent viewer DEMUX Demultiplexer DOLLARf Delay operator INTEGRALf Integration palettes 2377 INf Input Port LOGICALOP Logical operation MUX Multiplexer NRMSOMf Merge data OUTf Output Port PRODUCT Product RELATIONALOP Relational operation SATURATION Saturation SWITCH2m Switch2 TEXTf Text palettes 2378 Nome LOGICALOP Logical operation Block Screenshot Contents Logical operation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Commonly used blocks palette Description The Logical Operator block performs the specified logical operation on its inputs An input value is TRUE 1 if it is nonzero and FALSE 0 if it is zero Dialog box number of inputs The number of block inputs The value must be appropriate for the selected operator Properties Type vec of size 1 Operator AND palettes 2379 The logical operator to be applied to the block inputs Valid choices are the operators from the list Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function logicalop Interfacing function SCImodulesscicosblocksmacrosMiscLOGICALOPsci Computational function SCImodulesscicosblockssrcclogicalopc SCImodulesscicosblockssrcclogicalopi32c SCImodulesscicosblockssrcclogicalopi16c SCImodulesscicosblockssrcclogicalopi8c SCImodulesscicosblockssrcclogicalopui32c SCImodulesscicosblockssrcclogicalopui16c SCImodulesscicosblockssrcclogicalopui8c Authors Fady NASSIF INRIA palettes 2380 Ramine Nikoukhah INRIA palettes 2381 Nome RELATIONALOP Relational operation Block Screenshot Contents Relational operation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Commonly used blocks palette Description It performs logical comparison of its two inputs Dialog box Operator Designate the relational operator used to compare the two inputs Properties Type vec of size 1 Use zero crossing palettes 2382 Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function relationalop Interfacing function SCImodulesscicosblocksmacrosMiscRELATIONALOPsci Computational function SCImodulesscicosblockssrccrelationalopc SCImodulesscicosblockssrccrelationalopi32c SCImodulesscicosblockssrccrelationalopi16c SCImodulesscicosblockssrccrelationalopi8c SCImodulesscicosblockssrccrelationalopui32c SCImodulesscicosblockssrccrelationalopui16c SCImodulesscicosblockssrccrelationalopui8c Authors Fady NASSIF INRIA palettes 2383 Ramine Nikoukhah INRIA 3 Continuous time systems palette palettes 2384 Nome Continuouspal Continuous time systems palette Block Screenshot Module xcos Description The Continuous time systems palette includes basic linear blocks Blocks CLINDUMMYf Dummy CLR Continuous transfer function CLSS Continuous statespace system DERIV Derivative INTEGRALf Integration INTEGRALm Integration PID PID regulator TCLSS Continuous linear system with jump TIMEDELAY Time delay VARIABLEDELAY Variable delay palettes 2385 Nome CLINDUMMYf Dummy Block Screenshot Contents Dummy Palette Description Default properties Interfacing function Authors Palette Continuous time systems palette Description This block should be placed in any block diagram that contains a zerocrossing block but no continuous system with state The reason for that is that it is the ode solver that find zero crossing surfaces Default properties always active yes directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function cdummy Interfacing function SCImodulesscicosblocksmacrosLinearCLINDUMMYfsci palettes 2386 Authors Ramine Nikoukhah INRIA palettes 2387 Nome CLR Continuous transfer function Block Screenshot Contents Continuous transfer function Palette Description Dialog box Default properties Interfacing function Computational function Palette Continuous time systems palette Description This block realizes a SISO linear system represented by its rational transfer function NumeratorDe nominator The rational function must be proper Dialog box Numerator This parameter sets the numerator of the transfer function This must be a polynomial in s Properties Type pol of size 1 Denominator palettes 2388 This parameter sets the denominator of the transfer function This must be a polynomial in s Properties Type pol of size 1 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function csslti4 Interfacing function SCImodulesscicosblocksmacrosLinearCLRsci Computational function SCImodulesscicosblockssrcccsslti4c Type 4 palettes 2389 Nome CLSS Continuous statespace system Block Screenshot Contents Continuous statespace system Palette Description Dialog box Default properties Interfacing function Computational function Palette Continuous time systems palette Description This block realizes a continuoustime linear statespace system The system is defined by the matrices and the initial state The dimen sions must be compatible palettes 2390 Dialog box matrix A square matrix Properties Type mat of size 11 B matrix The matrix if system has no input Properties Type mat of size size121 C matrix The matrix if system has no output Properties Type mat of size 1size12 D matrix The matrix if system has no D term Properties Type mat of size 11 Initial state A vectorscalar initial state of the system Properties Type vec of size size12 Default properties always active yes directfeedthrough no zerocrossing no mode no palettes 2391 regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function csslti4 Interfacing function SCImodulesscicosblocksmacrosLinearCLSSsci Computational function SCImodulesscicosblockssrcccsslti4c Type 4 palettes 2392 Nome DERIV Derivative Block Screenshot Contents Derivative Palette Description Default properties Interfacing function Computational function Authors Palette Continuous time systems palette Description The Derivative block approximates the derivative of its input by computing Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 palettes 2393 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function deriv Interfacing function SCImodulesscicosblocksmacrosLinearDERIVsci Computational function SCImodulesscicosblockssrccderivc Type 4 Authors Ramine Nikoukhah INRIA palettes 2394 Nome INTEGRALf Integration Block Screenshot Contents Integration Palette Description Dialog box Default properties Interfacing function Computational function Palette Continuous time systems palette Description This block is an integrator The output is the integral of the input Dialog box Initial Condition A scalar that gives the initial condition Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing no palettes 2395 mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function integr Interfacing function SCImodulesscicosblocksmacrosLinearINTEGRALfsci Computational function SCImodulesscicosblockssrcfortranintegrf Type 0 palettes 2396 Nome INTEGRALm Integration Block Screenshot Contents Integration Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Continuous time systems palette Description This block is an integrator The output is the integral of the input Dialog box Initial Condition A vectorscalar initial conditions palettes 2397 With that parameter one can define the datatype of the inputoutput It can be a real or a complex type Properties Type mat of size 11 With reinitialization To reset its state to the specified initial condition based on an external signal select1 Properties Type vec of size 1 With saturation If selected limits the states to a value between the Lower saturation limit and Upper saturation limit parameters Properties Type vec of size 1 Upper limit The upper limit for the integral Properties Type mat of size 11 Lower limit The lower limit for the integral Properties Type mat of size 11 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function integralfunc Interfacing function SCImodulesscicosblocksmacrosLinearINTEGRALmsci palettes 2398 Computational function SCImodulesscicosblockssrccintegralfuncc SCImodulesscicosblockssrccintegralzfuncc Authors Fady NASSIF INRIA Alan Layec INRIA Ramine Nikoukhah INRIA palettes 2399 Nome PID PID regulator Block Screenshot Contents PID regulator Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Authors Palette Continuous time systems palette Description This block implements a PID controller The PID controller calculation algorithm involves three se parate parameters the Proportional the Integral and Derivative values The Proportional value deter mines the reaction to the current error the Integral determines the reaction based on the sum of recent errors and the Derivative determines the reaction to the rate at which the error has been changing The weighted sum of these three actions is used to adjust the process via a control element such as the position of a control valve or the power supply of a heating element Dialog box palettes 2400 Proportional The value of the gain that multiply the error Properties Type vec of size 1 Integral The value of the integral time of the error1Integral Properties Type vec of size 1 Derivation The value of the derivative time of the error Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosLinearPIDsci palettes 2401 Compiled Super Block content Authors Fady NASSIF INRIA palettes 2402 Nome TCLSS Continuous linear system with jump Block Screenshot Contents Continuous linear system with jump Palette Description Dialog box Default properties Interfacing function Computational function Palette Continuous time systems palette Description This block realizes a continuoustime linear statespace system with the possibility of jumps in the state The number of inputs to this block is two The first input is the regular input of the linear system the second carries the new value of the state which is copied into the state when an event arrives at the unique event input port of this block That means the state of the system jumps to the value present on the second input of size equal to that of the state The system is defined by the matrices and the initial state The dimensions must be compatible The sizes of inputs and outputs are adjusted automatically Dialog box palettes 2403 matrix A square matrix Properties Type mat of size 11 B matrix The matrix if system has no input Properties Type mat of size size121 C matrix The matrix if system has no output Properties Type mat of size 1size12 D matrix The matrix if system has no D term Properties Type mat of size 11 Initial state A vectorscalar initial state of the system Properties Type vec of size size12 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no palettes 2404 name of computational function tcslti4 Interfacing function SCImodulesscicosblocksmacrosLinearTCLSSsci Computational function SCImodulesscicosblockssrcctcslti4c Type 4 palettes 2405 Nome TIMEDELAY Time delay Block Screenshot Contents Time delay Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Continuous time systems palette Description The Transport Delay block delays the input by a specified amount of time It can be used to simulate a time delay At the start of the simulation the block outputs the Initial input parameter until the simulation time exceeds the Time delay parameter when the block begins generating the delayed input The Time delay parameter must be nonnegative Dialog box Delay The amount of simulation time that the input signal is delayed before being propagated to the output The value must be nonnegative palettes 2406 Properties Type vec of size 1 initial input The output generated by the block between the start of the simulation and the Time delay Properties Type vec of size 1 Buffer size The initial memory allocation for the number of points to store Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function timedelay Interfacing function SCImodulesscicosblocksmacrosLinearTIMEDELAYsci Computational function SCImodulesscicosblockssrcctimedelayc Type 4 Authors Ramine Nikoukhah INRIA palettes 2407 Nome VARIABLEDELAY Variable delay Block Screenshot Contents Variable delay Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Continuous time systems palette Description The Variable Transport Delay block can be used to simulate a variable time delay The block might be used to model a system with a pipe where the speed of a motor pumping fluid in the pipe is variable The block accepts two inputs the first input is the signal that passes through the block the second input is the time delay Dialog box Max delay It defines the largest value the time delay input can haveThe value cannot be negative palettes 2408 Properties Type vec of size 1 initial input The output generated by the block until the simulation time first exceeds the time delay input Properties Type vec of size 1 Buffer size The number of points the block can store Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function variabledelay Interfacing function SCImodulesscicosblocksmacrosLinearVARIABLEDELAYsci Computational function SCImodulesscicosblockssrccvariabledelayc Type 4 Authors Ramine Nikoukhah INRIA 4 Demonstrations blocks palette palettes 2409 Nome Demonstrationsblockspal Demonstrations blocks palette Block Screenshot Module xcos Description The Demonstrations blocks palette contains blocks used in some Xcos demonstration diagrams Blocks AUTOMAT hybrid automata BOUNCE Balls coordinates generator BOUNCEXY Balls viewer BPLATFORM Balls under a platform viewer PDE 1D PDE block palettes 2410 Nome AUTOMAT automata finite state machine Block Screenshot Contents automata finite state machine Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Demonstrations blocks palette Description This block gives the possibility to construct hybrid automata ie a hybrid system whose discrete part is defined via modes and transitions between modes and the continuous part is defined via DAE differential algebraic equations The automaton block provides a switching mechanism between subsystems corresponding to control modes of an automaton Subsystems are constructed in such a way that they have the state vector as input coming from the automaton block and compute the flow and jump functions zerocrossing and pass them back to the automaton block The state variables are defined in the automaton block and the subsystems are static functions Suppose that a hybrid automaton consists of control modes The continuoustime dynamics in mode is defined with DAE where and the dimension of is for any Suppose that in control mode there are jump conditions indicating jumps toward other modes The jump conditions are defined by functions where When a jump function changes sign and becomes positive a mode transition will happen When tran sition function becomes positive a transition to mode happens and state vector is reset to for In order to develop an automaton containing a mode with multiple reset functions the value of the current and previous active modes should be used These values are available at the first output port of the block The automaton block has the following inputoutput ports palettes 2411 Output 1 The first output port is a vector of size two con sisting of the current and the previous active control modes ie Output 2 The second output port is a vector of size providing the state vector and its first time derivative Inputs The automaton block has vector input ports corresponding to modes or subsys tems of the automaton Each input defines the dynamic behavior in the control each mode as well as the reset functions and the transition functions The input port which is the output of the subsystem is a vector of size Each input is composed of the following vector The first elements of the are the continuoustime dynamics The dy namics of the system in the control mode is described by a smooth index1 DAE The next elements of are the values used to reset the continuoustime state when a transition to control mode is activated The next elements of are the jump or zerocrossing functions If the zerocrossing function of mode crosses zero with negative to positive direction a transition to destination mode happens Event Output This is an event output port which is activated whenever a mode transition happens This event is useful when an event is needed to activate or initialize a part of the subsystem not included in the internal dynamics of the automaton block In the interface window the number of control modes the initial control mode and the initial value of continuoustime state at the beginning of the simulation should be given Find more documentation and demos about the Automaton block oat wwwscicosorg Interested users are referred to the paper Modeling Hybrid Automata in Scicos Masoud Najafi Ramine Nikoukhah 2007 IEEE Multiconference on Systems and Control Singapore palettes 2412 Dialog box Number of finitestate Modes Number of modes in the automation Properties Type vec of size 11 Initial Mode Initial active mode at the beginning of the simulation Properties Type vec of size 11 Number of continuoustime states Number of continuoustime states at modes Note that the num ber of continuoustime states is the same in all modes Properties Type vec of size 11 Continuoustime states initial values Initial value of continuoustime states at the beginning of the simulation Properties Type vec of size 11 Xproperties of continuoustime states in each Mode In this field the state types in mode are given A state in an index 1 DAE can be either differential state or algebraic state vector is coded in an MN matrix where M is the number of modes and N is the number of states This matrices indicates whether a continuoustime state is algebraic or differential in each control mode If in the mode state is differential the ijth element of the Xproperty matrix should set to 1 otherwise it should set to 1 Xproperty can be given as a 1N vector if type of states remain the same in all modes Properties Type mat of size 11 Jump from Mode 1MfinalGuardIn1i palettes 2413 The fields express the mode transition information Suppose that all control modes are labeled from 1 to M Then in the field corresponding to control modei destination modes of modei are defined in a vectorjth element of this vector gives the destination mode whenjth jump function becomes positive For example if in the field of the mode2 the user defines 134 it means that in mode2 there are three active jump functions When for example the third jump function becomes positive a mode transition to mode4 will be activated Properties Type vec of size 11 Default properties always active yes directfeedthrough no zerocrossing yes mode no regular inputs port 1 size 31 type 1 port 2 size 31 type 1 regular outputs port 1 size 21 type 1 port 2 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state yes discretetime state no object discretetime state no name of computational function automat Interfacing function SCImodulesscicosblocksmacrosMiscAUTOMATsci Computational function SCImodulesscicosblockssrccautomatc Type 10004 Authors Masoud Najafi INRIA palettes 2414 Nome BOUNCE Balls coordinates generator Block Screenshot Contents Balls coordinates generator Palette Dialog box Default properties Interfacing function Computational function Palette Demonstrations blocks palette Dialog box palettes 2415 Mass The parameter description 1 Properties Type vec of size 1 Radius The parameter description 2 Properties Type vec of size 1 xminxmaxyminymax The parameter description 3 Properties Type vec of size 1 xpos The parameter description 4 Properties Type vec of size 1 xdpos The parameter description 5 Properties Type vec of size 1 ypos The parameter description 6 Properties Type vec of size 1 ydpos The parameter description 7 Properties Type vec of size 1 g gravity The parameter description 8 Properties Type vec of size 1 C aerodynamic coeff The parameter description 9 Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing yes mode no palettes 2416 regular outputs port 1 size 21 type 1 port 2 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function bounceball Interfacing function SCImodulesscicosblocksmacrosMiscBOUNCEsci Computational function SCImodulesscicosblockssrccbounceballc Type 4 palettes 2417 Nome BOUNCEXY Balls viewer Block Screenshot Contents Balls viewer Palette Dialog box Default properties Interfacing function Computational function Authors Palette Demonstrations blocks palette Dialog box colors palettes 2418 The parameter description 1 Properties Type vec of size 1 radii The parameter description 2 Properties Type vec of size 1 window number 1 for automatic The parameter description 3 Properties Type vec of size 1 animation mode 01 The parameter description 4 Properties Type vec of size 1 Xmin The parameter description 5 Properties Type vec of size 1 Xmax The parameter description 6 Properties Type vec of size 1 Ymin The parameter description 7 Properties Type vec of size 1 Ymax The parameter description 8 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 palettes 2419 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function bouncexy Interfacing function SCImodulesscicosblocksmacrosMiscBOUNCEXYsci Computational function SCImodulesscicosblockssrccbouncexyc Type 4 Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2420 Nome BPLATFORM Balls under a platform viewer Block Screenshot Contents Balls under a platform viewer Palette Dialog box Default properties Interfacing function Authors Palette Demonstrations blocks palette Dialog box Default properties always active no directfeedthrough no zerocrossing no mode no palettes 2421 regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function bplatform2 Interfacing function SCImodulesscicosblocksmacrosMiscBPLATFORMsci Authors M Najafi INRIA palettes 2422 Nome PDE 1D PDE block Block Screenshot Contents 1D PDE block Palette Description Dialog box Default properties Interfacing function Authors Palette Demonstrations blocks palette Description This block is an implementation of several numerical schemes Finite Elements 1st and 2nd order Finite Differences 1st and 2nd order Finite Volumes 1st order to solve mono dimensional PDE Partial Differential Equation within SCICOS The mathematical framwork was restricts in PDEs linear scalars with maximum order 2 in time and space The goal is to provide engineers and physicists with an easy to use toolbox in SCICOS that will let them graphically describe the PDE to be solved A decision system selects the most efficient numerical scheme depending on the type of the PDE and runs the solvers palettes 2423 Dialog box a et b double The two edges of the discretization field specification de lEDP check box to select the PDE operators aix bit i17 are the operator coefficients type of PDE discriminant constant or variable in the later case the sign should be given Discretization methode choix check box is the choice for the manual or the automatic mode type in the manual mode we can give the method type Finite differences finite elements or finite volumes degré method degre 1 or 2 for the FD and FE methods 1 for the FV method Nombre de noeuds to give the number of the nodal points palettes 2424 Conditions initiales uxt0 dudt at t0 to give the initial conditions Conditions aux limites type two type of the boundray conditions are possible Dirichlet or Neumann expressions to give then boundray conditions expressions Points de mesures To give the list of mesurment points Name A getvalue box to give the block names Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 0 port 3 size 11 type 0 port 4 size 11 type 0 port 5 size 11 type 1 regular outputs port 1 size 101 type 1 port 2 size 01 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function PDE Interfacing function SCImodulesscicosblocksmacrosPDEPDEsci Authors EADS 20050116 palettes 2425 EADS 20050116 5 Discontinuities palette palettes 2426 Nome discontinuitiespal discontinuities palette Block Screenshot Module xcos Description discontinuities palette includes blocks whose outputs are discontinuities functions of their inputs Blocks BACKLASH Backlash DEADBAND Deadband DELAYVf Variable time delay HYSTHERESIS Hystheresis RATELIMITER Rate limiter QUANTf Quatization SATURATION Saturation palettes 2427 Nome BACKLASH Backlash Block Screenshot Contents Backlash Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description The Backlash block implements a system in which a change in input causes an equal change in output However when the input changes direction an initial change in input has no effect on the output The amount of sidetoside play in the system is referred to as the Dialog box initial output The initial output value Properties Type vec of size 1 palettes 2428 gap The width of the deadband Properties Type vec of size 1 use zerocrossing Select to enable use of zero crossing detection to detect engagement with lower and upper th resholds Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function backlash Interfacing function SCImodulesscicosblocksmacrosMiscBACKLASHsci Computational function SCImodulesscicosblockssrccbacklashc Type 4 Authors Ramine Nikoukhah INRIA palettes 2429 Nome DEADBAND Deadband Block Screenshot Contents Deadband Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description Provide a region of zero output Dialog box End of dead band The upper limit of the dead band Properties Type vec of size 1 Start of dead band palettes 2430 The lower limit of the dead band Properties Type vec of size 1 zero crossing Select to enable zero crossing detection to detect when the limits are reached Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function deadband Interfacing function SCImodulesscicosblocksmacrosMiscDEADBANDsci Computational function SCImodulesscicosblockssrccdeadbandc Type 4 Authors Ramine Nikoukhah INRIA palettes 2431 Nome HYSTHERESIS Hystheresis Block Screenshot Contents Hystheresis Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description Switch output between two constantsThe Relay block allows its output to switch between two speci fied values When the relay is on it remains on until the input drops below the value of the Switch off point parameter When the relay is off it remains off until the input exceeds the value of the Switch on point parameter The block accepts one input and generates one output Dialog box palettes 2432 switch on at The Switch on point parameter is converted to the input data type offline using roundtonearest and saturation Properties Type vec of size 1 switch off at The Switch off point parameter is converted to the input data type offline using roundtonearest and saturation Properties Type vec of size 1 output when on The output when the relay is on Properties Type vec of size 1 output when off The output when the relay is off Properties Type vec of size 1 use zero crossing yes Select to enable zero crossing detection to detect switchon and switchoff points Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function hystheresis palettes 2433 Interfacing function SCImodulesscicosblocksmacrosMiscHYSTHERESISsci Computational function SCImodulesscicosblockssrcchystheresisc Type 4 Authors Ramine Nikoukhah INRIA palettes 2434 Nome RATELIMITER Rate limiter Block Screenshot Contents Rate limiter Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description The Rate Limiter block limits the first derivative of the signal passing through it The output changes no faster than the specified limit Dialog box max slope The limit of the derivative of an increasing input signal Properties Type vec of size 1 min slope palettes 2435 The limit of the derivative of a decreasing input signal Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function ratelimiter Interfacing function SCImodulesscicosblocksmacrosMiscRATELIMITERsci Computational function SCImodulesscicosblockssrccratelimiterc Type 4 Authors Ramine Nikoukhah INRIA palettes 2436 Nome SATURATION Saturation Block Screenshot Contents Saturation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette discontinuities palette Description The Saturation block imposes upper and lower bounds on a signal When the input signal is within the range specified by the Lower limit and Upper limit parameters the input signal passes through unchanged When the input signal is outside these bounds the signal is clipped to the upper or lower bound When the Lower limit and Upper limit parameters are set to the same value the block outputs that value Dialog box Upper limit palettes 2437 Specify the upper bound on the input signal When the input signal to the Saturation block is above this value the output of the block is clipped to this value Properties Type vec of size 1 Lower limit Specify the lower bound on the input signal When the input signal to the Saturation block is below this value the output of the block is clipped to this value Properties Type vec of size 1 zero crossing Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function satur Interfacing function SCImodulesscicosblocksmacrosNonLinearSATURATIONsci Computational function SCImodulesscicosblockssrccsaturc Type 4 Authors Ramine Nikoukhah INRIA palettes 2438 6 Discrete time systems palette palettes 2439 Nome Discretepal Discrete time systems palette Block Screenshot Module xcos Description The Discrete time systems palette contains blocks for medeling discrete time systems Blocks DELAYf Discrete time delay DELAYVf Variable delay DLR Discrete transfer function DLRADAPTf Discrete ZeroPole function DLSS Discrete statespace system DOLLARf Delay operator REGISTER Shift Register SAMPHOLDm Sample and hold TCLSS Continuous linear system with jump palettes 2440 Nome DELAYVf Variable delay Block Screenshot Contents Variable delay Palette Description Dialog box Default properties Interfacing function Computational function Palette Discrete time systems palette Description Add here a paragraph of the function description Dialog box Number of inputs Set the vector size of the first regular input and the vector size of the regular output port Properties Type vec of size 1 palettes 2441 Register initial condition Set the length and the initial conditions of the register Properties Type vec of size 1 Max delay It defines the largest value the time delay input can haveThe value cannot be negative Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 2 continuoustime state no discretetime state yes object discretetime state no name of computational function delayv Interfacing function SCImodulesscicosblocksmacrosLinearDELAYVfsci Computational function SCImodulesscicosblockssrcfortrandelayvf Type 1 palettes 2442 Nome DELAYf Discrete time delay Block Screenshot Contents Discrete time delay Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Palette Discrete time systems palette Description This compiled superblock implements a discretized delay It is build with a shift register and a clock The value of the delay is given by the discretization time step multiplied by the number1 of state of the register Dialog box Discretization time step Set the time period of the integrated clock palettes 2443 Properties Type vec of size 1 Register initial state Set the length and the initial conditions of the register Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosLinearDELAYfsci Compiled Super Block content palettes 2444 Nome DLR Discrete transfer function Block Screenshot Contents Discrete transfer function Palette Description Dialog box Default properties Interfacing function Computational function Palette Discrete time systems palette Description This block realizes a SISO linear system represented by its rational transfer function in the symbolic variable z The rational function must be proper Dialog box Numerator z This parameter sets the numerator of the transfer function This must be a polynomial inz Properties Type pol of size 1 Denominator z palettes 2445 This parameter sets the denominator of the transfer function This must be a polynomial inz Properties Type pol of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function dsslti4 Interfacing function SCImodulesscicosblocksmacrosLinearDLRsci Computational function SCImodulesscicosblockssrccdsslti4c Type 4 palettes 2446 Nome DLRADAPTf Discrete ZeroPole Block Screenshot Contents Discrete ZeroPole Palette Description Dialog box Default properties Interfacing function Computational function Palette Discrete time systems palette Description This block models system represented by zeros and poles of discrete transfer function Dialog box Vector of p mesh points The parameter description 1 palettes 2447 Properties Type vec of size 1 Numerator roots one line for each mesh The parameter description 2 Properties Type mat of size 11 Denominator roots one line for each mesh The parameter description 3 Properties Type mat of size size11 Vector of gain at mesh points The parameter description 4 Properties Type vec of size size1 past inputs Num degree values The parameter description 5 Properties Type vec of size size22 past outputs Den degree values The parameter description 6 Properties Type vec of size size32 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no palettes 2448 name of computational function dlradp Interfacing function SCImodulesscicosblocksmacrosNonLinearDLRADAPTfsci Computational function SCImodulesscicosblockssrcfortrandlradpf Type 0 palettes 2449 Nome DLSS Discrete statespace system Block Screenshot Contents Discrete statespace system Palette Description Dialog box Default properties Interfacing function Computational function Palette Discrete time systems palette Description This block realizes a discretetime linear statespace system The system is defined by the matrices and the initial state The dimensions must be compatible At the arrival of an input event on the unique input event port the state is updated Dialog box matrix palettes 2450 A square matrix Properties Type mat of size 11 B matrix The matrix if system has no input Properties Type mat of size size121 C matrix The matrix if system has no output Properties Type mat of size 1size12 D matrix The matrix if system has no D term Properties Type mat of size 11 Initial state A vectorscalar initial state of the system Properties Type vec of size size12 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function dsslti4 Interfacing function SCImodulesscicosblocksmacrosLinearDLSSsci palettes 2451 Computational function SCImodulesscicosblockssrccdsslti4c Type 4 palettes 2452 Nome DOLLARf Delay operator Block Screenshot Contents Delay operator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Discrete time systems palette Description The Unit Delay block delays its input by the specified sample period This block is equivalent to the z1 discretetime operator The block accepts one input and generates one output which can be either both scalar or both vector If the input is a vector all elements of the vector are delayed by the same sample period Dialog box initial condition The output of the simulation for the first sampling period during which the output of the Unit Delay block is otherwise undefined Properties Type vec of size 1 palettes 2453 Inherit no0 yes1 When Inherit is yes the block inherit its event input Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function dollar Interfacing function SCImodulesscicosblocksmacrosLinearDOLLARfsci Computational function SCImodulesscicosblockssrcfortrandollarf Type 0 Authors Ramine Nikoukhah INRIA palettes 2454 Nome REGISTER Shift Register Block Screenshot Contents Shift Register Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Discrete time systems palette Description This block realizes a shift register At every input event the register is shifted one step Dialog box Register initial condition A column vector It contains the initial state of the register Properties Type vec of size 1 Datatype This block support all datatypes besides complex palettes 2455 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function delay4 Interfacing function SCImodulesscicosblocksmacrosLinearREGISTERsci Computational function SCImodulesscicosblockssrccdelay4i32c SCImodulesscicosblockssrccdelay4i16c SCImodulesscicosblockssrccdelay4i8c SCImodulesscicosblockssrccdelay4ui32c SCImodulesscicosblockssrccdelay4ui16c SCImodulesscicosblockssrccdelay4ui8c Authors Fady NASSIF INRIA 7 Electrical palette palettes 2456 Nome Electricalpal Electrical palette Block Screenshot Module xcos Description Electrical toolbox contains very basic electrical components such as voltage source diode capacitor etc Blocks Capacitor Electrical capacitor CCS Controllable Modelica current source ConstantVoltage Electrical DC voltage source CurrentSensor Electrical current sensor CVS Controllable Modelica voltage source Diode Electrical diode Ground Ground zero potential reference Gyrator Modelica Gyrator IdealTransformer Ideal Transformer palettes 2457 Inductor Electrical inductor NMOS Simple NMOS Transistor NPN NPN transistor OpAmp Ideal opamp noratornullator pair PMOS Simple PMOS Transistor PNP PNP transistor PotentialSensor Potential sensor Resistor Electrical resistor SineVoltage Sine voltage source Switch Nonideal electrical switch VariableResistor Electrical variable resistor VoltageSensor Electrical voltage sensor VsourceAC Electrical AC voltage source VVsourceAC Variable AC voltage source palettes 2458 Nome CCS Controllable Modelica current source Block Screenshot Contents Controllable Modelica current source Palette Description Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description This block is an ideal current source The current value is controlled through the explicit input of the block connected to standard Xcos blocks The voltage across the block is independent of the current value Default properties Inputs Modelica variable name Iin Explicit variable Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable File name of the model CCS palettes 2459 Interfacing function SCImodulesscicosblocksmacrosElectricalCCSsci Modelica model SCImodulesscicosblocksmacrosElectricalCCSmo See also CVS Controllable Modelica voltage source Authors Masoud Najafi INRIA palettes 2460 Nome CVS Controllable Modelica voltage source Block Screenshot Contents Controllable Modelica voltage source Palette Description Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description This block is an ideal voltage source The voltage value is controlled through the explicit input of the block connected to standard Xcos blocks The current passing through the block is independent of the voltage across the block terminals Default properties Inputs Modelica variable name vin Explicit variable Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable File name of the model CVS palettes 2461 Interfacing function SCImodulesscicosblocksmacrosElectricalCVSsci Modelica model SCImodulesscicosblocksmacrosElectricalCVSmo See also CCS Controllable Modelica current source Authors Masoud Najafi INRIA palettes 2462 Nome Capacitor Electrical capacitor Block Screenshot Contents Electrical capacitor Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description A capacitor is an electrical component that can store energy in electrical circuits The relationship between the voltage across a capacitor with capacitance and the current passing through it is given by the Capacitors can also be used to differentiate between highfrequency and lowfrequency signals and this makes them useful in electronic filters A capacitor has a high impedance when a signal is low frequency signals Dialog box palettes 2463 C F Capacitance Properties Type vec of size 1 Initial Voltage Initial Voltage Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name C Default value 001 Is a state variable no Modelica parameter name v Default value 0 Is a state variable yes File name of the model Capacitor Interfacing function SCImodulesscicosblocksmacrosElectricalCapacitorsci Modelica model SCImodulesscicosblocksmacrosElectricalCapacitormo palettes 2464 Nome ConstantVoltage Electrical DC voltage source Block Screenshot Contents Electrical DC voltage source Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component is a model for any device or system that produces a constant electromotive force between its port The output voltage of this DC voltage source is defined by the user The black port indicates the positive voltage The ohmic resistance of this DC voltage source is zero Dialog box V volt Output voltage Properties Type vec of size 1 Default properties Inputs palettes 2465 Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name V Default value 001 Is a state variable no File name of the model ConstantVoltage Interfacing function SCImodulesscicosblocksmacrosElectricalConstantVoltagesci Modelica model SCImodulesscicosblocksmacrosElectricalConstantVoltagemo palettes 2466 Nome CurrentSensor Electrical current sensor Block Screenshot Contents Electrical current sensor Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This block is inserted in series in an electrical circuit to measure the current passing through the com ponent The measure is given to the explicit part of the model via an explicit pout Conventionally current flowing into the black port is considered positive The ohmic resistance of this block is zero Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Modelica variable name i Explicit variable File name of the model CurrentSensor Interfacing function SCImodulesscicosblocksmacrosElectricalCurrentSensorsci Modelica model SCImodulesscicosblocksmacrosElectricalCurrentSensormo palettes 2467 Nome Diode Electrical diode Block Screenshot Contents Electrical diode Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component consists of a simple diode parallel with an ohmic resistance The current passing through this component is defined as a function of the voltage across the ports where and are the saturation current and the voltage equivalent of temperature respectively If the exponent reaches a certain limit the diode characteristic becomes linear to avoid overflow Dialog box palettes 2468 Saturation current A Saturation current Properties Type vec of size 1 Voltage equivalent to temperature Volt Voltage equivalent of temperature Properties Type vec of size 1 Max exponent for linear continuation Max exponent for linear continuation Properties Type vec of size 1 R ohm Parallel ohmic resistance Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name Ids Default value 0000001 Is a state variable no Modelica parameter name Vt Default value 004 Is a state variable no Modelica parameter name Maxexp Default value 15 Is a state variable no Modelica parameter name R Default value 1000E08 palettes 2469 Is a state variable no File name of the model Diode Interfacing function SCImodulesscicosblocksmacrosElectricalDiodesci Modelica model SCImodulesscicosblocksmacrosElectricalDiodemo palettes 2470 Nome Ground Ground zero potential reference Block Screenshot Contents Ground zero potential reference Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description The Ground element is a single port component providing a reference voltage in electrical circuits The potential at the ground node is zero Every electrical circuit has to contain at least one ground element Default properties Inputs Modelica variable name p Implicit variable File name of the model Ground Interfacing function SCImodulesscicosblocksmacrosElectricalGroundsci Modelica model SCImodulesscicosblocksmacrosElectricalGroundmo palettes 2471 Nome Gyrator Modelica Gyrator Block Screenshot Contents Modelica Gyrator Palette Description Dialog box Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description A gyrator is a twoport element defined by the following equations i1 G2 v2 i2 G1 v1 where the constants G1 G2 are called the gyration conductance Dialog box G1 Gyration conductance i2v1 palettes 2472 Properties Type vec of size 1 G2 Gyration conductance i1v2 Properties Type vec of size 1 Default properties Inputs Modelica variable name p1 Implicit variable Modelica variable name n1 Implicit variable Modelica variable name p2 Implicit variable Modelica variable name n2 Implicit variable Parameters Modelica parameter name G1 Default value 1 Is a state variable no Modelica parameter name G2 Default value 1 Is a state variable no File name of the model Gyrator Interfacing function SCImodulesscicosblocksmacrosElectricalGyratorsci Modelica model SCImodulesscicosblocksmacrosElectricalGyratormo Authors Masoud Najafi INRIA palettes 2473 Nome IdealTransformer Ideal Transformer Block Screenshot Contents Ideal Transformer Palette Description Dialog box Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description The ideal transformer is an ideal twoport resistive circuit element which is characterized by the fol lowing two equations v1 n v2 i2 n i1 where n is a real number called the turns ratio Dialog box N Turns ratio N1N2 Properties Type vec of size 1 palettes 2474 Default properties Inputs Modelica variable name p1 Implicit variable Modelica variable name n1 Implicit variable Modelica variable name p2 Implicit variable Modelica variable name n2 Implicit variable Parameters Modelica parameter name N Default value 1 Is a state variable no File name of the model IdealTransformer Interfacing function SCImodulesscicosblocksmacrosElectricalIdealTransformersci Modelica model SCImodulesscicosblocksmacrosElectricalIdealTransformermo Authors Masoud Najafi INRIA palettes 2475 Nome Inductor Electrical inductor Block Screenshot Contents Electrical inductor Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description Inductor is an electrical component that can store energy in electrical circuits The relationship between the voltage across the ports of an inductor of inductance and the current passing through it is given by Inductors can also be used to differentiate between highfrequency and lowfrequency signals and this makes them useful in electronic filters An inductor shows a high impedance for high frequency signals Dialog box palettes 2476 L H Inductance Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name L Default value 000001 Is a state variable no File name of the model Inductor Interfacing function SCImodulesscicosblocksmacrosElectricalInductorsci Modelica model SCImodulesscicosblocksmacrosElectricalInductormo palettes 2477 Nome NMOS Simple NMOS Transistor Block Screenshot Contents Simple NMOS Transistor Palette Description Dialog box Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description Description The NMos model is a simple model of a nchannel metaloxide semiconductor FET It differs slightly from the device used in the SPICE simulator For more details please care for H Spiro The model does not consider capacitances A small fixed drainsource resistance is included to avoid numerical difficulties W m L m Beta 1 V² Vt V K2 K5 DW m DLm 12e6 4e6 062 45 24 61 12e6 9e6 depletion 60e6 3e6 048 1 08 68 12e6 9e6 enhance ment 12e6 4e6 0625 8 21 78 12e6 9e6 zero 50e6 8e6 0299 24 1144 7311 54e6 4e6 20e6 6e6 041 8 1144 7311 25e6 15e6 30e6 9e6 025 4 861 878 34e6 174e6 30e6 5e6 031 6 15 72 0 39e6 palettes 2478 50e6 6e6 0414 38 34 8 16e6 2e6 depletion 50e6 5e6 03 37 23 86 16e6 2e6 enhance ment 50e6 6e6 038 9 23 707 16e6 2e6 zero 20e6 4e6 06776 5409 065 71 8e6 2e6 20e6 4e6 06505 6209 065 71 8e6 2e6 20e6 4e6 05365 6909 03 8 3e6 2e6 20e6 4e6 05365 4909 03 8 3e6 2e6 12e6 4e6 023 45 29 6 0 0 depletion 60e6 3e6 022 1 11 65 0 0 enhance ment 12e6 4e6 038 8 33 6 0 0 zero 20e6 6e6 022 8 1 66 0 0 Dialog box Width m W Properties Type vec of size 1 Length m L Properties Type vec of size 1 Transconductance parameter AVV Beta palettes 2479 Properties Type vec of size 1 Zero bias threshold voltage V Vt Properties Type vec of size 1 Bulk threshold parameter K2 Properties Type vec of size 1 Reduction of pinchoff region K5 Properties Type vec of size 1 Narrowing of channel m dW Properties Type vec of size 1 Shortening of channel m dL Properties Type vec of size 1 DrainSourceResistance Ohm RDS Properties Type vec of size 1 Default properties Inputs Modelica variable name G Implicit variable Outputs Modelica variable name D Implicit variable Modelica variable name B Implicit variable Modelica variable name S Implicit variable Parameters Modelica parameter name W palettes 2480 Default value 000002 Is a state variable no Modelica parameter name L Default value 0000006 Is a state variable no Modelica parameter name Beta Default value 0000041 Is a state variable no Modelica parameter name Vt Default value 08 Is a state variable no Modelica parameter name K2 Default value 1144 Is a state variable no Modelica parameter name K5 Default value 07311 Is a state variable no Modelica parameter name dW Default value 00000025 Is a state variable no Modelica parameter name dL Default value 00000015 Is a state variable no Modelica parameter name RDS Default value 10000000 Is a state variable no File name of the model NMOS Interfacing function SCImodulesscicosblocksmacrosElectricalNMOSsci Modelica model SCImodulesscicosblocksmacrosElectricalNMOSmo palettes 2481 See also PMOS Simple PMOS Transistor Authors wwwmodelicaorg palettes 2482 Nome NPN NPN transistor Block Screenshot Contents NPN transistor Palette Description Dialog box Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description This model is a simple model of a bipolar NPN junction transistor according to EbersMoll palettes 2483 Dialog box Parameter Default value Description Bf 50 Forward beta Br 01 Reverse beta Is 1e16 Transport saturation current A Vak 002 Early voltage inverse 1Volt 1V Tauf 012e9 Ideal forward transit time s Taur 5e9 Ideal reverse transit time s Ccs 1e12 Collectorsubstratground cap F Cje 04e12 Baseemitter zero bias depletion cap F Cjc 05e12 Basecoll zero bias depletion cap F palettes 2484 Phie 08 Baseemitter diffusion voltage V Me 04 Baseemitter gradation exponent Phic 08 Basecollector diffusion voltage V Mc 0333 Basecollector gradation expo nent Gbc 1e15 Basecollector conductance S Gbe 1e15 Baseemitter conductance S Vt 002585 Voltage equivalent of tempera ture V EMin 100 if x EMin the expx function is linearized EMax 40 if x EMax the expx function is linearized Default properties Inputs Modelica variable name B Implicit variable Outputs Modelica variable name C Implicit variable Modelica variable name E Implicit variable Parameters Modelica parameter name Bf Default value 50 Is a state variable no Modelica parameter name Br Default value 01 Is a state variable no Modelica parameter name Is Default value 0 Is a state variable no Modelica parameter name Vak Default value 002 palettes 2485 Is a state variable no Modelica parameter name Tauf Default value 1200E10 Is a state variable no Modelica parameter name Taur Default value 5000E09 Is a state variable no Modelica parameter name Ccs Default value 1000E12 Is a state variable no Modelica parameter name Cje Default value 4000E13 Is a state variable no Modelica parameter name Cjc Default value 5000E13 Is a state variable no Modelica parameter name Phie Default value 08 Is a state variable no Modelica parameter name Me Default value 04 Is a state variable no Modelica parameter name Phic Default value 08 Is a state variable no Modelica parameter name Mc Default value 0333 Is a state variable no Modelica parameter name Gbc Default value 1000E15 Is a state variable no palettes 2486 Modelica parameter name Gbe Default value 1000E15 Is a state variable no Modelica parameter name Vt Default value 002585 Is a state variable no Modelica parameter name EMinMax Default value 40 Is a state variable no File name of the model NPN Interfacing function SCImodulesscicosblocksmacrosElectricalNPNsci Modelica model SCImodulesscicosblocksmacrosElectricalNPNmo See also PNP PNP transistor Authors wwwmodelicaorg palettes 2487 Nome OpAmp Ideal opamp noratornullator pair Block Screenshot Contents Ideal opamp noratornullator pair Palette Description Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description The ideal OpAmp is a twoport The left port is fixed to v10 and i10 nullator At the right port both any voltage v2 and any current i2 are possible norator Default properties Inputs Modelica variable name inp Implicit variable Modelica variable name inn Implicit variable Outputs Modelica variable name out Implicit variable File name of the model OpAmp Interfacing function SCImodulesscicosblocksmacrosElectricalOpAmpsci palettes 2488 Modelica model SCImodulesscicosblocksmacrosElectricalOpAmpmo Authors wwwmodelicaorg palettes 2489 Nome PMOS Simple PMOS Transistor Block Screenshot Contents Simple PMOS Transistor Palette Description Dialog box Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description The PMOS model is a simple model of a pchannel metaloxide semiconductor FET It differs slightly from the device used in the SPICE simulator For more details please care for H Spiro The model does not consider capacitances A small fixed drainsource resistance is included to avoid numerical difficulties Some typical parameter sets are W m Lm Beta 1V² Vt V K2 K5 DW m DL m 50e6 8e6 0085 15 41 839 38e6 40e6 20e6 6e6 0105 10 41 839 25e6 21e6 30e6 5e6 0059 3 98 101 0 39e6 30e6 5e6 0152 69 104 11 8e6 4e6 30e6 5e6 0163 69 104 11 8e6 4e6 30e6 5e6 0182 69 086 106 1e6 6e6 20e6 6e6 0074 1 4 59 0 0 palettes 2490 Dialog box Width m W Properties Type vec of size 1 Length m L Properties Type vec of size 1 Transconductance parameter AVV Beta Properties Type vec of size 1 Zero bias threshold voltage V Vt Properties Type vec of size 1 Bulk threshold parameter K2 Properties Type vec of size 1 Reduction of pinchoff region K5 Properties Type vec of size 1 palettes 2491 Narrowing of channel m dW Properties Type vec of size 1 Shortening of channel m dL Properties Type vec of size 1 DrainSourceResistance Ohm RDS Properties Type vec of size 1 Default properties Inputs Modelica variable name G Implicit variable Outputs Modelica variable name D Implicit variable Modelica variable name B Implicit variable Modelica variable name S Implicit variable Parameters Modelica parameter name W Default value 000005 Is a state variable no Modelica parameter name L Default value 0000006 Is a state variable no Modelica parameter name Beta Default value 00000105 Is a state variable no Modelica parameter name Vt Default value 1 palettes 2492 Is a state variable no Modelica parameter name K2 Default value 041 Is a state variable no Modelica parameter name K5 Default value 0839 Is a state variable no Modelica parameter name dW Default value 00000025 Is a state variable no Modelica parameter name dL Default value 00000021 Is a state variable no Modelica parameter name RDS Default value 10000000 Is a state variable no File name of the model PMOS Interfacing function SCImodulesscicosblocksmacrosElectricalPMOSsci Modelica model SCImodulesscicosblocksmacrosElectricalPMOSmo See also NMOS Simple NMOS Transistor Authors wwwmodelicaorg palettes 2493 Nome PNP PNP transistor Block Screenshot Contents PNP transistor Palette Description Dialog box Default properties Interfacing function Modelica model See also Authors Palette Electricalcosf Electrical toolbox Description This model is a simple model of a bipolar PNP junction transistor according to EbersMoll palettes 2494 Dialog box Parameter Default value Description Bf 50 Forward beta Br 01 Reverse beta Is 1e16 Transport saturation current A Vak 002 Early voltage inverse 1Volt 1V Tauf 012e9 Ideal forward transit time s Taur 5e9 Ideal reverse transit time s Ccs 1e12 Collectorsubstratground cap F Cje 04e12 Baseemitter zero bias depletion cap F Cjc 05e12 Basecoll zero bias depletion cap F Phie 08 Baseemitter diffusion voltage V Me 04 Baseemitter gradation exponent palettes 2495 Phic 08 Basecollector diffusion voltage V Mc 0333 Basecollector gradation expo nent Gbc 1e15 Basecollector conductance S Gbe 1e15 Baseemitter conductance S Vt 002585 Voltage equivalent of tempera ture V EMin 100 if x EMin the expx function is linearized EMax 40 if x EMax the expx function is linearized Default properties Inputs Modelica variable name B Implicit variable Outputs Modelica variable name C Implicit variable Modelica variable name E Implicit variable Parameters Modelica parameter name Bf Default value 50 Is a state variable no Modelica parameter name Br Default value 01 Is a state variable no Modelica parameter name Is Default value 0 Is a state variable no Modelica parameter name Vak Default value 002 Is a state variable no Modelica parameter name Tauf palettes 2496 Default value 1200E10 Is a state variable no Modelica parameter name Taur Default value 5000E09 Is a state variable no Modelica parameter name Ccs Default value 1000E12 Is a state variable no Modelica parameter name Cje Default value 4000E13 Is a state variable no Modelica parameter name Cjc Default value 5000E13 Is a state variable no Modelica parameter name Phie Default value 08 Is a state variable no Modelica parameter name Me Default value 04 Is a state variable no Modelica parameter name Phic Default value 08 Is a state variable no Modelica parameter name Mc Default value 0333 Is a state variable no Modelica parameter name Gbc Default value 1000E15 Is a state variable no Modelica parameter name Gbe Default value 1000E15 palettes 2497 Is a state variable no Modelica parameter name Vt Default value 002585 Is a state variable no Modelica parameter name EMinMax Default value 40 Is a state variable no File name of the model PNP Interfacing function SCImodulesscicosblocksmacrosElectricalPNPsci Modelica model SCImodulesscicosblocksmacrosElectricalPNPmo See also NPN NPN transistor Authors wwwmodelicaorg palettes 2498 Nome PotentialSensor Potential sensor Block Screenshot Contents Potential sensor Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This block is used to measure the voltage with respect to the reference voltage Ground block in an electrical circuit The voltage is given to the explicit part of the model via an explicit output port Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name v Explicit variable File name of the model PotentialSensor Interfacing function SCImodulesscicosblocksmacrosElectricalPotentialSensorsci Modelica model SCImodulesscicosblocksmacrosElectricalPotentialSensormo palettes 2499 Nome Resistor Electrical resistor Block Screenshot Contents Electrical resistor Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description A resistor is a twoport electrical component that resists an electric current by producing a voltage drop between its terminals according to the Ohms law The electrical resistance is equal to the voltage drop across the resistor divided by the current through the resistor Dialog box R ohm palettes 2500 Resistance Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name R Default value 001 Is a state variable no File name of the model Resistor Interfacing function SCImodulesscicosblocksmacrosElectricalResistorsci Modelica model SCImodulesscicosblocksmacrosElectricalResistormo palettes 2501 Nome SineVoltage Sine voltage source Block Screenshot Contents Sine voltage source Palette Description Dialog box Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description This Modelica block a general sine voltage source The internal ohmic resistance is zero Dialog box palettes 2502 Amplitude Volt Sine voltage amplitude Properties Type vec of size 1 phase rad phase shift of the sine voltage Properties Type vec of size 1 Frequency Hz Sine voltage frequency Properties Type vec of size 1 Voltageoffset V Offset Voltage of the sine voltage Properties Type vec of size 1 Timeoffset s Start time During the start time the signal value is equal to the voltage offset Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name V Default value 1 Is a state variable no Modelica parameter name phase Default value 0 Is a state variable no Modelica parameter name freqHz Default value 1 Is a state variable no palettes 2503 Modelica parameter name offset Default value 0 Is a state variable no Modelica parameter name startTime Default value 0 Is a state variable no File name of the model SineVoltage Interfacing function SCImodulesscicosblocksmacrosElectricalSineVoltagesci Modelica model SCImodulesscicosblocksmacrosElectricalSineVoltagemo Authors wwwmodelicaorg palettes 2504 Nome Switch Nonideal electrical switch Block Screenshot Contents Nonideal electrical switch Palette Description Dialog box Default properties Interfacing function Modelica model Authors Palette Electricalcosf Electrical toolbox Description This is a nonideal twopole switch If the explicit input become positive two pins are connected via a resistor of resistance RON Otherwise two pins are connected via ROFF resistance Note that using this block may result in a stiff model so try to choose proper error tolerances Dialog box Resistance in On state Ohm Switch resistance when the Switch is closed Properties Type vec of size 1 palettes 2505 Resistance in Off state Ohm Switch resistance when the switch is open Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Modelica variable name inp Explicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name Ron Default value 001 Is a state variable no Modelica parameter name Roff Default value 100000 Is a state variable no File name of the model Switch Interfacing function SCImodulesscicosblocksmacrosElectricalSwitchsci Modelica model SCImodulesscicosblocksmacrosElectricalSwitchmo Authors Masoud Najafi INRIA palettes 2506 Nome VVsourceAC Variable AC voltage source Block Screenshot Contents Variable AC voltage source Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description The variable voltage source block is a model for a controlled AC voltage source This component provides a sinusoid voltage across its ports The amplitude of the output voltage is governed by the explicit input and the frequency is defined by the user The ohmic resistance of the block is zero Dialog box Frequency Hz Frequency of the output sinosoid voltage Properties Type vec of size 1 Default properties Inputs Modelica variable name p palettes 2507 Implicit variable Modelica variable name VA Explicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name f Default value 50 Is a state variable no File name of the model VVsourceAC Interfacing function SCImodulesscicosblocksmacrosElectricalVVsourceACsci Modelica model SCImodulesscicosblocksmacrosElectricalVVsourceACmo palettes 2508 Nome VariableResistor Electrical variable resistor Block Screenshot Contents Electrical variable resistor Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component represents a variable ohmic resistor The resistance is controlled via an explicit input port Default properties Inputs Modelica variable name p Implicit variable Modelica variable name R Explicit variable Outputs Modelica variable name n Implicit variable File name of the model VariableResistor palettes 2509 Interfacing function SCImodulesscicosblocksmacrosElectricalVariableResistorsci Modelica model SCImodulesscicosblocksmacrosElectricalVariableResistormo palettes 2510 Nome VoltageSensor Electrical voltage sensor Block Screenshot Contents Electrical voltage sensor Palette Description Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component is used to measure the voltage difference between two nodes in an electrical circuit The output signal is the difference between the voltages of the black port and the white port The ohmic conductance of this block is zero Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Modelica variable name v Explicit variable File name of the model VoltageSensor palettes 2511 Interfacing function SCImodulesscicosblocksmacrosElectricalVoltageSensorsci Modelica model SCImodulesscicosblocksmacrosElectricalVoltageSensormo palettes 2512 Nome VsourceAC Electrical AC voltage source Block Screenshot Contents Electrical AC voltage source Palette Description Dialog box Default properties Interfacing function Modelica model Palette Electricalcosf Electrical toolbox Description This component is an AC voltage source with sinusoid output voltage The amplitude and the fre quency of the output voltage is set by the user The ohmic resistance of this block is zero Dialog box Amplitude Volt Amplitude of the output sinusoid voltage Properties Type vec of size 1 Frequency Hz Frequency of the output sinusoid voltage palettes 2513 Properties Type vec of size 1 Default properties Inputs Modelica variable name p Implicit variable Outputs Modelica variable name n Implicit variable Parameters Modelica parameter name VA Default value 220 Is a state variable no Modelica parameter name f Default value 50 Is a state variable no File name of the model VsourceAC Interfacing function SCImodulesscicosblocksmacrosElectricalVsourceACsci Modelica model SCImodulesscicosblocksmacrosElectricalVsourceACmo 8 Event handling palette palettes 2514 Nome Eventspal Event handling palette Block Screenshot Module xcos Description The Event handling palette is used to handle events in the diagram It contains several activation clocks synchronous blocks and blocks to gather events in a single link Blocks ANDBLK Activation and ANDLOGf Logical and CEVENTSCOPE Activation scope CLKFROM Receives data from a corresponding CLKGOTO CLKGOTO Pass block input to CLKFROM block palettes 2515 CLKGotoTagVisibility Define Scope of CLKGOTO tag visibility CLKOUTVf Output activation port CLKSOMVf Activation union CLOCKc Activation clock EDGETRIGGER EDGETRIGGER block ENDBLK END block ENDc ENDc block ESELECTf Synchronous block EventSelect EVTDLYc Event delay EVTGENf Event generator EVTVARDLY Event variable delay ExtractActivation ExtractActivation block HALTf Stop simulation IFTHELf Synchronous block IfThenElse Mfreq Multiple Frequencies MCLOCKf Clock Frequency division MFCLCKf Clock Multiple Frequencies REGISTER Shift Register SampleCLK Sample Time Clock freqdiv Frequency division palettes 2516 Nome ANDBLK Activation and Block Screenshot Contents Activation and Palette Description Default properties Interfacing function Compiled Super Block content Authors Palette Event handling palette Description The Bus Creator block combines a set of signals ie a group of signals represented by a single line in a block diagram It allows you to reduce the number of lines required to route signals from one part of a diagram to another This makes your easier to understand Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 2 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper palettes 2517 Interfacing function SCImodulesscicosblocksmacrosEventsANDBLKsci Compiled Super Block content Authors Ramine Nikoukhah INRIA palettes 2518 Nome ANDLOGf Logical and Block Screenshot Contents Logical and Palette Description Default properties Interfacing function Authors Palette Event handling palette Description This block with two event inputs and a regular output outputs 1 or 1 on its regular output depending on input events 1 When events are synchronously present on both event input ports 1 When only one event is present Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 2 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2519 object discretetime state no name of computational function andlog Interfacing function SCImodulesscicosblocksmacrosEventsANDLOGfsci Authors Ramine Nikoukhah INRIA palettes 2520 Nome CEVENTSCOPE Activation scope Block Screenshot Contents Activation scope Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Event handling palette Description This block realizes the visualization of the input event signals Dialog box Number of event inputs palettes 2521 an integer giving the number of event input ports colors a vector of integers The ith element is the color number or dash type used to draw the evolution of the ith input port signal Seexset for color dash type definitions Properties Type vec of size 1 colors c an integer It is the color number or dash type used to draw the evolution of the input port signal Seeplot2d for color dash type definitions Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Refresh period Maximum value on the Xaxis time The plot is redrawn when time reaches a multiple of this value Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2522 object discretetime state no name of computational function cevscpe Interfacing function SCImodulesscicosblocksmacrosSinksCEVENTSCOPEsci Computational function SCImodulesscicosblockssrcccevscpec Type 4 Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2523 Nome CLKFROM Receives data from a corresponding CLKGOTO Block Screenshot Contents Receives data from a corresponding CLKGOTO Palette Description Dialog box Default properties Interfacing function See also Authors Palette Event handling palette Description This block is used to connect events ports For more information on how it works please refer to the documentation of the FROM block by clicking on the link in the See also field Dialog box Tag The tag of the CLKGOTO block passing the signal to this CLKFROM block Properties Type str of size 1 Default properties always active no palettes 2524 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function clkfrom Interfacing function SCImodulesscicosblocksmacrosBranchingCLKFROMsci See also FROM FROM Receives data from a corresponding GOTO Authors Fady NASSIF INRIA palettes 2525 Nome CLKGOTO Pass block input to CLKFROM block Block Screenshot Contents Pass block input to CLKFROM block Palette Description Dialog box Default properties Interfacing function See also Authors Palette Event handling palette Description This block is used to connect events ports For more information on how it works please refer to the documentation of the GOTO block by clicking on the link in the See also field Dialog box Tag This parameter identifies the Goto block whose scope is defined in this block Properties Type str of size 1 Tag Visibility 1Local 2Scoped 3Global palettes 2526 This parameter idetifies the visibility of the block It can be local1 scoped2 or global3 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function clkgoto Interfacing function SCImodulesscicosblocksmacrosBranchingCLKGOTOsci See also GOTO GOTO Pass block input to From block Authors Fady NASSIF INRIA palettes 2527 Nome CLKGotoTagVisibility Define Scope of CLKGOTO tag visibility Block Screenshot Contents Define Scope of CLKGOTO tag visibility Palette Description Dialog box Default properties Interfacing function See also Authors Palette Event handling palette Description This block is used in the event case For more information on how it works please refer to the docu mentation of the GotoTagVisibility block by clicking on the link in the See also field Dialog box GotoTag The Goto block tag whose visibility is defined by the location of this block Properties Type str of size 1 Default properties always active no palettes 2528 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function clkgototagvisibility Interfacing function SCImodulesscicosblocksmacrosBranchingCLKGotoTagVisibilitysci See also GotoTagVisibility Define Scope of GOTO tag visibility Authors Fady NASSIF INRIA palettes 2529 Nome CLKOUTVf Output activation port Block Screenshot Contents Output activation port Palette Description Dialog box Default properties Interfacing function Authors Palette Event handling palette Description This block must only be used inside Xcos Super Blocks to represent an event output port In a Super Block the event output ports must be numbered from 1 to the number of event output ports Dialog box Port number an integer defining the port number Properties Type vec of size 1 Default properties always active no directfeedthrough no palettes 2530 zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function output Interfacing function SCImodulesscicosblocksmacrosSinksCLKOUTVfsci Authors Ramine Nikoukhah INRIA palettes 2531 Nome CLKSOMVf Activation union Block Screenshot Contents Activation union Palette Description Default properties Interfacing function Computational function Authors Palette Event handling palette Description This block is an event addition block with up to three inputs The output reproduces the events on all the input ports Strictly speaking CLKSOMV is not a Xcos block because it is discarded at the compilation phase The inputs and output of CLKSOMV are synchronized Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 3 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function sum palettes 2532 Interfacing function SCImodulesscicosblocksmacrosEventsCLKSOMVfsci Computational function SCImodulesscicosblockssrccsumc Type 0 Authors Ramine Nikoukhah INRIA palettes 2533 Nome EDGETRIGGER EDGETRIGGER block Block Screenshot Contents EDGETRIGGER block Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Palette Event handling palette Description This block generates an event on rising falling or both edges of the input signal depending on block parameter A rising edge is a change in value from strictly negative to positive or zero or a change in value from zero to strictly positive A falling edge is the opposite Note that this block only generates an event if the input jumps due to an event The generated event is synchronous with the event causing the jump This block does not detect continuoustime zerocrossings Dialog box rising 1 falling 1 both 0 Properties Type vec of size 1 Default properties always active no palettes 2534 directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosMiscEDGETRIGGERsci Compiled Super Block content palettes 2535 Nome ESELECTf Synchronous block EventSelect Block Screenshot Contents Synchronous block EventSelect Palette Description Dialog box Default properties Interfacing function Authors Palette Event handling palette Description Special block similar to IfThenElse Input and output are synchronized The incoming event is di rected to one of the output event ports depending on the value of the regular input For example when the input value is between 0 and 1 the control input is redirected to the first command output when the input value is between 1 and 2 the control input is redirected to the second command output et cætera Dialog box number of output event ports palettes 2536 A scalar Number of output event ports Properties Type vec of size 1 Inherit If no then it inherits the event from event input port elseif yes then event is activated by regular input port Properties Type vec of size 1 zerocrossing Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 2 continuoustime state no discretetime state no object discretetime state no name of computational function eselect Interfacing function SCImodulesscicosblocksmacrosBranchingESELECTfsci Authors Ramine Nikoukhah INRIA palettes 2537 Nome EVTDLYc Event delay Block Screenshot Contents Event delay Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Event handling palette Description One event is generated Delay after an event enters the unique input event port Block may also generate an initial output event The event date of that block is computed by the formula where the date of initial output event the delay and and internal integer discrete counter palettes 2538 Dialog box Delay scalar Time delay between input and output event Properties Type vec of size 1 Date of initial output event scalar IfAutoexec0 block initially generates an output event at dateAutoexec Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function evtdly4 Interfacing function SCImodulesscicosblocksmacrosEventsEVTDLYcsci palettes 2539 Computational function SCImodulesscicosblockssrccevtdly4c Type 4 See also CLOCKc Activation clock Authors Alan Layec INRIA palettes 2540 Nome EVTGENf Event generator Block Screenshot Contents Event generator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Event handling palette Description One event is generated on the unique output event port if Event time is larger than equal to zero if not no event is generated Dialog box Event Time scalar date of the initial event Properties Type vec of size 1 Default properties always active no palettes 2541 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function trash Interfacing function SCImodulesscicosblocksmacrosEventsEVTGENfsci Computational function SCImodulesscicosblockssrcfortrantrashf Type 0 Authors Ramine Nikoukhah INRIA palettes 2542 Nome EVTVARDLY Event variable delay Block Screenshot Contents Event variable delay Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Event handling palette Description One event is generated Delay after an event enters the unique input event port The value of the delay is read from the regular input port Block may also generate an initial output event Dialog box Initial event firing time One event is generated on the unique output event port if Event time is larger than equal to zero if not no event is generated Properties Type vec of size 1 Default properties always active no palettes 2543 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function evtvardly Interfacing function SCImodulesscicosblocksmacrosEventsEVTVARDLYsci Computational function SCImodulesscicosblockssrccevtvardlyc Type 4 Authors Ramine Nikoukhah INRIA palettes 2544 Nome ExtractActivation ExtractActivation block Block Screenshot Contents ExtractActivation block Palette Default properties Interfacing function Compiled Super Block content Palette Event handling palette Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosMiscExtractActivationsci palettes 2545 Compiled Super Block content palettes 2546 Nome HALTf Halt Block Screenshot Contents Halt Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Event handling palette Description This block has a unique input event port Upon the arrival of an event the simulation is stopped and the main Xcos window is activated Simulation can be restarted or continued Run button Dialog box State on halt A scalar value to be placed in the state of the block For debugging purposes this allows to distinguish between different halts Properties Type vec of size 1 Default properties always active no palettes 2547 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function hltblk Interfacing function SCImodulesscicosblocksmacrosEventsHALTfsci Computational function SCImodulesscicosblockssrcfortranhltblkf Type 0 Authors Ramine Nikoukhah INRIA palettes 2548 Nome IFTHELf Synchronous block IfThenElse Block Screenshot Contents Synchronous block IfThenElse Palette Description Dialog box Default properties Interfacing function Authors Palette Event handling palette Description One event is generated on one of the output event ports when an input event arrives Depending on the sign of the regular input the event is generated on the first or second output This is a Synchro block input and output event are synchronized Dialog box Inherit If no then it inherits the event from event input port elseif yes then event is activated by regular input port Properties Type vec of size 1 zerocrossing palettes 2549 Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 2 continuoustime state no discretetime state no object discretetime state no name of computational function ifthel Interfacing function SCImodulesscicosblocksmacrosEventsIFTHELfsci Authors Ramine Nikoukhah INRIA palettes 2550 Nome MCLOCKf MCLOCKf title Block Screenshot Contents Multiple Frequencies fn Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Palette Event handling palette Description Add here a paragraph of the function description Dialog box basic period 1f The parameter description 1 Properties Type vec of size 1 multiply by n The parameter description 2 Properties Type vec of size 1 palettes 2551 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 2 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosEventsMCLOCKfsci Compiled Super Block content palettes 2552 Nome MFCLCKf MFCLCKf title Block Screenshot Contents Clock Frequency division Palette Description Dialog box Default properties Interfacing function Computational function Palette Event handling palette Description Add here a paragraph of the function description Dialog box basic period 1f The parameter description 1 Properties Type vec of size 1 multiply by n The parameter description 2 Properties Type vec of size 1 palettes 2553 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 2 continuoustime state no discretetime state yes object discretetime state no name of computational function mfclck Interfacing function SCImodulesscicosblocksmacrosEventsMFCLCKfsci Computational function SCImodulesscicosblockssrcfortranmfclckf Type 0 palettes 2554 Nome Mfreq Multiple Frequencies Block Screenshot Contents Multiple Frequencies Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Event handling palette Description This blocks generates events at specific sample time of the simulation time The sample time is given in the Sample Time field and the offset is given in the Offset field This block has one event input the number of event outputs depends on the number of different sample time For example if the vector of sample time is 1 1 2 and the vector of offset is 0 5 0 then the block has 7 outputs The first output is activated when the simulation time is equal to a multiple of the first sample time plus the first offset The second output is activated when the simulation time is equal to a multiple of the second sample time plus the second offset The third output is activated when we have both cases first case and second case The fourth output is activated when the simulation time is equal to a multiple of the third sample time plus the third offset The fifth output is activated when we have both cases first case and forth case The sixth output is activated when we have both cases second case and fourth case The seventh output is activated when we have both cases third case and forth case palettes 2555 etc So the number of outputs is equal to 2number of different time values Each of these time values is represented by a binary number associated to the outputs number in decimal Dialog box Sample time Vector of sample time values Properties Type vec of size 1 Offset Vector of offset values Must have the same size as the Sample time and each offset value must be less than its corresponding sample time Properties Type vec of size 1 Example Let us take the example where the sample time is equal to 1 1 2 and the offset is equal to 0 5 0 Consider tsimulation time When t0 the fifth output is activated 001 100 When t05 the second output is activated 010 When t1 the first output is activated 001 When t15 the second output is activated 010 When t2 we loop back to 0 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 3 continuoustime state no discretetime state no palettes 2556 object discretetime state no name of computational function mfrequ Interfacing function SCImodulesscicosblocksmacrosEventsMfreqsci Computational function SCImodulesscicosblockssrccmfrequc Type 4 See also MFCLCKf MFCLCKf title Authors Fady NASSIF INRIA palettes 2557 Nome freqdiv Frequency division Block Screenshot Contents Frequency division Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Authors Palette Event handling palette Description This block is a Super Block The input event is directed once every n times to output The input is driven by an event clock Dialog box Phase positive scalar Properties Type vec of size 1 Division factor palettes 2558 an integer greater than 1 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosEventsfreqdivsci Compiled Super Block content palettes 2559 Authors Ramine Nikoukhah INRIA 9 Implicit palette palettes 2560 Nome Implicitpal Implicit palette Block Screenshot Module xcos Description In the Implicit palette you can find blocks used to model implicit systems Blocks CONSTRAINTf Constraint DIFFf Sum palettes 2561 Nome CONSTRAINTf Constraint Block Screenshot Contents Constraint Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Implicit palette Description Defines implicit algebraic relations Dialog box Set number of constraints no of algebraic relations to be defined Properties Type vec of size 1 Default properties always active yes directfeedthrough no palettes 2562 zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function constraint Interfacing function SCImodulesscicosblocksmacrosMiscCONSTRAINTfsci Computational function SCImodulesscicosblockssrcfortranconstraintf Type 10001 Authors Ramine Nikoukhah INRIA palettes 2563 Nome DIFFf Derivative Block Screenshot Contents Derivative Palette Description Dialog box Default properties Interfacing function Computational function Palette Implicit palette Description This block computes the derivative of the input Dialog box Initial state The initial continuous state Properties Type vec of size 1 Initial Derivative The initial derivative state palettes 2564 Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state yes discretetime state no object discretetime state no name of computational function diffblk Interfacing function SCImodulesscicosblocksmacrosMiscDIFFfsci Computational function SCImodulesscicosblockssrcfortrandiffblkf Type 10001 10 Integer palette palettes 2565 Nome Integerpal Integer palette Block Screenshot Module xcos Description That palette is dedicated to handle integer numbers Various basic operators for the management of bit fields and for logic are implemented as well as common gates encountered in digital circuits Blocks BITCLEAR BITCLEAR Clear a Bit BITSET BITSET Set a Bit CONVERT CONVERT Data Type Conversion DFLIPFLOP D flipflop DLATCH D latch flipflop EXTRACTBITS EXTRACTBITS INTMUL INTMUL integer matrix multiplication JKFLIPFLOP JK flipflop LOGIC Combinational Logic SHIFT SHIFT Shift Bits SRFLIPFLOP SR flipflop palettes 2566 Nome BITCLEAR Clear a Bit Block Screenshot Contents Clear a Bit Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This blocks set the specified bit of the integer input to 0 The user can specify the bit in the fieldindex of bit Bit 0 is the least significant bit Dialog box Datatype3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 palettes 2567 index of bit 0 is least significant It indicate the index of the bit to clear When the type is int32 or uint32 the number must be positive and less than 32 When the type is int16 or uint16 the number must be positive and less than 16 When the type is int8 or uint8 the number must be positive and less than 8 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 3 regular outputs port 1 size 11 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function bitclear32 Interfacing function SCImodulesscicosblocksmacrosIntegerOpBITCLEARsci Computational function SCImodulesscicosblockssrccbitclear32c SCImodulesscicosblockssrccbitclear16c SCImodulesscicosblockssrccbitclear8c See also BITSET BITSET Set a Bit Authors Fady NASSIF INRIA palettes 2568 Nome BITSET Set a Bit Block Screenshot Contents Set a Bit Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This blocks set the specified bit of the integer input to 1 The user can specify the bit in the fieldindex of bit Bit 0 is the least significant bit Dialog box Datatype3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 palettes 2569 index of bit 0 is leat significant It indicate the index of the bit to clear When the type is int32 or uint32 the number must be positive and less than 32 When the type is int16 or uint16 the number must be positive and less than 16 When the type is int8 or uint8 the number must be positive and less than 8 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 3 regular outputs port 1 size 11 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function bitset32 Interfacing function SCImodulesscicosblocksmacrosIntegerOpBITSETsci Computational function SCImodulesscicosblockssrccbitset32c SCImodulesscicosblockssrccbitset16c SCImodulesscicosblockssrccbitset8c See also BITCLEAR BITCLEAR Clear a Bit Authors Fady NASSIF INRIA palettes 2570 Nome CONVERT Data Type Conversion Block Screenshot Contents CONVERT Data Type Conversion Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Integer palette Description This block converts an input signal of any data type to a specified data type The input can be real complex or integer When the output is an integer and when overflow occurs the block three different forms of results 1 A normal non saturated result 2 A saturated result 3 An error message warning the user about the overflow The user can select one of these three forms by setting the DO ON OVERFLOW field to 01 or 2 Dialog box palettes 2571 input type 1 double 3int32 4int16 5int8 It indicates the input data type it can be a double or an integer Properties Type vec of size 1 output type 1 double 3int32 4int16 5int8 It indicates the output data type it can be a double or an integer Properties Type vec of size 1 Do on Overflow0Nothing 1Saturate 2Error When this parameter is set to zero the result is similar to a normal multiplication of two integer matrix When it is set to 1 on overflow the block saturate the result When it is set to 2 on overflow an error message box appears Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function convert Interfacing function SCImodulesscicosblocksmacrosIntegerOpCONVERTsci Computational function SCImodulesscicosblockssrccconvertc Authors Fady NASSIF INRIA palettes 2572 Nome DFLIPFLOP D flipflop Block Screenshot Contents D flipflop Palette Description Default properties Interfacing function Compiled Super Block content See also Authors Palette Integer palette Description The DFLIPFLOP block outputs the input state when the enable is set and on the rising edge of the clock The input is D the enable is en and the clock is clk Q and Q are the outputs of this block This block is almostly used with digital number the input data type is int8 The truth table of this block is en D Q Q 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs palettes 2573 port 1 size 11 type 5 port 2 size 11 type 1 port 3 size 11 type 1 regular outputs port 1 size 11 type 5 port 2 size 11 type 5 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosIntegerOpDFLIPFLOPsci Compiled Super Block content See also DLATCH D latch flipflop SRFLIPFLOP SR flipflop JKFLIPFLOP JK flipflop palettes 2574 Authors Fady NASSIF INRIA palettes 2575 Nome DLATCH D latch flipflop Block Screenshot Contents D latch flipflop Palette Description Default properties Interfacing function Compiled Super Block content See also Authors Palette Integer palette Description This block outputs the input state when the input gate is high The input is D the enable is C Q and Q are the outputs of this block This block is almost used with digital number the input data type is int8 The truth table of this block is C D Q Q 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs palettes 2576 port 1 size 11 type 5 port 2 size 11 type 1 regular outputs port 1 size 11 type 5 port 2 size 11 type 5 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosIntegerOpDLATCHsci Compiled Super Block content See also DFLIPFLOP D flipflop SRFLIPFLOP SR flipflop JKFLIPFLOP JK flipflop Authors Fady NASSIF INRIA palettes 2577 Nome EXTRACTBITS EXTRACTBITS Block Screenshot Contents EXTRACTBITS Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This block outputs a contiguous selection of bits from the input integer numberThe Bits to extract defines the method by which the user select the output bits 1 When Upper Half is selected the block outputs the half of the input that contain the most significant bit In this case the third parameter number of bits or index of bit is ignored 2 When Lower Half is selected the block outputs the half of the input that contain the least significant bit In this case the third parameter number of bits or index of bit is ignored 3 When Range starting with most significant bit is selected the block outputs certain number of bits of the input that contain the most significant bit In this case the third parameter number of bits or index of bit defines the number of bits to extract 4 When Range ending with least significant bit is selected the block outputs certain number of bits of the input that contain the least significant bit In this case the third parameter number of bits or index of bit defines the number of bits to extract 5 When Range of bits is selected the block outputs a range of bits of the input In this case the third parameter number of bits or index of bit defines the range of bits to extract it must be a vector with the format startend The extracted value depends on the forth parameter Treat bit field as an integer When it is set to 0 the input scaling is used to determine the output scaling When it is set to 1 only the extracted bits forms the output number palettes 2578 Dialog box Datatype3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 Bits to extract1Upper Half 2Lower Half 3Range starting with most significant bit 4Ran ge ending with least significant bit 5Range of bits It indicates the mode used to extract bits from the input data Properties Type vec of size 1 number of bits or index of bit case range of bitsstartend0 is least significant bit When the Bits to extract field is set to 3 or 4 this parameter is used to determine the number of bits to extract and it must be a number When the Bits to extract field is set to 5 this parameter is used to determine range of bits to extract and it must have the startend form vector When the Bits to extract field is set to 1 or 2 this parameter is ignored Properties Type vec of size 1 Treat bit field as an integer0no 1yes It indicates the scaling mode to use on the output bits selection Properties Type vec of size 1 palettes 2579 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 3 regular outputs port 1 size 11 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function extractbit32UH0 Interfacing function SCImodulesscicosblocksmacrosIntegerOpEXTRACTBITSsci Computational function SCImodulesscicosblockssrccextractbit32UH0c SCImodulesscicosblockssrccextractbit32UH1c SCImodulesscicosblockssrccextractbitu32UH1c SCImodulesscicosblockssrccextractbit32LHc SCImodulesscicosblockssrccextractbit32MSB0c SCImodulesscicosblockssrccextractbit32MSB1c SCImodulesscicosblockssrccextractbitu32MSB1c SCImodulesscicosblockssrccextractbit32LSBc SCImodulesscicosblockssrccextractbit32RB0c SCImodulesscicosblockssrccextractbit32RB1c SCImodulesscicosblockssrccextractbitu32RB1c SCImodulesscicosblockssrccextractbit16UH0c SCImodulesscicosblockssrccextractbit16UH1c palettes 2580 SCImodulesscicosblockssrccextractbitu16UH1c SCImodulesscicosblockssrccextractbit16LHc SCImodulesscicosblockssrccextractbit16MSB0c SCImodulesscicosblockssrccextractbit16MSB1c SCImodulesscicosblockssrccextractbitu16MSB1c SCImodulesscicosblockssrccextractbit16LSBc SCImodulesscicosblockssrccextractbit16RB0c SCImodulesscicosblockssrccextractbit16RB1c SCImodulesscicosblockssrccextractbitu16RB1c SCImodulesscicosblockssrccextractbit8UH0c SCImodulesscicosblockssrccextractbit8UH1c SCImodulesscicosblockssrccextractbitu8UH1c SCImodulesscicosblockssrccextractbit8LHc SCImodulesscicosblockssrccextractbit8MSB0c SCImodulesscicosblockssrccextractbit8MSB1c SCImodulesscicosblockssrccextractbitu8MSB1c SCImodulesscicosblockssrccextractbit8LSBc SCImodulesscicosblockssrccextractbit8RB0c SCImodulesscicosblockssrccextractbit8RB1c SCImodulesscicosblockssrccextractbitu8RB1c See also BITSET BITSET Set a Bit BITCLEAR BITCLEAR Clear a Bit Authors Fady NASSIF INRIA palettes 2581 Nome INTMUL Integer matrix multiplication Block Screenshot Contents Integer matrix multiplication Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description The INTMUL block computes the matrix multiplication of two integers inputs matricesThe number of rows of the second matrix must be equal to the number of columns of the first matrix The output is a matrix where the number of rows is equal to the number of rows of the first input matrix and the number of columns is equal to the number of columns of the second input matrix This block support all the integer data type On overflow the result can take different forms 1 A normal non saturated result 2 A saturated result 3 An error message warning the user about the overflow The user can select one of these three forms by setting the DO ON OVERFLOW field to 01 or 2 palettes 2582 Dialog box Datatype 3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 Do on Overflow0Nothing 1Saturate 2Error When this parameter is set to zero the result is similar to a normal multiplication of two integer matrix When it is set to 1 on overflow the block saturate the result When it is set to 2 on overflow an error message box appears Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 3 port 2 size 23 type 3 regular outputs port 1 size 13 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matmuli32 palettes 2583 Interfacing function SCImodulesscicosblocksmacrosIntegerOpINTMULsci Computational function SCImodulesscicosblockssrccmatmuli32nc SCImodulesscicosblockssrccmatmuli16nc SCImodulesscicosblockssrccmatmuli8nc SCImodulesscicosblockssrccmatmului32nc SCImodulesscicosblockssrccmatmului16nc SCImodulesscicosblockssrccmatmului8nc SCImodulesscicosblockssrccmatmuli32sc SCImodulesscicosblockssrccmatmuli16sc SCImodulesscicosblockssrccmatmuli8sc SCImodulesscicosblockssrccmatmului32sc SCImodulesscicosblockssrccmatmului16sc SCImodulesscicosblockssrccmatmului8sc SCImodulesscicosblockssrccmatmuli32ec SCImodulesscicosblockssrccmatmuli16ec SCImodulesscicosblockssrccmatmuli8ec SCImodulesscicosblockssrccmatmului32ec SCImodulesscicosblockssrccmatmului16ec SCImodulesscicosblockssrccmatmului8ec See also MATMUL MATMUL Matrix Multiplication Authors Fady NASSIF INRIA palettes 2584 Nome JKFLIPFLOP JK flipflop Block Screenshot Contents JK flipflop Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Integer palette Description The JK flip flop is the most versatile of the basic flipflops It has two inputs traditionally labeled J and K When J and K are different the output takes the value of J at the next falling edge When J and K are both low no change occurs in the output state when they are both high the output will toggle from one state to other It can perform the functions of the setreset flipflop and has the advantage that there are no ambiguous states It can also act as a T flipflop to accomplish toggling action if J and K are tied together This toggle application finds extensive use in binary counters This block is almost used with digital number the input data type is int8 The truth table of this block is J K Qt Qt 0 0 Qt1 Qt1 0 1 0 1 1 0 1 0 1 1 Qt1 Qt1 palettes 2585 Dialog box Initial Value Initial Value of the state Q Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 5 port 2 size 11 type 1 port 3 size 11 type 5 regular outputs port 1 size 11 type 5 port 2 size 11 type 5 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosIntegerOpJKFLIPFLOPsci palettes 2586 Compiled Super Block content See also DLATCH D latch flipflop DFLIPFLOP D flipflop SRFLIPFLOP SR flipflop Authors Fady NASSIF INRIA palettes 2587 Nome LOGIC Combinational Logic Block Screenshot Contents Combinational Logic Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This block implements a standard truth table for modeling programming array digital circuit and any other boolean expressions The user can specify a matrix that defines all the possible block output in the Truth table field Each row of the matrix contains the output of different combination of input elements The number of rows must be a power of two it defines the number of inputs using the equation number of row 2 number of input The number of outputs is equal to the number of columns of the matrix This block support only the int8 data type When the input is positive the input is considered as logical 1 When it is negative or zero it is considered as logical 0 This block can be activated by an implicit input event or it can inherit the clock from the regular input This block is used to implement SR and JK flipflops palettes 2588 Dialog box Truth table The matrix of outputs For more information see the description part Properties Type mat of size 12 Inherit0no 1yes Specifies if the clock is inherit or not Properties Type vec of size 1 Example The easiest example to consider is the OR example In this case we have two inputs and only one outputthe truth table for this example is 0111 input 1 input 2 output 0 0 0 0 1 1 1 0 1 1 1 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 5 port 2 size 11 type 5 palettes 2589 regular outputs port 1 size 11 type 5 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function logic Interfacing function SCImodulesscicosblocksmacrosIntegerOpLOGICsci Computational function SCImodulesscicosblockssrcclogicc See also SRFLIPFLOP SR flipflop JKFLIPFLOP JK flipflop Authors Fady NASSIF INRIA palettes 2590 Nome SHIFT Shift Bits Block Screenshot Contents Shift Bits Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Integer palette Description This block shifts the bits of the input signal In this operation the digits are moved to the right or to the left The user can choose the rule to shifts the bits It can be normal or cycle by setting the Shifttype parameter to 0 or 1 When the Shifttype is 0 an arithmetic shift is applied to the input signal In this case the bits that are shifted out of either end are discarded Zeros are shifted in on the right in the case of left shift in the case of right shifts copies of the sign bit is shifted in on the left When the Shifttype is 1a circular shift is applied to the input signal In this case the bits are rotated as if the left and right ends of the register are joined The value that is shifted in on the right during a leftshift is whatever values was shifted out on the left and vice versa palettes 2591 Dialog box Datatype 3int32 4int16 5int8 It indicates the type of the inputoutput data It support all the integer datatype number must be between 3 and 8 Properties Type vec of size 1 Number of bits to shift left use negative number to shift right It indicates the number of bits the input signal is shifted A positive value indicates a shift left negative values indicates shift right Properties Type vec of size 1 Shifttype0Arithmetic 1Circular It indicate the rule used to shift the bits It can be arithmetic or circular When the Shifttype is normal an arithmetic shift is applied to the input signal In this case the bits that are shifted Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 3 regular outputs port 1 size 12 type 3 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2592 object discretetime state no name of computational function shift32LA Interfacing function SCImodulesscicosblocksmacrosIntegerOpSHIFTsci Computational function SCImodulesscicosblockssrccshift32LAc SCImodulesscicosblockssrccshift32LCc SCImodulesscicosblockssrccshift32RAc SCImodulesscicosblockssrccshiftu32RAc SCImodulesscicosblockssrccshift32RCc SCImodulesscicosblockssrccshift16LAc SCImodulesscicosblockssrccshift16LCc SCImodulesscicosblockssrccshift16RAc SCImodulesscicosblockssrccshiftu16RAc SCImodulesscicosblockssrccshift16RCc SCImodulesscicosblockssrccshift8LAc SCImodulesscicosblockssrccshift8LCc SCImodulesscicosblockssrccshift8RAc SCImodulesscicosblockssrccshiftu8RAc SCImodulesscicosblockssrccshift8RCc See also BITSET BITSET Set a Bit BITCLEAR BITCLEAR Clear a Bit Authors Fady NASSIF INRIA palettes 2593 Nome SRFLIPFLOP SR flipflop Block Screenshot Contents SR flipflop Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Integer palette Description This block describe the simplest and the most fundamental latch the SR flip flop Where S and R are the input and Q and Q are the outputsIf S Set is pulsed high while R is held low then the Q output is forced high and stays high when S returns low similarly if R Reset is pulsed high while S is held low then the Q output is forced low and stays low when R returns low When both are low Qt takes the same state as Qt1 When they are both high both Q and Q take the low values we are in an unstable state Practically we have to avoid this caseThis block is almost used with digital number the input data type is int8 The truth table of this block is S R Qt Qt 0 0 Qt1 Qt1 0 1 0 1 1 0 1 0 1 1 0 0 This case is to avoid palettes 2594 Dialog box Initial Value Initial Value of the state Q Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 5 port 2 size 11 type 5 regular outputs port 1 size 11 type 5 port 2 size 11 type 5 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosIntegerOpSRFLIPFLOPsci palettes 2595 Compiled Super Block content See also DLATCH D latch flipflop DFLIPFLOP D flipflop JKFLIPFLOP JK flipflop Authors Fady NASSIF INRIA 11 Lookup tables palette palettes 2596 Nome Lookuptablespal Lookup tables palette Block Screenshot Module xcos Description The lookup tables palette includes blocks that compute output approximations from inputs Blocks INTRP2BLKf 2D interpolation INTRPLBLKf Interpolation LOOKUPf Lookup table palettes 2597 Nome INTRP2BLKf 2D interpolation Block Screenshot Contents 2D interpolation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Lookup tables palette Description The output of this block is a function of the inputs obtained by bilinear interpolation This block has two scalar inputs and a single scalar output The and give respectively the coordinate and the coordinate of the th data point to be interpolated and its value Dialog box X coord an nvector strictly increasing palettes 2598 Properties Type vec of size 1 Y coord an mvector strictly increasing Properties Type vec of size 1 Z values an matrix Properties Type mat of size 11 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function intrp2 Interfacing function SCImodulesscicosblocksmacrosNonLinearINTRP2BLKfsci Computational function SCImodulesscicosblockssrcfortranintrp2f Type 1 Authors Ramine Nikoukhah INRIA palettes 2599 Nome INTRPLBLKf Interpolation Block Screenshot Contents Interpolation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Lookup tables palette Description The output of this block is a function of the input obtained by linear interpolation This block has a single scalar input and a single scalar output port The coord and coord give respectively the coordi nate and the coordinate of the data points to be interpolated coord must be strictly increasing Dialog box X coord A vector strictly increasing Properties Type vec of size 1 palettes 2600 Y coord A vector same size as coord Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function intrpl Interfacing function SCImodulesscicosblocksmacrosNonLinearINTRPLBLKfsci Computational function SCImodulesscicosblockssrcfortranintrplf Type 0 Authors Ramine Nikoukhah INRIA palettes 2601 Nome LOOKUPf Lookup table Block Screenshot Contents Lookup table Palette Description Default properties Interfacing function Computational function Authors Palette Lookup tables palette Description This block realizes a nonlinear function defined using a graphical editor Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2602 object discretetime state no name of computational function lookup Interfacing function SCImodulesscicosblocksmacrosNonLinearLOOKUPfsci Computational function SCImodulesscicosblockssrcfortranlookupf Type 0 Authors Ramine Nikoukhah INRIA 12 Math operations palette palettes 2603 Nome Mathoperationspal Math operations palette Block Screenshot Module xcos Description The Math operations palette contains blocks that model general mathematical functions Blocks ABSVALUE Absolute value BIGSOMf Sum COSBLKf Cosinus Block EXPBLKm Exponential GAINBLKf Gain INVBLK Inverse palettes 2604 LOGBLKf Common logarithm MATMAGPHI Complex to Magnitude and Angle Conversion MATZREIM Complex decomposition MAXf MAX MAXMIN Max and Min MINf MIN POWBLKf Array power PRODf Multiplication PRODUCT Product SIGNUM Signum SINBLKf Sinus block SQRT Square root SUMf Addition SUMMATION Summation TANBLKf Tangent block TrigFun Trigonometric function palettes 2605 Nome ABSVALUE Absolute value Block Screenshot Contents Absolute value Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Abs block outputs the absolute value of the input Dialog box use zerocrossing Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2606 zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function absolutevalue Interfacing function SCImodulesscicosblocksmacrosNonLinearABSVALUEsci Computational function SCImodulesscicosblockssrccabsolutevaluec Type 4 Authors Ramine Nikoukhah INRIA palettes 2607 Nome BIGSOMf Sum Block Screenshot Contents Sum Palette Description Dialog box Default properties Interfacing function Computational function Palette Math operations palette Description The Sum block performs addition on its inputs This block can add scalar or vector inputs Dialog box Inputs ports signsgain Set sign and a gain for each inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no palettes 2608 mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function sum Interfacing function SCImodulesscicosblocksmacrosLinearBIGSOMfsci Computational function SCImodulesscicosblockssrccsumc Type 2 palettes 2609 Nome COSBLKf COSBLK Block Screenshot Contents COSBLK Palette Description Default properties Interfacing function Palette Math operations palette Description Description Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2610 object discretetime state no name of computational function cosblk Interfacing function SCImodulesscicosblocksmacrosNonLinearCOSBLKfsci palettes 2611 Nome EXPBLKm Exponential Block Screenshot Contents Exponential Palette Description Dialog box Default properties Interfacing function Computational function Palette Math operations palette Description This block realizes The input and output port sizes are determined by the compiler Dialog box a A real positive scalar Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2612 zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function expblkm Interfacing function SCImodulesscicosblocksmacrosNonLinearEXPBLKmsci Computational function SCImodulesscicosblockssrccexpblkmc Type 4 palettes 2613 Nome GAINBLKf Gain Block Screenshot Contents Gain Palette Description Dialog box Default properties Interfacing function Authors Palette Math operations palette Description The GAINBLK computes the product of a square matrix A by the input matrix U where the number of rowscols of A is equal to the number of rows of U Dialog box Gain This parameter defined the square matrix A Properties Type mat of size 11 Default properties always active no directfeedthrough yes palettes 2614 zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gain Interfacing function SCImodulesscicosblocksmacrosLinearGAINBLKfsci Authors Ramine Nikoukhah INRIA palettes 2615 Nome INVBLK Inverse Block Screenshot Contents Inverse Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description This block computes The input output size is determined by the context Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no palettes 2616 name of computational function invblk4 Interfacing function SCImodulesscicosblocksmacrosNonLinearINVBLKsci Computational function SCImodulesscicosblockssrccinvblk4c Type 4 palettes 2617 Nome LOGBLKf Log Block Screenshot Contents Log Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description This block realizes The input and output port sizes are determined by the context Dialog box Basis A real scalar greater than 1 Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2618 zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function logblk Interfacing function SCImodulesscicosblocksmacrosNonLinearLOGBLKfsci Computational function SCImodulesscicosblockssrcfortranlogblkf Type 0 Authors Ramine Nikoukhah INRIA palettes 2619 Nome MATMAGPHI Complex to Magnitude and Angle Conversion Block Screenshot Contents Complex to Magnitude and Angle Conversion Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Math operations palette Description MATMAGPHI Block has two types of decomposotions When the type is set to one the block converts a complex number to the magnitude and the radian angle in this case the input is complex and the outputs are real double If the input is real double the angle will be zero or PI and the magnitude will be equal to the absolute of the input number When the type is set to two the block outputs a complex number given the magnitude and the radian angle In this case the inputs are real double and the output is complex Dialog box decomposition type 1Complex2MAGampPHI 2MAGampPHI2Complex It indicates the rule of the conversion palettes 2620 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 2 regular outputs port 1 size 12 type 1 port 2 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matzabs Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATMAGPHIsci Computational function SCImodulesscicosblockssrccmatzabsc SCImodulesscicosblockssrccmatzabscc See also MATZREIM Complex decomposition Authors Fady NASSIF INRIA palettes 2621 Nome MATZREIM Complex decomposition Block Screenshot Contents Complex decomposition Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Math operations palette Description This block decomposes a complex number by separating the real and imaginary parts or compose a complex number by joining the two parts The user can select even to separate or to join real and imaginary part by setting the decomposition type to 1 or 2 When it is set to 1 the input is a complex matrix and the outputs are the real and imaginary parts of the input When it set to 2 The inputs are two real matrices the output is a complex number with real part the first input and imaginary part the second input Dialog box decomposition type 1Complex2RealampImag 2RealampImag2Complex Indicates the type to use for the decomposition See the description part for more information Properties Type vec of size 1 palettes 2622 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 2 regular outputs port 1 size 12 type 1 port 2 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matzreim Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATZREIMsci Computational function SCImodulesscicosblockssrccmatzreimc SCImodulesscicosblockssrccmatzreimcc See also MATMAGPHI MATMAGPHI Complex to Magnitude and Angle Conversion Authors Fady NASSIF INRIA palettes 2623 Nome MAXMIN Max and Min Block Screenshot Contents Max and Min Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The MinMax block outputs either the minimum or the maximum element or elements of the inputs You can choose the function to apply by selecting one of the choices from the Function parameter list Dialog box Min or Max The function min or max to apply to the input Properties Type vec of size 1 Number of input vectors palettes 2624 The number of inputs to the block Properties Type vec of size 1 zerocrossing Select to enable zero crossing detection to detect minimum and maximum values Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function minmax Interfacing function SCImodulesscicosblocksmacrosNonLinearMAXMINsci Computational function SCImodulesscicosblockssrccminmaxc Type 4 Authors Ramine Nikoukhah INRIA palettes 2625 Nome MAXf MAX Block Screenshot Contents MAX Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description That block find the max value in the elements of its input vector Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no palettes 2626 name of computational function maxblk Interfacing function SCImodulesscicosblocksmacrosNonLinearMAXfsci Computational function SCImodulesscicosblockssrcfortranmaxblkf Type 0 palettes 2627 Nome MINf MIN Block Screenshot Contents MIN Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description That block find the min value in the elements of its input vector Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no palettes 2628 name of computational function minblk Interfacing function SCImodulesscicosblocksmacrosNonLinearMINfsci Computational function SCImodulesscicosblockssrcfortranminblkf Type 0 palettes 2629 Nome POWBLKf Power Block Screenshot Contents Power Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description This block realizes The input and output port sizes are determined by the compiler according to the connected blocks port sizes Dialog box to the power of real scalar Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2630 zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function powblk Interfacing function SCImodulesscicosblocksmacrosNonLinearPOWBLKfsci Computational function SCImodulesscicosblockssrcfortranpowblkf Type 0 Authors Ramine Nikoukhah INRIA palettes 2631 Nome PRODUCT Product Block Screenshot Contents Product Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Product block performs multiplication or division of its inputs This block produces outputs using either elementwise or matrix multiplication depending on the value of the Multiplication parameter You specify the operations with the Number of inputs parameter Multiply1 and divide 1 cha racters indicate the operations to be performed on the inputs Dialog box Number of inputs or sign vector Enter the number of inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2632 zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function product Interfacing function SCImodulesscicosblocksmacrosNonLinearPRODUCTsci Computational function SCImodulesscicosblockssrccproductc Type 4 Authors Ramine Nikoukhah INRIA palettes 2633 Nome PRODf Multiplication Block Screenshot Contents Multiplication Palette Description Default properties Interfacing function Computational function Authors Palette Math operations palette Description The output is the element wise product of the inputs Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no palettes 2634 discretetime state no object discretetime state no name of computational function prod Interfacing function SCImodulesscicosblocksmacrosNonLinearPRODfsci Computational function SCImodulesscicosblockssrccprodc Type 2 Authors Ramine Nikoukhah INRIA palettes 2635 Nome SIGNUM Signum Block Screenshot Contents Signum Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Sign block indicates the sign of the input The output is 1 when the input is greater than zero The output is 0 when the input is equal to zero The output is 1 when the input is less than zero Dialog box use zerocrossing Select to enable zero crossing detection Properties Type vec of size 1 palettes 2636 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function signum Interfacing function SCImodulesscicosblocksmacrosNonLinearSIGNUMsci Computational function SCImodulesscicosblockssrccsignumc Type 4 Authors Ramine Nikoukhah INRIA palettes 2637 Nome SINBLKf SINBLK Block Screenshot Contents SINBLK Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description Description Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no palettes 2638 discretetime state no object discretetime state no name of computational function sinblk Interfacing function SCImodulesscicosblocksmacrosNonLinearSINBLKfsci Computational function SCImodulesscicosblockssrcfortransinblkf Type 0 palettes 2639 Nome SQRT Square root Block Screenshot Contents Square root Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Math operations palette Description This block computes the square root of each element of the input matrix It supported real and complex data types Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Scicos will print the message Datatype is not supported Properties Type vec of size 1 Default properties always active no palettes 2640 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matsqrt Interfacing function SCImodulesscicosblocksmacrosMatrixOpSQRTsci Computational function SCImodulesscicosblockssrccmatsqrtc SCImodulesscicosblockssrccmatzsqrtc See also POWBLKf Pow Authors Fady NASSIF INRIA palettes 2641 Nome SUMMATION Matrix Summation Block Screenshot Contents Matrix Summation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Sum block performs addition or subtraction on its inputs This block can add or subtract scalar vector or matrix inputs It can also collapse the elements of a single input vector The number of inputs is given by the second parameter This parameter can be a vector of 1 and 1 or it can be a positive value In the first case the size of the vector indicates the number of inputs and the signs indicates whether it is a summation or a subtraction In the second case the block is a summation block and the value indicates the number of inputs On overflow the result can take different forms 1 A normal non saturated result 2 A saturated result 3 An error message warning the user about the overflow The user can select one of these three forms by setting the DO ON OVERFLOW field to 01 or 2 palettes 2642 Dialog box Datatype 1real double 2complex 3int32 It indicates the type of the inputoutput data It support all datatype number must be between 1 and 8 Properties Type vec of size 1 Number of inputs or sign vector of 1 1 It indicates the number of inputs and the operation see the description for more detail Properties Type vec of size 1 Do on Overflow0Nothing 1Saturate 2Error When this parameter is set to zero the result is similar to a normal summation of two integer matrix When it is set to 1 on overflow the block saturate the result When it is set to 2 on overflow an error message box appears If the Data type is double or complex this parameter is not used Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2643 object discretetime state no name of computational function summation Interfacing function SCImodulesscicosblocksmacrosLinearSUMMATIONsci Computational function SCImodulesscicosblockssrccsummationc SCImodulesscicosblockssrccsummationzc SCImodulesscicosblockssrccsummationi32nc SCImodulesscicosblockssrccsummationi16nc SCImodulesscicosblockssrccsummationi8nc SCImodulesscicosblockssrccsummationui32nc SCImodulesscicosblockssrccsummationui16nc SCImodulesscicosblockssrccsummationui8nc SCImodulesscicosblockssrccsummationi32sc SCImodulesscicosblockssrccsummationi16sc SCImodulesscicosblockssrccsummationi8sc SCImodulesscicosblockssrccsummationui32sc SCImodulesscicosblockssrccsummationui16sc SCImodulesscicosblockssrccsummationui8sc SCImodulesscicosblockssrccsummationi32ec SCImodulesscicosblockssrccsummationi16ec SCImodulesscicosblockssrccsummationi8ec SCImodulesscicosblockssrccsummationui32ec SCImodulesscicosblockssrccsummationui16ec SCImodulesscicosblockssrccsummationui8ec Authors Fady NASSIF INRIA Alan Layec INRIA Ramine Nikoukhah INRIA palettes 2644 Nome SUMf Addition Block Screenshot Contents Addition Palette Description Default properties Interfacing function Computational function Authors Palette Math operations palette Description The Sum block performs addition on its inputs This block can add scalar vector or matrix inputs Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 0 port 3 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 palettes 2645 continuoustime state no discretetime state no object discretetime state no name of computational function plusblk Interfacing function SCImodulesscicosblocksmacrosLinearSUMfsci Computational function SCImodulesscicosblockssrccplusblkc Type 2 Authors Ramine Nikoukhah INRIA palettes 2646 Nome TANBLKf TANBLK Block Screenshot Contents TANBLK Palette Description Default properties Interfacing function Computational function Palette Math operations palette Description Description Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no palettes 2647 discretetime state no object discretetime state no name of computational function tanblk Interfacing function SCImodulesscicosblocksmacrosNonLinearTANBLKfsci Computational function SCImodulesscicosblockssrcfortrantanblkf Type 0 palettes 2648 Nome TrigFun Trigonometric function Block Screenshot Contents Trigonometric function Palette Description Dialog box Default properties Interfacing function Computational function Palette Math operations palette Description The Trigonometric Function block performs numerous common trigonometric functions You can select one of these functions from the Function list sin cos tan asin acos atan atan2 sinh cosh and tanh The block output is the result of the operation of the function on the input or inputs Dialog box Function The trigonometric function Properties Type str of size 1 Default properties always active no palettes 2649 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function sinblk Interfacing function SCImodulesscicosblocksmacrosNonLinearTrigFunsci Computational function SCImodulesscicosblockssrccsinblkc Type 4 13 Matrix operation palette palettes 2650 Nome Matrixpal Matrix operation palette Block Screenshot Module xcos Description Matrix palette contains all blocks that you need to do simple and complex matrix operations Blocks CUMSUM CUMSUM Cumulative Sum EXTRACT EXTRACT Matrix Extractor EXTTRI EXTTRI Triangular or Diagonal extraction MATBKSL MATBKSLleft matrix division MATCATH MATCATH Horizontal Concatenation MATCATV MATCATV Vertical Concatenation palettes 2651 MATDET MATDET Matrix Determinant MATDIAG MATDIAG Create Diagonal Matrix MATDIV MATDIV Matrix division MATEIG MATEIG Matrix Eigenvalues MATEXPM MATEXPM Matrix Exponential MATINV MATINV Matrix Inverse MATLU MATLU LU Factorization MATMAGPHI MATMAGPHI Complex to Magnitude and Angle Conversion MATMUL MATMUL Matrix Multiplication MATPINV MATPINV Matrix PseudoInverse MATRESH MATRESH Matrix Reshape MATSING MATSING SVD decomposition MATSUM Matrix Sum MATTRAN Matrix Transpose MATZCONJ Matrix Conjugate MATZREIM Complex decomposition RICC RICC Equation de Riccati ROOTCOEF Coefficient computation SQRT SQRT Square root SUBMAT SUBMAT Submatrix extraction palettes 2652 Nome CUMSUM Cumulative Sum Block Screenshot Contents Cumulative Sum Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The CUMSUM block sums the element of an input mn matrix u along either the rows the columns or the first non singleton dimension When the Sum along parameter is set to 1 the block sums across the elements of each row The result will be displayed as a m1 matrix When the Sum along parameter is set to 2 the block sums across the elements of each column The result will be display as a 1n matrix When the Sum along parameter is set to 0 the block sums across the first non singleton dimension The result will be displayed as one element This block is equivalent to cumsum in scilab Dialog box palettes 2653 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Scicos will print the message Datatype is not supported Properties Type vec of size 1 Sum along 0the first non singleton dimension 1Rows 2Columns Indicate whether to sum across the rows the columns or the first non singleton dimension Properties Type vec of size 1 Example A1 2 34 5 67 8 9 If the sum is along the row the result will be B121518 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cumsumm Interfacing function SCImodulesscicosblocksmacrosMatrixOpCUMSUMsci Computational function SCImodulesscicosblockssrcccumsummc SCImodulesscicosblockssrcccumsumrc palettes 2654 SCImodulesscicosblockssrcccumsumcc SCImodulesscicosblockssrcccumsumzmc SCImodulesscicosblockssrcccumsumzrc SCImodulesscicosblockssrcccumsumzcc See also MATSUM Matrix Sum xcos Block Authors Fady NASSIF INRIA palettes 2655 Nome EXTRACT Matrix Extractor Block Screenshot Contents Matrix Extractor Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The EXTRACT block extracts some elements from the matrix The size of the output depends on the number of rows and number of columns to extract Dialog box Datatype 1real double 2Complex palettes 2656 It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 Lines to extract It indicates the numbers of the lines to extract Properties Type mat of size 11 Columns to extract It indicates the numbers of the columns to extract Properties Type mat of size 11 Example A1 2 34 5 67 8 9 If the Lines to extract is 1 and 2 and the Column to extract is 1 and 3 then the output is B1 34 6 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function extract Interfacing function SCImodulesscicosblocksmacrosMatrixOpEXTRACTsci Computational function SCImodulesscicosblockssrccextractc palettes 2657 SCImodulesscicosblockssrccextractzc See also EXTTRI EXTTRI Triangular or Diagonal extraction xcos Block Authors Fady NASSIF INRIA palettes 2658 Nome EXTTRI Triangular or Diagonal extraction Block Screenshot Contents Triangular or Diagonal extraction Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The EXTTRI block extracts some elements from the input matrix u When the Extraction type is set to 1 the block copies the elements on and above the main diagonal to an output matrix of the same size The elements below the main diagonal are set to zero When the Extraction type is set to 2 the block copies the elements on and below the main diagonal to an output matrix of the same size The elements above the main diagonal are set to zero When the Extraction type is set to 3 the block copies the elements on the main diagonal to an output matrix of the same size The elements above and below the main diagonal are set to zero palettes 2659 Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 extraction type 1lower 2upper 3diagonal It indicates the form of the output matrix It can be an upper triangle a lower triangle or a diagonal matrix Properties Type vec of size 1 Example A1 2 34 5 67 8 910 11 12 If the extraction type is 2 then the output is B1 0 04 5 07 8 910 11 12 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2660 object discretetime state no name of computational function extrilz Interfacing function SCImodulesscicosblocksmacrosMatrixOpEXTTRIsci Computational function SCImodulesscicosblockssrccexttrilc SCImodulesscicosblockssrccexttriuc SCImodulesscicosblockssrccextdiagc SCImodulesscicosblockssrccexttrilzc SCImodulesscicosblockssrccexttriuzc SCImodulesscicosblockssrccextdiagzc See also EXTRACT EXTRACT Matrix Extractor xcos Block Authors Fady NASSIF INRIA palettes 2661 Nome MATBKSL left matrix division Block Screenshot Contents left matrix division Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATBKSL block outputs the left matrix division It is a solution to AxB The higher input is the A matrix the lower one is the B matrix and the output is x If A is an MbyN1 matrix B must be a MbyN2 where N1 and N2 can be different or equal The output x is a N1byN2 matrix The equivalent of BACKSLASH is ïn Scilab Dialog box Datatype 1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported palettes 2662 Properties Type vec of size 1 Example A1 7 323 32 29 B21 1813 10 then the result of the AxB equation is AB x4504 39223643 31320000 0000 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 13 type 1 regular outputs port 1 size 23 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matbksl Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATBKSLsci Computational function SCImodulesscicosblockssrccmatbkslc SCImodulesscicosblockssrccmatzbkslc See also MATDIV MATDIV Matrix division xcos Block MATMUL MATMUL Matrix Multiplication xcos Block palettes 2663 Authors Fady NASSIF INRIA palettes 2664 Nome MATCATH Horizontal Concatenation Block Screenshot Contents Horizontal Concatenation Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATCATH Block outputs the horizontal concatenation of multiple matrices It is also called concatenation according to the columns The inputs U1U2Un must have the same number of rows The output is a MbyN1N2Nn matrix where N1N2Nn are the numbers of columns of the inputs matrices and M is the number of rows The equivalent of MATCATH in Scilab is yU1 U2 Un Dialog box palettes 2665 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 number of columns of each matrix It indicates the number of columns of the inputs matrices Properties Type mat of size 11 Example A1 2 34 5 6 B7 89 10 The result of the horizental concatenation is C1 2 3 7 84 5 6 9 10 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 13 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matcath Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATCATHsci Computational function SCImodulesscicosblockssrccmatcathc palettes 2666 SCImodulesscicosblockssrccmatzcathc See also MATCATV MATCATV Vertical Concatenation xcos Block Authors Fady NASSIF INRIA palettes 2667 Nome MATCATV Vertical Concatenation Block Screenshot Contents Vertical Concatenation Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATCATV Block outputs the vertical concatenation of multiple matrices It is also called con catenation according to the rows The inputs U1U2Un must have the same number of columns The output is a M1M2MnbyN matrix where M1M2Mn are the numbers of rows of the inputs matrices and N is the number of columns The equivalent of MATCATH in Scilab is yU1U2Un Dialog box palettes 2668 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 number of line of each matrix It indicates the number of rows of the inputs matrices Properties Type mat of size 11 Example A1 23 45 6 B7 89 10 The result of the horizental concatenation is C1 23 45 67 89 10 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 13 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matcatv Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATCATVsci Computational function SCImodulesscicosblockssrccmatcatvc palettes 2669 SCImodulesscicosblockssrccmatzcatvc See also MATCATH MATCATH Horizontal Concatenation xcos Block Authors Fady NASSIF INRIA palettes 2670 Nome MATDET Matrix Determinant Block Screenshot Contents Matrix Determinant Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATDET outputs the determinant of a square input matrix If the input AA11 A12 A13A21 A22 A23A31 A32 A33 then the output of the block has the form of yA11A22A33A23A32 A12A21A33A23A31A13A21A32A22A31 The equivalent of MATDET in Scilab is det Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported palettes 2671 Properties Type vec of size 1 Example U1 0 632 2 59 9 4 y2215 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matdet Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATDETsci Computational function SCImodulesscicosblockssrccmatdetc SCImodulesscicosblockssrccmatzdetc See also MATINV MATINV Matrix Inverse xcos Block Authors Fady NASSIF INRIA palettes 2672 Nome MATDIAG Create Diagonal Matrix Block Screenshot Contents Create Diagonal Matrix Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATDIAG block create a diagonal matrix from a 1D vector If the input is a Mby1 vector than the output is an MbyM matrix Dialog box Datatype 1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 palettes 2673 Example if the input of the block is Uones51 then the output is y1 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matdiag Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATDIAGsci Computational function SCImodulesscicosblockssrccmatdiagc SCImodulesscicosblockssrccmatzdiagc See also EXTTRI EXTTRI Triangular or Diagonal extraction xcos Block Authors Fady NASSIF INRIA palettes 2674 Nome MATDIV Matrix division Block Screenshot Contents Matrix division Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATDIV block outputs the right matrix division It is a solution to xBA The higher input is the A matrix the lower one is the B matrix and the output is x If A is an M1byN matrix B must be a M2byN where M1 and M2 can be different or equal The output x is a M1byM2 matrix The equivalent of BACKSLASH is in Scilab Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Xcos will print the message Datatype is not supported palettes 2675 Properties Type vec of size 1 Example A1 7 323 32 29 B21 18 3413 10 1911 54 36 then the result of the xBA equation is AB x0475 0712 01564350 8381 0491 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 13 type 1 port 2 size 23 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matdiv Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATDIVsci Computational function SCImodulesscicosblockssrccmatdivc SCImodulesscicosblockssrccmatzdivc See also MATBKSL MATBKSLleft matrix division MATMUL MATMUL Matrix Multiplication palettes 2676 Authors Fady NASSIF INRIA palettes 2677 Nome MATEIG Matrix Eigenvalues Block Screenshot Contents Matrix Eigenvalues Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATEIG calculate the eigenvalues and the eigenvectors of a square input matrix U When the Decomposition type is set to 1 the block outputs the eigenvalues in a vector form if the input is a MbyM matrix the output is a Mby1 vector When the Decomposition type is set to 2 the block outputs two matrices for an MbyM input matrixthe first output is a MbyM diagonal matrix composed by the eigenvalues and the second is a MbyM matrices composed by the eigenvectors the eigenvectors are represented by the columns of the matrix The equivalent of the MATEIG block in Scilab is specA Dialog box palettes 2678 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 decomposition type 1eig values 2eig valueseig vectors To select the form of the output Properties Type vec of size 1 Example A1 12 3221 35 4670 8 19 When the Decomposition type is set to one the output is y356491427976369 When the Decomposition type is set to two the outputs are y135649 0000 00000000 14279 00000000 0000 76369 y20557 0080 03490330 0922 07700762 0379 0533 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 2 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matvps Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATEIGsci Computational function SCImodulesscicosblockssrccmatvpsc palettes 2679 SCImodulesscicosblockssrccmatvpvc SCImodulesscicosblockssrccmatzvpsc SCImodulesscicosblockssrccmatzvpvc See also MATSING MATSING SVD decomposition xcos Block Authors Fady NASSIF INRIA palettes 2680 Nome MATEXPM Matrix Exponential Block Screenshot Contents Matrix Exponential Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATEXPM outputs the matrix exponential of a square matrix input by the pades approximants The output is a square matrix with the same size of the input The equivalent of this block in Scilab is expm Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported palettes 2681 Properties Type vec of size 1 Example u1 2 32 3 14 2 1 y182612 196518 141735172973 190770 133577204677 220063 159067 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matexpm Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATEXPMsci Computational function SCImodulesscicosblockssrccmatexpmc SCImodulesscicosblockssrccmatzexpmc See also MATMUL MATMUL Matrix Multiplication xcos Block Authors Fady NASSIF INRIA palettes 2682 Nome MATINV Matrix Inverse Block Screenshot Contents Matrix Inverse Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATINV Block outputs the inverse of a square input matrix using the LU factorization A warning message is printed if the input is badly scaled or nearly singular The equivalent function of this block in Scilab is inv Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 palettes 2683 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matinv Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATINVsci Computational function SCImodulesscicosblockssrccmatinvc SCImodulesscicosblockssrccmatzinvc See also MATLU MATLU LU Factorization xcos Block MATPINV MATPINV Matrix PseudoInverse xcos Block Authors Fady NASSIF INRIA palettes 2684 Nome MATLU LU Factorization Block Screenshot Contents LU Factorization Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATLU Block outputs two matrices L and U with row pivoting from the LU factorization of a square input matrix If A is the input matrix then EALU where E is the permutation matrixThe equivalent function of this block in Scilab is lueluA Dialog box Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 palettes 2685 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matlu Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATLUsci Computational function SCImodulesscicosblockssrccmatluc SCImodulesscicosblockssrccmatzluc See also MATINV MATINV Matrix Inverse xcos Block Authors Fady NASSIF INRIA palettes 2686 Nome MATMUL Matrix Multiplication Block Screenshot Contents Matrix Multiplication Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATMUL block computes the matrix multiplication of two inputs matricesThe number of rows of the second matrix must be equal to the number of columns of the first matrix The output is a matrix where the number of rows is equal to that of the first input matrix and the number of columns is equal to that of the second input matrix Dialog box Datatype1real double 2Complex palettes 2687 It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 Multiplication rule 1 2 Properties Type vec of size 1 Example A1 2 34 5 6 B9 8 7 65 4 3 29 7 5 3 y46 37 28 19115 94 73 52 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 23 type 1 regular outputs port 1 size 13 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matmulm Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATMULsci Computational function SCImodulesscicosblockssrccmatmulmc SCImodulesscicosblockssrccmatzmulmc palettes 2688 SCImodulesscicosblockssrccmatmul2mc SCImodulesscicosblockssrccmatzmul2mc See also INTMUL INTMUL integer matrix multiplication xcos Block MATDIV MATDIV Matrix division Scicos Block MATBKSL MATBKSLleft matrix division xcos Block MATEXPM MATEXPM Matrix Exponential xcos Block SUMMATION SUMMATION Matrix Summation xcos Block Authors Fady NASSIF INRIA Alan Layec INRIA palettes 2689 Nome MATPINV Matrix PseudoInverse Block Screenshot Contents Matrix PseudoInverse Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATPINV Block outputs the inverse of a non square input matrix using the SVD theoryif the SVD decomposition of A is equal to AUSV The pseudoinverse x of A is given by XVSU where Sij1Sij if Sij 0 U and V are respectively the transpose of U and V and we have AXAA and XAXX Both AX and XA are Hermitian A warning message is printed if the input is badly scaled or nearly singular When the input is a MbyN matrix the output is a NbyM matrix The equivalent function of this block in Scilab is pinv Dialog box palettes 2690 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matpinv Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATPINVsci Computational function SCImodulesscicosblockssrccmatpinvc SCImodulesscicosblockssrccmatzpinvc See also MATINV MATINV Matrix Inverse xcos Block MATSING MATSING SVD decomposition xcos Block Authors Fady NASSIF INRIA palettes 2691 Nome MATRESH Matrix Reshape Block Screenshot Contents Matrix Reshape Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The RESHAPE block changes the dimensions of a matrix or a vector to another dimensions specified by the user in the output size desired label The output size must be less or equal to the input size Dialog box Datatype1real double 2Complex palettes 2692 It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 input size It indicates the size of the input matrix Properties Type vec of size 1 output size desired It indicates the desired outputs size Properties Type vec of size 1 Example u1 2 3 45 6 7 8 When the output desired is 16 the output is y1 2 3 4 5 6 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matreshape Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATRESHsci Computational function SCImodulesscicosblockssrccmatreshapec palettes 2693 SCImodulesscicosblockssrccmatzreshapec See also EXTRACT EXTRACT Matrix Extractor xcos Block Authors Fady NASSIF INRIA palettes 2694 Nome MATSING SVD decomposition Block Screenshot Contents SVD decomposition Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATSING block computes the economy sized SVD of the MbyN input matrix A by finding US and V such that AUSV When the decomposition type is set to one the output is a vector composed by the singular values When the decomposition type is set to two we have three outputs the second output is a diagonal matrix S composed by the singular values and the other two outputs are the unitary matrices U and V The equivalent function of this block in Scilab is svd Dialog box palettes 2695 Datatype1real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 decomposition type 1singular values 2sing valuesmatrix U amp V It indicates the form of the output When it is set to one we have a unique vector output singular values When it is set to two we have three same sizes matricesUSV Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matsing Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATSINGsci Computational function SCImodulesscicosblockssrccmatsingc SCImodulesscicosblockssrccmatsvdc SCImodulesscicosblockssrccmatzsingc SCImodulesscicosblockssrccmatzsvdc See also MATEIG MATEIG Matrix Eigenvalues xcos Block palettes 2696 MATLU MATLU LU Factorization xcos Block Authors Fady NASSIF INRIA palettes 2697 Nome MATSUM Matrix Sum Block Screenshot Contents Matrix Sum Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description The MATSUM block returns the sum of the element of an input matrixvector When the Sum along is set to all the block outputs the sum of all the elements of the matrix The output is then a scalar When the Sum along is set to lines the block is a rowwise sum The output is a row vector When the Sum along is set to Columns the block is a columnwise sum The output is a column vector The equivalent function of this block in Scilab is sum Dialog box Datatype1real double 2Complex palettes 2698 It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported Properties Type vec of size 1 Sum along 0all 1lines 2Columns Indicates the used rule to sum For more information see the description part Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function matsum Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATSUMsci Computational function SCImodulesscicosblockssrccmatsumc SCImodulesscicosblockssrccmatsumlc SCImodulesscicosblockssrccmatsumcc SCImodulesscicosblockssrccmatzsumc SCImodulesscicosblockssrccmatzsumlc SCImodulesscicosblockssrccmatzsumcc See also SUBMAT SUBMAT Submatrix extraction xcos Block palettes 2699 SUMMATION SUMMATION Matrix Summation xcos Block Authors Fady NASSIF INRIA palettes 2700 Nome MATTRAN Matrix Transpose Block Screenshot Contents Matrix Transpose Palette Description Dialog box Example Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description This Block transposes an MxN matrix to a NxM matrix For complex data type it uses the hermitian transpose The equivalent of this block in Scilab is yu Dialog box Datatype1real double 2Complex It indicates the data type of the output It support only the two types double 1 and complex 2 If we input another entry in this label xcos will print the message Datatype is not supported palettes 2701 Properties Type vec of size 1 Example Complex 1i 23i 32i Tranpose 1 i 4 i 4i 58i 62i 23i 58i 32i 62i Real 1 2 3 Tranpose 1 4 4 5 6 2 5 3 6 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function mattranm Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATTRANsci Computational function SCImodulesscicosblockssrccmattranmc SCImodulesscicosblockssrccmatztranmc palettes 2702 See also Matrixpal Matrix operation palette xcos Palette Authors Fady NASSIF INRIA Alan Layec INRIA palettes 2703 Nome MATZCONJ Matrix Conjugate Block Screenshot Contents Matrix Conjugate Palette Description Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description This blocks computes the conjugate of a complex input matrix Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 2 regular outputs port 1 size 12 type 2 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no palettes 2704 discretetime state no object discretetime state no name of computational function matzconj Interfacing function SCImodulesscicosblocksmacrosMatrixOpMATZCONJsci Computational function SCImodulesscicosblockssrccmatzconjc See also Matrixpal Matrix operation palette xcos Palette Authors Fady NASSIF INRIA palettes 2705 Nome RICC Riccati Equation Block Screenshot Contents Riccati Equation Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Matrix operation palette Description This block computes the solution of Riccati equation using different method and for both case conti nuous and discrete The Riccati equation in continuous time is AXXACXDX0 The Riccati equation in discrete time is AXinvInDAXC0 where A is an NxN matrix it is the first input of the block C and D are two NxN symmetrics matrices and are respectively the second and third input of the RICC block X represent the output of the block it is also a NxN matrix The user can choose between two methods of computation For the continuous time he can use even the Schur method or the matrix sign function approach method by setting the Model parameter to 1 or 2 For the discrete time the models are the Schur method and the inverse free spectral decomposition method palettes 2706 Dialog box Type 1Cont 2Disc For continuous time signal set this parameter to 1 For discrete input time set it to 2 Properties Type vec of size 1 Model1Schr 2signcont invdisc To use the Shur method in computation set this parameter to 1 To use matrix sign function appro ach in continuous case or the inverse free spectral decomposition method in discrete case set this parameter to 2 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 port 3 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function riccm palettes 2707 Interfacing function SCImodulesscicosblocksmacrosMatrixOpRICCsci Computational function SCImodulesscicosblockssrccriccmc See also Matrixpal Matrix operation palette xcos Palette Authors Fady NASSIF INRIA palettes 2708 Nome ROOTCOEF Coefficient computation Block Screenshot Contents Coefficient computation Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Matrix operation palette Description This block computes the coefficients of a polynomial given its root values Dialog box Datatype1real double 2Complex This block can only support double inputs values These values can be real or complex Properties Type vec of size 1 input row size The input row size palettes 2709 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function rootcoef Interfacing function SCImodulesscicosblocksmacrosMatrixOpROOTCOEFsci Computational function SCImodulesscicosblockssrccrootcoefc SCImodulesscicosblockssrccrootzcoefc Authors Fady NASSIF INRIA palettes 2710 Nome SUBMAT Submatrix extraction Block Screenshot Contents Submatrix extraction Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Matrix operation palette Description This block outputs a sub matrix of the input matrix The output matrix will be defining by using the parameters of this block Dialog box palettes 2711 Datatype 1real double 2Complex Type of the output matrix It can be double or complex Properties Type vec of size 1 Starting Row Index The first row of the submatrix Properties Type vec of size 1 Ending Row Index The last row of the Submatrix Properties Type vec of size 1 Starting Column Index The first column of the submatrix Properties Type vec of size 1 Ending Column Index The last row of the submatrix Properties Type vec of size 1 Input Dimension The Matrix input dimensions Properties Type vec of size 2 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no palettes 2712 name of computational function submat Interfacing function SCImodulesscicosblocksmacrosMatrixOpSUBMATsci Computational function SCImodulesscicosblockssrccsubmatc SCImodulesscicosblockssrccsubmatzc Authors Fady NASSIF INRIA 14 Port Subsystem palette palettes 2713 Nome Portactionpal Port Subsystem palette Block Screenshot Module xcos Description The Port Subsystem palette includes blocks for creating subsystems Blocks CLKINVf Input activation port EventSelect CLKOUTVf Output activation port EventSelect INf Input Port INIMPLf Input implicit port OUTIMPLf Output implicit port OUTf Output Port SUPERf Super block palettes 2714 Nome INf Input Port Block Screenshot Contents Input Port Palette Description Dialog box Default properties Interfacing function Authors Palette Port Subsystem palette Description This block must only be used inside xcos Super Blocks to represent a regular input port The input size is determined by the context In a Super Block regular input ports must be numbered from 1 to the number of regular input ports Dialog box Port number an integer defining the port number Properties Type vec of size 1 Default properties always active no directfeedthrough no palettes 2715 zerocrossing no mode no regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function input Interfacing function SCImodulesscicosblocksmacrosSourcesINfsci Authors Ramine Nikoukhah INRIA palettes 2716 Nome OUTIMPLf Output implicit port Block Screenshot Contents Output implicit port Palette Description Dialog box Default properties Interfacing function Authors Palette Port Subsystem palette Description Outport blocks are the links from a system to a destination outside the system Dialog box Port number Specify the port number of the Outport block Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no palettes 2717 mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function outimpl Interfacing function SCImodulesscicosblocksmacrosSinksOUTIMPLfsci Authors Ramine Nikoukhah INRIA palettes 2718 Nome OUTf Output Port Block Screenshot Contents Output Port Palette Description Dialog box Default properties Interfacing function Authors Palette Port Subsystem palette Description This block must only be used inside Xcos Super Blocks to represent a regular output port In a Super Block regular output ports must be numbered from 1 to the number of regular output ports Size of the output is determined by the compiler according to the connected blocks port sizes Dialog box Port number an integer defining the port number Properties Type vec of size 1 Default properties always active no directfeedthrough no palettes 2719 zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function output Interfacing function SCImodulesscicosblocksmacrosSinksOUTfsci Authors Ramine Nikoukhah INRIA 15 Signal processing palette palettes 2720 Nome Signalprocessingpal Signal processing palette Block Screenshot Module xcos Description The signal processing palette contains blocks designed specifically for signal processing applications Blocks MCLOCKf MFCLCKf QUANTf Quantization SAMPHOLDm Sample and hold palettes 2721 Nome QUANTf Quantization Block Screenshot Contents Quantization Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal processing palette Description This block outputs the quantization of the input according to a choice of methods Dialog box Step scalar Quantization step Properties Type vec of size 1 Quantization Type scalar with possible values 123 or 4 Properties Type vec of size 1 palettes 2722 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function qzrnd Interfacing function SCImodulesscicosblocksmacrosNonLinearQUANTfsci Computational function SCImodulesscicosblockssrcfortranqzrndf SCImodulesscicosblockssrcfortranqztrnf SCImodulesscicosblockssrcfortranqzflrf SCImodulesscicosblockssrcfortranqzcelf Authors Ramine Nikoukhah INRIA palettes 2723 Nome SAMPHOLDm Sample and hold Block Screenshot Contents Sample and hold Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal Processing palette Description Each time an input event is received block copy its input on the output and hold it until input event For periodic Sample and hold event input must be generated by a Clock Dialog box Datatype1real double 2Complex 3int32 Output datatype This block can support all data types Properties Type vec of size 1 Default properties always active no directfeedthrough yes palettes 2724 zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function samphold4m Interfacing function SCImodulesscicosblocksmacrosLinearSAMPHOLDmsci Computational function SCImodulesscicosblockssrccsamphold4mc Type 4 Authors Fady NASSIF INRIA 16 Signal routing palette palettes 2725 Nome Signalroutingpal Signal routing palette Block Screenshot Module xcos Description The Signal routing palette includes blocks that transport signals from one point in a block diagram to another Blocks DEMUX Demultiplexer EXTRACTOR Extractor FROM FROM Receives data from a corresponding GOTO FROMMO Receives data from a corresponding GOTOMO GOTO GOTO Pass block input to From block GOTOMO Pass block input to FROMMO block GotoTagVisibility Define Scope of GOTO tag visibility GotoTagVisibilityMO Define Scope of GOTOMO tag visibility ISELECTm Iselect palettes 2726 MUX Multiplexer MSWITCH Multiport switch NRMSOMf Merge data RELAYf Relay SELECTm Select SWITCH2m Switch2 SWITCHf Switch palettes 2727 Nome DEMUX Demultiplexer Block Screenshot Contents Demultiplexer Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description Given a vector valued input this block splits inputs over vector valued outputs So where are numbered from top to bottom Input and Output port sizes are determined by the context Dialog box number of output ports or vector of sizes positive integer less than or equal to Properties Type vec of size 1 Default properties always active no palettes 2728 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 01 type 1 regular outputs port 1 size 11 type 1 port 2 size 21 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function multiplex Interfacing function SCImodulesscicosblocksmacrosBranchingDEMUXsci Computational function SCImodulesscicosblockssrccmultiplexc Type 4 Authors Ramine Nikoukhah INRIA palettes 2729 Nome EXTRACTOR Extractor Block Screenshot Contents Extractor Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description Extracts or select a regular input from a multiple regular input Dialog box indices to extract a regular input to be extracted from the multiple regular inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no palettes 2730 mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function extractor Interfacing function SCImodulesscicosblocksmacrosBranchingEXTRACTORsci Computational function SCImodulesscicosblockssrccextractorc Type 4 Authors Ramine Nikoukhah INRIA palettes 2731 Nome FROM FROM Receives data from a corresponding GOTO Block Screenshot Contents FROM Receives data from a corresponding GOTO Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal routing palette Description The main role of the GOTOFROM blocks is to transport signals from a block to another block without connecting them physically The FROM block transports its received data from the corresponding GOTO to its output Multiples FROM blocks can receive data from one GOTO although a GOTO can send data to multiple FROM The GOTO and FROM blocks are connected by the tag parameter For information on the visibility and limitation of these blocks please refer to the GOTO documen tation This block can support all the data types Dialog box palettes 2732 Tag The tag of the GOTO block passing the signal to this FROM block Properties Type str of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function from Interfacing function SCImodulesscicosblocksmacrosBranchingFROMsci See also GOTO GOTO Pass block input to From block GotoTagVisibility Define Scope of GOTO tag visibility Authors Fady NASSIF INRIA palettes 2733 Nome FROMMO Receives data from a corresponding GOTOMO Block Screenshot Contents Receives data from a corresponding GOTOMO Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal Routing palette Description This block is used to connect Modelica blocks For more information on how it works please refer to the documentation of the FROM block by clicking on the link in the See also field Dialog box Tag The tag of the GOTOMO block passing the signal to this FROMMO block Properties Type str of size 1 Default properties always active no palettes 2734 directfeedthrough no zerocrossing no mode no regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function frommo Interfacing function SCImodulesscicosblocksmacrosBranchingFROMMOsci See also FROM FROM Receives data from a corresponding GOTO xcos Block Authors Fady NASSIF INRIA palettes 2735 Nome GOTO GOTO Pass block input to From block Block Screenshot Contents GOTO Pass block input to From block Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal routing palette Description The main role of the GOTOFROM blocks is to transport signals from a block to another block without connecting them physically The GOTO block transports its input data to its corresponding FROM block A simple GOTO block can send data to multiple FROM although a FROM can receive data from only one GOTO The GOTO and FROM blocks are connected by the tag parameter The Tag Visibility parameter indicates if the location of the FROM block is limited Local means that the corresponding FROM of that GOTO must be in the same subsystem Scoped means that the corresponding FROM of that GOTO must be in the same subsystem or in any subsystem below the GotoTagVisibility block in the model hierarchy Global means that the corresponding FROM of that GOTO can be anywhere in the model This block can support all the data types palettes 2736 Dialog box Tag This parameter identifies the Goto block whose scope is defined in this block Properties Type str of size 1 Tag Visibility1Local 2scoped 3 global This parameter identifies the visibility of the block It can be local1 scoped2 or global3 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function goto Interfacing function SCImodulesscicosblocksmacrosBranchingGOTOsci See also FROM FROM Receives data from a corresponding GOTO GotoTagVisibility Define Scope of GOTO tag visibility palettes 2737 Authors Fady NASSIF INRIA palettes 2738 Nome GOTOMO Pass block input to FROMMO block Block Screenshot Contents Pass block input to FROMMO block Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal Routing palette Description This block is used to connect Modelica blocks For more information on how it works please refer to the documentation of the GOTO block by clicking on the link in the See also field Dialog box Tag This parameter identifies the Goto block whose scope is defined in this block Properties Type str of size 1 Tag Visibility1Local 2scoped 3 global This parameter identifies the visibility of the block It can be local1 scoped2 or global3 palettes 2739 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gotomo Interfacing function SCImodulesscicosblocksmacrosBranchingGOTOMOsci See also GOTO GOTO Pass block input to From block xcos Block Authors Fady NASSIF INRIA palettes 2740 Nome GotoTagVisibility Define Scope of GOTO tag visibility Block Screenshot Contents Define Scope of GOTO tag visibility Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal routing palette Description This block defines the accessibility of the GOTO block when it is configure as scoped The FROM block corresponding to that GOTO must be in the same subsystem of the GotoTagVisibility or in subsystems below it in the model hierarchy Dialog box GotoTag The Goto block tag whose visibility is defined by the location of this block Properties Type str of size 1 Default properties always active no palettes 2741 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gototagvisibility Interfacing function SCImodulesscicosblocksmacrosBranchingGotoTagVisibilitysci See also GOTO GOTO Pass block input to From block FROM FROM Receives data from a corresponding GOTO Authors Fady NASSIF INRIA palettes 2742 Nome GotoTagVisibilityMO Define Scope of GOTOMO tag visibility Block Screenshot Contents Define Scope of GOTOMO tag visibility Palette Description Dialog box Default properties Interfacing function See also Authors Palette Signal Routing palette Description This block is used in case of Modelica connection For more information on how it works please refer to the GotoTagVisibility block by clicking on the link in the See also field Dialog box GotoTag The Goto block tag whose visibility is defined by the location of this block Properties Type str of size 1 Default properties always active no palettes 2743 directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gototagvisibilitymo Interfacing function SCImodulesscicosblocksmacrosBranchingGotoTagVisibilityMOsci See also GotoTagVisibility Define Scope of GOTO tag visibility xcos Block Authors Fady NASSIF INRIA palettes 2744 Nome ISELECTm Iselect Block Screenshot Contents Iselect Palette Description Dialog box Default properties Interfacing function Computational function Palette Signal routing palette Description Select signals from an incoming events This block has one regular input port Dialog box Datatype1 real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Xcos will print the message Datatype is not supported Properties Type vec of size 1 number of outputs a scalar Number of regular and event outputs palettes 2745 Properties Type vec of size 1 initial connected output an integer It must be between 1 and the number of inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 regular outputs port 1 size 12 type 1 port 2 size 12 type 1 numbersizes of activation inputs 2 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function selectorm Interfacing function SCImodulesscicosblocksmacrosBranchingISELECTmsci Computational function SCImodulesscicosblockssrccselectormc Type 4 palettes 2746 Nome MUX Multiplexer Block Screenshot Contents Multiplexer Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description Given vector valued inputs this block merges inputs in an single output vector So where are numbered from top to bottom Input and Output port sizes are determined by the context Dialog box number of input ports or vector of sizes integer greater than or equal to 1 and less than 8 Properties Type vec of size 1 Default properties always active no palettes 2747 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 21 type 1 regular outputs port 1 size 01 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function multiplex Interfacing function SCImodulesscicosblocksmacrosBranchingMUXsci Computational function SCImodulesscicosblockssrccmultiplexc Type 4 Authors Ramine Nikoukhah INRIA palettes 2748 Nome MSWITCH Multiport switch Block Screenshot Contents Multiport switch Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description The MultiPort Switch block chooses between a number of inputs The first top input is called the control input while the rest of the inputs are called data inputs The value of the control input deter mines which data input is passed through to the output port Dialog box number of inputs Specify the number of data inputs to the block Properties Type vec of size 1 zero base indexing palettes 2749 If selected the block uses zerobased indexing Otherwise the block uses onebased indexing Properties Type vec of size 1 rounding rule int Select the rounding mode for the output Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 0 port 3 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function mswitch Interfacing function SCImodulesscicosblocksmacrosBranchingMSWITCHsci Computational function SCImodulesscicosblockssrccmswitchc Type 4 Authors Ramine Nikoukhah INRIA palettes 2750 Nome NRMSOMf Merge data Block Screenshot Contents Merge data Palette Description Dialog box Default properties Interfacing function Authors Palette Signal routing palette Description The Merge block combines its inputs into a single output line whose value at any time is equal to the most recently computed output of its driving blocks You can specify any number of inputs by setting the blocks Number of inputs parameter Dialog box number of inputs The number of input ports to be merged Properties Type vec of size 1 Default properties always active no palettes 2751 directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function junk Interfacing function SCImodulesscicosblocksmacrosBranchingNRMSOMfsci Authors Ramine Nikoukhah INRIA palettes 2752 Nome RELAYf Relay Block Screenshot Contents Relay Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description This block routes one of the regular inputs to the unique regular output the choice of which input is to be routed is done initially by the initial connected input parameter Then every time an input event arrives on the ith input event port the ith regular input port is routed to the regular output Dialog box number of inputs a scalar Number of regular and event inputs Properties Type vec of size 1 palettes 2753 initial connected input an integer It must be between 1 and the number of inputs Properties Type vec of size 1 Default properties always active yes directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 2 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function relay Interfacing function SCImodulesscicosblocksmacrosBranchingRELAYfsci Computational function SCImodulesscicosblockssrccrelayc Type 2 Authors Ramine Nikoukhah INRIA palettes 2754 Nome SELECTm Select Block Screenshot Contents Select Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description A Selector block accepts either vector or matrix signals as input Set the Input Type parameter to the type of signal vector or matrix that the block should accept in your model The parameter dialog box and the blocks appearance change to reflect the type of input that you select The way the block determines the elements to select differs slightly depending on the type of input Dialog box Datatype1 real double 2Complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Xcos will print the message Datatype is not supported Properties Type vec of size 1 palettes 2755 number of inputs a scalar Number of regular and event inputs Properties Type vec of size 1 initial connected input an integer It must be between 1 and the number of inputs Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 port 2 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 2 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function selectorm Interfacing function SCImodulesscicosblocksmacrosBranchingSELECTmsci Computational function SCImodulesscicosblockssrccselectormc Type 4 Authors Fady NASSIF INRIA Ramine Nikoukhah INRIA palettes 2756 Nome SWITCH2m Switch2 Block Screenshot Contents Switch2 Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description The Switch block passes through the first top input or the third bottom input based on the value of the second middle input The first and third inputs are called data inputs The second input is called the control input You select the conditions under which the first input is passed with the Criteria for passing first input parameter You can make the block check whether the control input is greater than or equal to the threshold value purely greater than the threshold value or nonzero If the control input meets the condition set in the Criteria for passing first input parameter then the first input is passed Otherwise the third input is passed Dialog box palettes 2757 Datatype1 real double 2Complex a scalar Give the datatype of the inputsoutput Properties Type vec of size 1 pass first input if u2 a Select the conditions under which the first input is passed You can make the block check whether the control input is greater than or equal to the threshold value purely greater than the threshold value or nonzero If the control input meets the condition set in this parameter then the first input is passed Otherwise the third input is passed Properties Type vec of size 1 threshold a Assign the switch threshold that determines which input is passed to the output Properties Type vec of size 1 use zero crossing yes Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 12 type 1 port 2 size 11 type 0 port 3 size 12 type 1 regular outputs port 1 size 12 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function switch2m palettes 2758 Interfacing function SCImodulesscicosblocksmacrosBranchingSWITCH2msci Computational function SCImodulesscicosblockssrccswitch2mc Type 4 Authors Fady NASSIF INRIA Ramine Nikoukhah INRIA palettes 2759 Nome SWITCHf Switch Block Screenshot Contents Switch Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Signal routing palette Description This is a Manual Switch block It selects one of its inputs to pass through to the output The selected input is propagated to the output while the unselected inputs are discarded Dialog box number of inputs Specify the number of data inputs to the block Properties Type vec of size 1 connected input an integer It must be between 1 and the number of inputs palettes 2760 Properties Type vec of size 1 Default properties always active yes directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function switchn Interfacing function SCImodulesscicosblocksmacrosBranchingSWITCHfsci Computational function SCImodulesscicosblockssrccswitchnc Type 2 Authors Ramine Nikoukhah INRIA 17 Sinks palette palettes 2761 Nome Sinkspal Sinks palette Block Screenshot Module xcos Description In Sinks palette you can find a variety of blocks used to display Scope and write data during simu lation and also some output ports used in superblocks The blocks of that palette doesnt have regular output ports Blocks AFFICHm Display CANIMXY yfx animated viewer CANIMXY3D zfxy animated viewer CFSCOPE Floating point scope CLKOUTVf Output activation port CMAT3D Matrix z values 3D viewer CMATVIEW Matrix Colormapped viewer CMSCOPE Multi display scope CSCOPE Single Display Scope CSCOPXY yfx permanent viewer CSCOPXY3D zfxy permanent viewer ENDBLK END block viewer palettes 2762 ENDc ENDc block viewer HALTf Halt block viewer OUTIMPLf Output implicit port viewer OUTf Output port viewer TOWSc Data to Scilab worspace TRASHf Trash block WFILEf Write to file WRITEAUf Write AU sound file Write binary data palettes 2763 Nome AFFICHm Display Block Screenshot Contents Display Palette Description Dialog box Default properties Interfacing function Computational function Palette Sinks palette Description This block displays the value of its unique input inside the block in the diagram during simulation Dialog box palettes 2764 Input Size Explicitly define the size of the input port Properties Type mat of size 12 Font number integer the selected font number see xset Properties Type vec of size 1 Font size integer the selected font size set xset Properties Type vec of size 1 Color integer the selected color for the text see xset Properties Type vec of size 1 Total number of digits an integer greater than 3 the maximum number of digits used to represent the number sign integer part and rational part Properties Type vec of size 1 Number of rational part digits n integer greater than or equal 0 the number of digits used to represent the rational part Properties Type vec of size 1 Block inherits Options to choose event inheritance from regular input or from explicit event input 0 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no palettes 2765 discretetime state yes object discretetime state no name of computational function affich2 Interfacing function SCImodulesscicosblocksmacrosSinksAFFICHmsci Computational function SCImodulesscicosblockssrcfortranaffich2f Type 0 palettes 2766 Nome CANIMXY yfx animated viewer Block Screenshot Contents yfx animated viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description This block realizes the visualization of the evolution of the two regular input signals by drawing the second input as a function of the first at instants of events on the event input port When a point is drawn on screen it stays until the buffer length is reached This scope is useful to make simple animations palettes 2767 Dialog box Number of Curves Set the number of curves Properties Type vec of size 1 color an integer It is the color number or marker type used to draw the evolution of the input port signal Seexset for color dash type definitions Properties Type vec of size 1 line or mark size an integer Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Properties Type vec of size 1 Output window position palettes 2768 a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Xmin Minimum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Xmax Maximum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Ymin Minimum and maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Ymax Maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Buffer size An integer value In order to minimize the number of graphics outputs data may buffered Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 palettes 2769 continuoustime state no discretetime state no object discretetime state no name of computational function canimxy Interfacing function SCImodulesscicosblocksmacrosSinksCANIMXYsci Computational function SCImodulesscicosblockssrcccanimxyc Type 4 See also CANIMXY3D zfxy animated viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2770 Nome CANIMXY3D zfxy animated viewer Block Screenshot Contents zfxy animated viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description This block realizes the visualization of the evolution of the three regular input signals by drawing the third input as a function of the two others at instants of events on the event input port When a point is drawn on screen it stays until the buffer length is reached This scope is useful to make simple animations palettes 2771 Dialog box Number of Curves Set the number of curves Properties Type vec of size 1 color an integer It is the color number or marker type used to draw the evolution of the input port signal Seexset for color dash type definitions Properties Type vec of size 1 line or mark size an integer Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Properties Type vec of size 1 Output window position palettes 2772 a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Xmin and Xmax Minimum and Maximum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Ymin and Ymax Minimum and Maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Zmin and Zmax Minimum and Maximum values of the third input used to set up the Zaxis of the plot in the graphics window Properties Type vec of size 1 Alpha and Theta Set Alpha and Theta for the 3D view Properties Type vec of size 1 Buffer size An integer value In order to minimize the number of graphics outputs data may buffered Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 port 3 size 11 type 1 palettes 2773 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function canimxy3d Interfacing function SCImodulesscicosblocksmacrosSinksCANIMXY3Dsci Computational function SCImodulesscicosblockssrcccanimxy3dc Type 4 See also CANIMXY yfx animated viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2774 Nome CFSCOPE Floating point scope Block Screenshot Contents Floating point scope Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description This is a floating scope block palettes 2775 Dialog box Color a vector of integers The ith element is the color number or dash type used to draw the evolution of the ith input port signal Seeplot2d for color dash type definitions Properties Type vec of size 8 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If default value is used1 Xcos define the output window number Properties Type vec of size 1 Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Ymin Minimum values of the input used to set up the Yaxis of the plot in the graphics window palettes 2776 Properties Type vec of size 1 Ymax Maximum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Refresh period Maximum value on the Xaxis time The plot is redrawn when time reaches a multiple of this value Properties Type vec of size Buffer size To improve efficiency it is possible to buffer the input data The drawing is only done after each Buffer size call to the block Properties Type vec of size 1 Links to view This parameter allows you to display the output of specified link Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cfscope Interfacing function SCImodulesscicosblocksmacrosSinksCFSCOPEsci Computational function SCImodulesscicosblockssrcccfscopec Type 4 Authors Ramine Nikoukhah INRIA palettes 2778 Nome CMAT3D Matrix z values 3D viewer Block Screenshot Contents Matrix z values 3D viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description CMAT3D is a scope that shows matrix values as z values on a xy grid Dialog box palettes 2779 Bounds Vector X 1 for standard If you let 1 the x ticks would be between 0 and 1 else you can put your own vector Properties Type vec of size 1 Bounds Vector Y 1 for standard If you let 1 the x ticks would be between 0 and 1 else you can put your own vector Properties Type vec of size 1 ColorMap The colormap is a range color linked to the window output of the scope You can put a jetcolormap or hotcolormap or graycolormap or your own see colormap help Properties Must be a mx3 matrix and m 3 Zmin Minimum value in Z values Properties Type vec of size 1 Zmax Maximum values in Z values Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cmat3d Interfacing function SCImodulesscicosblocksmacrosSinksCMAT3Dsci palettes 2780 Computational function SCImodulesscicosblockssrcccmat3dc Type 4 See also CMATVIEW Matrix Colormapped viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2781 Nome CMATVIEW Matrix Colormapped viewer Block Screenshot Contents Matrix Colormapped viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description CMATVIEW is a scope that shows matrix values on a colormapped grid Dialog box ColorMap palettes 2782 The colormap is a range color linked to the window output of the scope You can put a jetcolormap or hotcolormap or graycolormap or your own see colormap help Properties Must be a mx3 matrix and m 3 Minimum level range The minimum level range is the minimum value who comes in the regular input port It would be linked to the cold value of the colormap Properties A scalar Maximum level range The maximum level range is the maximum value who comes in the regular input port It would be linked to the hot value of the colormap Properties A scalar Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 12 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cmatview Interfacing function SCImodulesscicosblocksmacrosSinksCMATVIEWsci Computational function SCImodulesscicosblockssrcccmatviewc Type 4 See also CMAT3D Matrix z values 3D viewer Authors palettes 2783 Ramine Nikoukhah INRIA Benoit Bayol palettes 2784 Nome CMSCOPE Multi display scope Block Screenshot Contents Multi display scope Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description When you start a simulation Xcos open Scope windows The Scope block displays its input with respect to simulation time The Scope block can have multiple axes one per port all axes have a common time range with independent yaxes The Scope allows you to adjust the amount of time and the range of input values displayed palettes 2785 Dialog box Input ports sizes It allows multiple input ports Properties Type vec of size 1 Drawing colors a vector of integers The ith element is the color number or dash type used to draw the evolution of the ith input port signal Seeplot2d for color dash type definitions Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If default value is used1 Xcos define the output window number Properties Type vec of size 1 Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes palettes 2786 a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size size 1 Ymin vector Minimum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size size1 Ymax vector Maximum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size size1 Refresh period Maximum value on the Xaxis time The plot is redrawn when time reaches a multiple of this value Properties Type vec of size size1 Buffer size To improve efficiency it is possible to buffer the input data The drawing is only done after each Buffer size call to the block Properties Type vec of size 1 Accept herited events 01 if 0CSCOPEf draws a new point only when an event occurs on its event input port if 1CSCOPEf draws a new point when an event occurs on its event input port and when its regular input changes due to an event on an other upstrem block herited events Properties Type vec of size 1 Name of Scope Namelabel of the block Properties Type str of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 palettes 2787 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cmscope Interfacing function SCImodulesscicosblocksmacrosSinksCMSCOPEsci Computational function SCImodulesscicosblockssrcccmscopec Type 4 Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2788 Nome CSCOPE Single Display Scope Block Screenshot Contents Single Display Scope Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description The Scope block displays its input with respect to simulation time Both axes have a common range The Scope allows you to adjust the amount of time and the range of input values displayed palettes 2789 Dialog box Color a vector of integers The ith element is the color number or dash type used to draw the evolution of the ith input port signal Seeplot2d for color dash type definitions Properties Type vec of size 8 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If default value is used1 Scicos define the output window number Properties Type vec of size 1 Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Ymin palettes 2790 Minimum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Ymax Maximum values of the input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Refresh period Maximum value on the Xaxis time The plot is redrawn when time reaches a multiple of this value Properties Type vec of size 1 Buffer size To improve efficiency it is possible to buffer the input data The drawing is only done after each Buffer size call to the block Properties Type vec of size 1 Accept herited events 01 if 0CSCOPEf draws a new point only when an event occurs on its event input port If 1CSCOPEf draws a new point when an event occurs on its event input port and when its regular input changes due to an event on an other upstream block herited events Properties Type vec of size 1 Name of Scope Namelabel of the block Properties Type str of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cscope palettes 2791 Interfacing function SCImodulesscicosblocksmacrosSinksCSCOPEsci Computational function SCImodulesscicosblockssrcccscopec Type 4 See also CMSCOPE Multi display scope Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2792 Nome CSCOPXY yfx permanent viewer Block Screenshot Contents yfx permanent viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description This block realizes the visualization of the evolution of the two regular inputs signals by drawing the second input as a function of the first at instants of events on the event input port When a point is drawn on screen it stays until the simulation is finished palettes 2793 Dialog box Number of Curves Set the number of curves Properties Type vec of size 1 color an integer It is the color number or dash type used to draw the evolution of the input port signal Seeplot2d for color dash type definitions Properties Type vec of size 1 line or mark size an integer Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Properties Type vec of size 1 Output window position a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position palettes 2794 Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Xmin Minimum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type of size Xmax Maximum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Ymin Minimum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Ymax Maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Buffer size To improve efficiency it is possible to buffer the input data The drawing is only done after each Buffer size call to the block Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no Benoit Bayol palettes 2795 discretetime state no object discretetime state no name of computational function cscopxy Interfacing function SCImodulesscicosblocksmacrosSinksCSCOPXYsci Computational function SCImodulesscicosblockssrcccscopxyc Type 4 See also CSCOPXY3D zfxy permanent viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2796 Nome CSCOPXY3D zfxy permanent viewer Block Screenshot Contents zfxy permanent viewer Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks palette Description This block realizes the visualization of the evolution of the three regular inputs signals by drawing the third input as a function of the two others at instants of events on the event input port When a point is drawn on screen it stays until the simulation is finished palettes 2797 Dialog box Number of Curves Set the number of curves Properties Type vec of size 1 color an integer It is the color number or marker type used to draw the evolution of the input port signal Seexset for color dash type definitions Properties Type vec of size 1 line or mark size an integer Properties Type vec of size 1 Output window number The number of graphic window used for the display It is often good to use high values to avoid conflict with palettes and Super Block windows If you have more than one scope make sure they dont have the same window numbers unless superposition of the curves is desired Properties Type vec of size 1 Output window position palettes 2798 a 2 vector specifying the coordinates of the upper left corner of the graphic window Answer for default window position Properties Type vec of size 1 Output window sizes a 2 vector specifying the width and height of the graphic window Answer for default window dimensions Properties Type vec of size 1 Xmin and Xmax Minimum and Maximum values of the first input used to set up the Xaxis of the plot in the graphics window Properties Type vec of size 1 Ymin and Ymax Minimum and Maximum values of the second input used to set up the Yaxis of the plot in the graphics window Properties Type vec of size 1 Zmin and Zmax Minimum and Maximum values of the third input used to set up the Zaxis of the plot in the graphics window Properties Type vec of size 1 Alpha and Theta Set Alpha and Theta for the 3D view Properties Type vec of size 1 Buffer size An integer value In order to minimize the number of graphics outputs data may buffered Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 port 2 size 11 type 1 port 3 size 11 type 1 palettes 2799 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cscopxy3d Interfacing function SCImodulesscicosblocksmacrosSinksCSCOPXY3Dsci Computational function SCImodulesscicosblockssrcccscopxy3dc Type 4 See also CSCOPXY yfx permanent viewer Authors Ramine Nikoukhah INRIA Benoit Bayol palettes 2800 Nome ENDBLK END block Block Screenshot Contents END block Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Sinks Sinks palette Description That block can be used to set the final time of the simulation When that block is truely parametrized then the simulator will jump to the final integration time defined in the Setup item of the simulate Menu from the time defined by the parameter Final simulation time of the dialog box That parameter can be a numerical value or a symbolic variable defined in the scicos context Dialog box Final simulation time Set the final time of the simulation When simulator reaches that value then the current time will jump to the final integration time Properties Type vec of size 1 palettes 2801 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosMiscENDBLKsci Compiled Super Block content See also ENDc ENDc block Scicos Block Authors Alan Layec INRIA palettes 2802 Nome ENDc ENDc block Block Screenshot Contents ENDc block Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sinks Sinks palette Description That block increases the current time to the final integration time of the simulation when it is activated with Tcur the activation date of the block and Tf the final integration time defined in the in the Setup item of the simulate Menu scsmpropstf Dialog box Final simulation time palettes 2803 That parameter is a date for an initial output event By using a feed back from the event output port to the event input port then that block can himself end the simulation at the time defined by this parameter Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 1 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function scicosexit Interfacing function SCImodulesscicosblocksmacrosEventsENDcsci Computational function SCImodulesscicosblockssrccscicosexitc Type 4 See also ENDBLK END block Scicos Block Authors Alan Layec INRIA palettes 2804 Nome TOWSc Data to Scilab worspace Block Screenshot Contents Data to Scilab worspace Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description That block is used to put simulated data in the scilab workspace Each sampling time both dates and values of input are recorded Dialog box Size of buffer Set the size of the input buffer That gives the total number of samples recorded during the simu lation palettes 2805 That buffer is a circulate buffer Properties Type vec of size 1 Scilab variable name Set the name of the Scilab variable This must be a valid variable name The simulation must be finished to retrieve that variable in the Scilab workspace Properties Type str of size 1 Inherit no0 yes1 Options to choose event inheritance from regular input or from explicit event input 0 Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function towsc Interfacing function SCImodulesscicosblocksmacrosSinksTOWScsci Computational function SCImodulesscicosblockssrcctowscc Type 4 Authors Alan Layec INRIA palettes 2806 Nome TRASHf Trash block Block Screenshot Contents Trash block Palette Description Default properties Interfacing function Computational function Palette Sinks palette Description That block is an endblock It do nothing Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function trash palettes 2807 Interfacing function SCImodulesscicosblocksmacrosSinksTRASHfsci Computational function SCImodulesscicosblockssrcfortrantrashf Type 0 palettes 2808 Nome WFILEf Write to file Block Screenshot Contents Write to file Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description This block allows user to save data in a file in formatted and binary mode Each call to the block corresponds to a record in the file Each record has the following form where is the value of time when block is called and is the ith input value This block does not manage UTF filename The pair block is Dialog box palettes 2809 Input size a scalar This fixes the input size Properties Type vec of size 1 Output file name a character string defining the path of the file Properties Type str of size 1 Output Format a character string defining the Fortran format to use or nothing for an unformatted binary wri te If given the format must began by a left parenthesis and end by a right parenthesis exam ple Properties Type str of size 1 Buffer size To improve efficiency it is possible to buffer the input data Write on the file is only done after eachBuffer size call to the block Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function writef Interfacing function SCImodulesscicosblocksmacrosSinksWFILEfsci Computational function SCImodulesscicosblockssrcfortranwriteff Type 0 palettes 2810 Authors Ramine Nikoukhah INRIA palettes 2811 Nome WRITEAUf Write AU sound file Block Screenshot Contents Write AU sound file Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description This block writes a sound file specified by the string au file The data should be arranged with one channel per column Amplitude values outside the range 11 are clipped prior to writing auwrite supports multichannel data for 8bit mulaw and 8 and 16bit linear formats Dialog box Buffer size To improve efficiency it is possible to buffer the input data read on the file is only done after each Buffer size call to the block Properties Type vec of size 1 palettes 2812 Swap mode 01 WithSwap mode1 the file is supposed to be coded in little endian IEEE format and data are swaped if necessary to match the IEEE format of the processor IfSwap mode0 then automatic bytes swap is disabled Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function writeau Interfacing function SCImodulesscicosblocksmacrosSinksWRITEAUfsci Computational function SCImodulesscicosblockssrccwriteauc Type 2 Authors Ramine Nikoukhah INRIA palettes 2813 Nome WRITECf Write binary data Block Screenshot Contents Write binary data Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sinks palette Description This block allows user to write data in a C binary file Dialog box Input size palettes 2814 a scalar the size of the input Properties Type vec of size 1 Output file name a character string defining the output file name Properties Type str of size 1 Output Format a character string defining the format to use Properties Type str of size 1 Buffer size To improve efficiency it is possible to buffer the input data read on the file is only done after eachBuffer size call to the block Properties Type vec of size 1 Swap mode 01 WithSwap mode1 the file is supposed to be coded in little endian IEEE format and data are swaped if necessary to match the IEEE format of the processor IfSwap mode0 then automatic bytes swap is disabled Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function writec Interfacing function SCImodulesscicosblocksmacrosSinksWRITECfsci palettes 2815 Computational function SCImodulesscicosblockssrccwritecc Type 2 Authors Ramine Nikoukhah INRIA 18 Sources palette palettes 2816 Nome Sourcespal Sources palette Block Screenshot Module xcos Description Most of blocks of the Source palette can be viewed as data generators That palette also contains blocks to read data from files and input ports used in superblocks The blocks of that palette doesnt have regular input ports Blocks CLKINVf Input activation port CLOCKc Activation clock CONSTm Constant Counter Counter palettes 2817 CURVf Curve FROMWSB Data from Scilab workspace to Xcos GENSINf Sin generator GENSQRf Square wave generator INf Input Port INIMPLf Input implicit port ModuloCount Modulo counter RAMP Ramp RANDm Random generator READAUf Read AU sound file READCf Read binary data RFILEf Read from file SampleCLK Sample Time Clock SAWTOOTHf Sawtooth generator Sigbuilder Signal creatorgenerator STEPFUNCTION Step function generator TIMEf Time TKSCALE Adjust constant value with a tk widget palettes 2818 Nome CLKINVf Input activation port Block Screenshot Contents Input activation port Palette Description Dialog box Default properties Interfacing function Authors Palette Sources palette Description This block must only be used inside Xcos Super Blocks to represent an event input port In a Super Block the event input ports must be numbered from 1 to the number of event input ports Dialog box Port number an integer defining the port number Properties Type vec of size 1 Default properties always active no directfeedthrough no palettes 2819 zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function input Interfacing function SCImodulesscicosblocksmacrosSourcesCLKINVfsci Authors Ramine Nikoukhah INRIA palettes 2820 Nome CLOCKc Activation clock Block Screenshot Contents Activation clock Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Sources palette Description This block is a Super Block constructed by feeding back the output of the block into its input event port The unique output of this block generates a regular train of events thats scheduled by the dialog parameter Period Dialog box Period scalar One over the frequency of the clock palettes 2821 Period is the time that separates two output events Properties Type vec of size 1 Init time scalar Starting date If negative the clock never starts Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosSourcesCLOCKcsci Compiled Super Block content palettes 2822 See also EVTDLYc Event delay Authors Alan Layec INRIA palettes 2823 Nome CONSTm Constant Block Screenshot Contents Constant Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a constant value generator Dialog box Constant A matrix of any type The size of the matrix gives the size of the regular output port The constantij value is the componentij value of the output port From this value the block inherits its data type Properties Type mat of size 12 palettes 2824 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function cstblk4 Interfacing function SCImodulesscicosblocksmacrosSourcesCONSTmsci Computational function SCImodulesscicosblockssrcccstblk4c Type 4 Authors Fady NASSIF INRIA Alan Layec INRIA palettes 2825 Nome CURVf Curve Block Screenshot Contents Curve Palette Description Default properties Interfacing function Computational function See also Authors Palette Sources palette Description This block defines a tabulated function of time Between mesh points block performs a linear inter polation Outside tabulation block outputs last tabulated value User may define the tabulation of the function using a curve editor Default properties always active yes directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no palettes 2826 object discretetime state no name of computational function intplt Interfacing function SCImodulesscicosblocksmacrosSourcesCURVfsci Computational function SCImodulesscicosblockssrcfortranintpltf Type 0 See also Sigbuilder Signal creatorgenerator Authors Ramine Nikoukhah INRIA palettes 2827 Nome Counter Counter Block Screenshot Contents Counter Palette Description Dialog box Default properties Interfacing function Computational function See also Authors Palette Sources palette Description This block counts from minimal to maximal or from maximal to minimal depending on the choice of the rule Dialog box Minimum The lowest number of the counter palettes 2828 Properties Type vec of size 1 Maximum The highest number of the counter Properties Type vec of size 1 Rule 1Increment 2Decrement The rule of counting If it is 1 then the counter counts from the lower number to the higher number the count in this case is increasing otherwise if the rule is equal to 2 the counter will decrease and it will count from the higher number to the lower one Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function counter Interfacing function SCImodulesscicosblocksmacrosSourcesCountersci Computational function SCImodulesscicosblockssrcccounterc Type 4 See also ModuloCount Modulo counter xcos Block Authors Fady NASSIF INRIA palettes 2829 Nome FROMWSB Data from Scilab workspace to Xcos Block Screenshot Contents Data from Scilab workspace to Xcos Palette Description Dialog box Default properties Interfacing function Compiled Super Block content See also Authors Palette Sources palette Description That block is used to get data defined in the Scilab workspace and use them in Xcos Data should have time and values fields Dialog box Variable name This variable is defined in Scilab and should be a structure with two fields ie a time field of size Nx1 and a values filed of size NxM time is a column vector of size palettes 2830 Nx1 and values is a matrix of size NM time filed can only be of Real type whereas the values field can be and Interpolation method Variables read by Xcos are data values read at discrete instants given by the time field This option causes the block to interpolate at time steps for which no corresponding workspace data exists There are four interpolation methods available 0 Zero order method This method generates a piecewise constant signal ie for This method is available for all data types 1 Linear method This method generates a piecewise linear signal ie for For data types other than double and complex the linear interpolation can be used but the final output will be com puted by casting interpolation result into the original data type 2NATURAL method This cubic spline is computed by using the following conditions con sidering points This method is only available for Real and complex data types 3NOTAKNOT method The cubic spline is computed by using the following conditions considering points This method is only available for Real and complex data types Enable zero crossing0No 1Yes Enables zero crossing detection When and interpolation methods are chosen the output signal will be discontinuous at data time instants These possible discontinuities may cause problem for the numerical solver In order to perform a reliable numerical integration the zero crossing option is used If output of the block affects data used by the nume rical solver at discontinuous points a discrete event is generated and the numerical solver is cold restarted The discrete event is also generated at the and for other interpolating methods Output at end0Zero 1Hold 2Repeat This option is for selecting method for generating out put after the last time point for which data is available from the workspace 0 Zero The output is set to zero 1 Hold The output is hold 2 Repeat The output is repeated from workspace Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs palettes 2831 port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosSourcesFROMWSBsci Compiled Super Block content See also TOWSc Data to Scilab worspace Authors Masoud Najafi INRIA palettes 2832 Nome GENSINf Sin generator Block Screenshot Contents Sin generator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a sine wave generator Dialog box Magnitude a scalar The magnitude M Properties Type vec of size 1 palettes 2833 Frequency a scalar The frequency F Properties Type vec of size 1 phase a scalar The phase P Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function gensin Interfacing function SCImodulesscicosblocksmacrosSourcesGENSINfsci Computational function SCImodulesscicosblockssrcfortrangensinf Type 0 Authors Ramine Nikoukhah INRIA palettes 2834 Nome GENSQRf Square wave generator Block Screenshot Contents Square wave generator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a square wave generator output takes values M and M Every time an event is received on the input event port the output switches from M to M or M to M Dialog box Amplitude a scalar Properties Type vec of size 1 Default properties always active no palettes 2835 directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function gensqr Interfacing function SCImodulesscicosblocksmacrosSourcesGENSQRfsci Computational function SCImodulesscicosblockssrcfortrangensqrf Type 0 Authors Ramine Nikoukhah INRIA palettes 2836 Nome INIMPLf Input implicit port Block Screenshot Contents Input implicit port Palette Description Dialog box Default properties Interfacing function Authors Palette Sources palette Description Inport blocks are the links from outside a system into the system Dialog box Port number Specify the port number of the Inport block Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no palettes 2837 mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function inimpl Interfacing function SCImodulesscicosblocksmacrosSourcesINIMPLfsci Authors Ramine Nikoukhah INRIA palettes 2838 Nome ModuloCount Modulo counter Block Screenshot Contents Modulo counter Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description It is a discrete block The block outputs a periodic scalar signal having a waveform that the user specifies Dialog box initial state A scalar initial discrete state Properties Type vec of size 1 Modulo what number palettes 2839 Number of required discrete signals Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function modulocount Interfacing function SCImodulesscicosblocksmacrosSourcesModuloCountsci Computational function SCImodulesscicosblockssrccmodulocountc Type 4 Authors Ramine Nikoukhah INRIA palettes 2840 Nome RAMP Ramp Block Screenshot Contents Ramp Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description The Ramp block generates a signal that starts at a specified time and value and changes by a specified rate The blocks Slope Start time and Initial output parameters determine the characteristics of the output signal All must have the consistent dimensions after scalar expansion Dialog box Slope The rate of change of the generated signal Properties Type vec of size 1 palettes 2841 Start time The time at which the signal begins to be generated Properties Type vec of size 1 Initial output The initial value of the signal Properties Type vec of size 1 Default properties always active yes directfeedthrough no zerocrossing yes mode yes regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function ramp Interfacing function SCImodulesscicosblocksmacrosSourcesRAMPsci Computational function SCImodulesscicosblockssrccrampc Type 4 Authors Ramine Nikoukhah INRIA palettes 2842 Nome RANDm Random generator Block Screenshot Contents Random generator Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a random wave generator each output component takes piecewise constant random values Every time an event is received on the input event port the outputs take new independent random values Output port size is given by the size of A and B matrices palettes 2843 Dialog box Datatype1real double 2complex It indicates the type of the output It support only the two types double 1 and complex 2 If we input another entry in this label Scicos will print the message Datatype is not supported Properties Type vec of size 1 flag 0 or 1 0 for uniform distribution on AAB 1 for normal distribution Properties Type vec of size 1 A matrix Properties Type mat of size 12 B matrix Properties Type mat of size 12 seed matrix Seed value for a sequence of random number First number is for the real part and the second for the imaginary part Properties Type mat of size 12 palettes 2844 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function rndblkm Interfacing function SCImodulesscicosblocksmacrosSourcesRANDmsci Computational function SCImodulesscicosblockssrccrndblkmc SCImodulesscicosblockssrccrndblkzmc Authors Fady Nassif INRIA Ramine Nikoukhah INRIA palettes 2845 Nome READAUf Read AU sound file Block Screenshot Contents Read AU sound file Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description Loads a sound file specified by the string au file returning the sampled data in y The au extension is appended if no extension is given Amplitude values are in the range 11 auread supports mul tichannel data in the following formats 8bit mulaw 8 16 and 32bit linear Floatingpoint Dialog box palettes 2846 Input file name a character string defining the path of the file Properties Type str of size 1 Buffer size To improve efficiency it is possible to buffer the input data Read on the file is only done after each Buffer size call to the block Properties Type vec of size 1 Swap mode 01 WithSwap mode1 the file is supposed to be coded in little endian IEEE format and data are swaped if necessary to match the IEEE format of the processor IfSwap mode0 then automatic bytes swap is disabled Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function readau Interfacing function SCImodulesscicosblocksmacrosSourcesREADAUfsci Computational function SCImodulesscicosblockssrccreadauc Type 2 Authors Ramine Nikoukhah INRIA palettes 2847 Nome READCf Read binary data Block Screenshot Contents Read binary data Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This block allows user to read data in a C file Output record selection and Time record Selection allows the user to select data among file records Each call to the block advance one record in the file palettes 2848 Dialog box Time record selection an empty matrix or a positive integer If an integer i is given the i th element of the read record is assumed to be the date of the output event If empty no output event exists Properties Type vec of size 1 Outputs record selection a vector of positive integer The th element of the read record gives the value of output Properties Type vec of size 1 Input file name a character string defining the path of the file Properties Type str of size 1 Input Format a character string defining the format to use Properties Type str of size 1 Record size palettes 2849 The file is supposed to be formed by a sequence of data with same format These data are organized in a sequence of record each of them containing Record size data Properties Type vec of size 1 Buffer size To improve efficiency it is possible to buffer the input data Read on the file is only done after each Buffer size call to the block Properties Type vec of size 1 Initial record index a scalar This fixes the first record of the file to use Properties Type vec of size 1 Swap mode 01 WithSwap mode1 the file is supposed to be coded in little endian IEEE format and data are swaped if necessary to match the IEEE format of the processor IfSwap mode0 then automatic bytes swap is disabled Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function readc Interfacing function SCImodulesscicosblocksmacrosSourcesREADCfsci Computational function SCImodulesscicosblockssrccreadcc Type 2 palettes 2850 Authors Ramine Nikoukhah INRIA palettes 2851 Nome RFILEf Read from file Block Screenshot Contents Read from file Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources Description This block allows user to read data in a file in formatted or binary mode Output record selection and Time record selection allows the user to select data among file records Each call to the block advance one record in the file The pair block is Dialog box palettes 2852 Time record selection an empty matrix or a positive integer If an integer is given the th element of the read record is assumed to be the date of the output event If empty no output event exists Properties Type vec of size 1 Outputs record selection a vector of positive integer The th element of the read record gives the value of i th output Properties Type vec of size 1 Input file name a character string defining the path of the file Properties Type str of size 1 Input Format a character string defining the Fortran format to use or nothing for an unformatted binary wri te If given the format must began by a left parenthesis and end by a right parenthesis exam ple Properties Type str of size 1 Buffer size To improve efficiency it is possible to buffer the input data read on the file is only done after eachBuffer size call to the block Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 palettes 2853 continuoustime state no discretetime state yes object discretetime state no name of computational function readf Interfacing function SCImodulesscicosblocksmacrosSourcesRFILEfsci Computational function SCImodulesscicosblockssrcfortranreadff Type 0 Authors Ramine Nikoukhah INRIA palettes 2854 Nome SAWTOOTHf Sawtooth generator Block Screenshot Contents Sawtooth generator Palette Description Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a sawtooth wave generator output is from to where and denote the times of two succes sive input events Default properties always active yes directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state yes object discretetime state no name of computational function sawtth palettes 2855 Interfacing function SCImodulesscicosblocksmacrosSourcesSAWTOOTHfsci Computational function SCImodulesscicosblockssrcfortransawtthf Type 0 Authors Ramine Nikoukhah INRIA palettes 2856 Nome STEPFUNCTION Step function generator Block Screenshot Contents Step function generator Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Authors Palette Sources palette Description The Step block provides a step between two definable levels at a specified time If the simulation time is less than the Step time parameter value the blocks output is the Initial value parameter value For simulation time greater than or equal to the Step time the output is the Final value parameter value Dialog box Step time The time in seconds when the output jumps from the Initial value parameter to the Final value parameter Properties Type vec of size 1 palettes 2857 Initial value The block output until the simulation time reaches the Step time parameter Properties Type vec of size 1 Final value The block output when the simulation time reaches and exceeds the Step time parameter Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosSourcesSTEPFUNCTIONsci Compiled Super Block content palettes 2858 Authors Ramine Nikoukhah INRIA palettes 2859 Nome SampleCLK Sample Time Clock Block Screenshot Contents Sample Time Clock Palette Description Dialog box Default properties Interfacing function See also Authors Palette Sources palette Description The difference between the SampleCLK and the CLOCKc is that all the SampleCLK blocks in our diagram are synchronous The synchronism is done due to two different methods of computation in the compilation phase The first method consists of computing a clock that is faster than all the SampleCLK connected to a counter which activate the event select block The clock is calculated due to the following rule If all the blocks have the same offset then the frequency of the clock is the gcd of the sample time and the offset of the clock is equal to the offset If the offsets are different then the frequency of the clock is the gcd of the sample time and the offset and the offset of the clock is equal to 0 The Counter counts from one to the least common multiple of the sample time lcm The number of outputs of the ESELECTf block is equal to the lcm The second method uses the Multifrequency block it generates events only for specific time Events in this method are not periodically generated as in the first one palettes 2860 Dialog box Sample time The Sample time value Properties Type vec of size 1 Offset The offset value Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function sampleclk Interfacing function SCImodulesscicosblocksmacrosSourcesSampleCLKsci See also CLOCKc Activation clock Counter Counter ESELECTf Synchronous block EventSelect Mfreq Multiple Frequencies palettes 2861 Authors Fady NASSIF INRIA palettes 2862 Nome Sigbuilder Signal creatorgenerator Block Screenshot Contents Signal creatorgenerator Palette Description Dialog box Default properties Interfacing function Compiled Super Block content Authors Palette Sources palette Description The Signal Builder block is a superblock containing a block whose output event port is connected to its input event port This event feedback gives the possibility to generate events at discontinuous point of the signal The generated events automatically restart the numerical solver and avoids numerical problems The generated event is also made available to the user for possible use Remind that if higher interpolation methods are used the events are generated only at the beginning and at the end of the signal palettes 2863 Dialog box The parameters of Sigbuilder block is the same as that of block Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function csuper Interfacing function SCImodulesscicosblocksmacrosSourcesSigbuildersci palettes 2864 Compiled Super Block content Authors Masoud Najafi INRIA palettes 2865 Nome TIMEf Time Block Screenshot Contents Time Palette Description Default properties Interfacing function Computational function Authors Palette Sources palette Description This block is a time generator The unique regular output is the current time Default properties always active yes directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no palettes 2866 name of computational function timblk Interfacing function SCImodulesscicosblocksmacrosSourcesTIMEfsci Computational function SCImodulesscicosblockssrcfortrantimblkf Type 0 Authors Ramine Nikoukhah INRIA palettes 2867 Nome TKSCALE Adjust constant value with a tk widget Block Screenshot Contents Adjust constant value with a tk widget Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Sources palette Description This source block generates a piecewise constant signal the value of which can be set interactively using a TK widget in the course of the simulation The output value is the value set by the slider an integer between Min value and Max value divided by the Normalization factor Increasing proporti onaly all three block parameters does not change the output range but it does increase precision Dialog box Min value palettes 2868 An integer specifying the min value in the range of the scale Properties Type vec of size 1 Max value An integer specifying the max value in the range of the scale Properties Type vec of size 1 Normalization The output of the block is the integer value specified by the slider an integer between Min value and the Max value divided by this Normalization factor Properties Type vec of size 1 Default properties always active no directfeedthrough no zerocrossing no mode no regular outputs port 1 size 11 type 1 numbersizes of activation inputs 1 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function tkscaleblk Interfacing function SCImodulesscicosblocksmacrosSourcesTKSCALEsci Computational function SCImodulesscicosmacrosscicosscicostkscaleblksci Type 5 Authors Ramine Nikoukhah INRIA 19 Thermohydraulics palette palettes 2869 Nome ThermoHydraulicspal ThermalHydraulics toolbox Block Screenshot Module xcos Description ThermalHydraulics toolbox contains some basic thermalhydraulic components such as pressure source pipe control valves etc Blocks Bache Thermalhydraulic tank reservoir PerteDP Thermalhydraulic pipe PuitsP Thermalhydraulic drain well SourceP Thermalhydraulic constant pressure source VanneReglante Thermalhydraulic control valve palettes 2870 Nome Bache Thermalhydraulic tank reservoir Block Screenshot Contents Thermalhydraulic tank reservoir Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description The Bache block represents a thermalhydraulic tank or reservoir This block has two inlets and two outlets whose altitudes can be changed by the user Conventionally for input ports black ports flow direction is positive when fluid flows into the tank On the other hand for output ports white ports flow direction is positive when fluid flows out of the tank The user can set the surface area of the tank the initial temperature and initial level of the fluid in the tank If an input or output port is left unused it should be blocked by a stopper block palettes 2871 Dialog box Pression dans le ciel de la bache Patm Pa Atmospheric pressure inside the tank Properties Type vec of size 1 Section de la bache A m2 Surface area of the tank Properties Type vec of size 1 Altitude du piquage d entrée 1 ze1 m Altitude of the first input port Properties Type vec of size 1 Altitude du piquage d entrée 2 ze2 m Altitude of the second input port Properties Type vec of size 1 Altitude du piquage de sortie 1 zs1 m Altitude of the first output port Properties Type vec of size 1 Altitude du piquage de sortie 2 zs2 m Altitude of the second output port Properties Type vec of size 1 palettes 2872 Altitude initiale du fluide z0 m Initial fluid level in the tank Properties Type vec of size 1 Température initiale du fluide T0 K Temperature of fluid in the tank Properties Type vec of size 1 Si 0 masse volumique imposée du fluide prho kgm3 Density of fluid Properties Type vec of size 1 Default properties Inputs Modelica variable name Ce1 Implicit variable Modelica variable name Ce2 Implicit variable Outputs Modelica variable name Cs1 Implicit variable Modelica variable name Cs2 Implicit variable Modelica variable name yNiveau Explicit variable Parameters Modelica parameter name Patm Default value 101300 Is a state variable no Modelica parameter name A Default value 1 Is a state variable no Modelica parameter name ze1 Default value 40 Is a state variable no palettes 2873 Modelica parameter name ze2 Default value 0 Is a state variable no Modelica parameter name zs1 Default value 40 Is a state variable no Modelica parameter name zs2 Default value 0 Is a state variable no Modelica parameter name z0 Default value 30 Is a state variable no Modelica parameter name T0 Default value 290 Is a state variable no Modelica parameter name prho Default value 0 Is a state variable no File name of the model Bache Interfacing function SCImodulesscicosblocksmacrosHydraulicsBachesci Modelica model SCImodulesscicosblocksmacrosHydraulicsBachemo palettes 2874 Nome PerteDP Thermalhydraulic pipe Block Screenshot Contents Thermalhydraulic pipe Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description A PertDP block represents a hydraulic pipe with linear resistance losses This component represents a hydraulic resistance and pressure loss is directly proportional to the flow rate Conventionally the flow direction is the positive when fluid flows from the black port to the white port The pressure loss is obtained with The key parameters of this block are the pipes length the pipes diameter inlet and outlet altitudes and some other thermalhydraulic coefficients palettes 2875 Dialog box Longueur du tube L m Length of pipe Properties Type vec of size 1 Diamètre interne du tube D m Pipe diameter Properties Type vec of size 1 Coefficient de perte de chargefrottementSU lambda Coefficient of thermohydraluc resistance Properties Type vec of size 1 Altitude entrée tuyauterie z1 m Altitude of the first port z1 Properties Type vec of size 1 Altitude sortie tuyauterie z2 m Altitude of the second port z2 Properties Type vec of size 1 Si 0 masse volumique imposée fu fluide prho kgm3 Fluid density Properties Type vec of size 1 Default properties Inputs Modelica variable name C1 Implicit variable palettes 2876 Outputs Modelica variable name C2 Implicit variable Parameters Modelica parameter name L Default value 10 Is a state variable no Modelica parameter name D Default value 02 Is a state variable no Modelica parameter name lambda Default value 003 Is a state variable no Modelica parameter name z1 Default value 0 Is a state variable no Modelica parameter name z2 Default value 0 Is a state variable no Modelica parameter name prho Default value 0 Is a state variable no File name of the model PerteDP Interfacing function SCImodulesscicosblocksmacrosHydraulicsPerteDPsci Modelica model SCImodulesscicosblocksmacrosHydraulicsPerteDPmo palettes 2877 Nome PuitsP Thermalhydraulic drain well Block Screenshot Contents Thermalhydraulic drain well Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description This thermalhydraulic component represents a thermalhydraulic constant pressure drain well This block is specified with its pressure and temperature Conventionally the flow direction is positive when fluid flows into the block Dialog box Pression de la source P0 Pa Pressure of the thermohydraulic source Properties Type vec of size 1 Temperature de la source T0 K palettes 2878 Temperature of the thermohydraulic source Properties Type vec of size 1 Enthalpie spécifique de la source H0 Jkg Specific Enthaly of the thermohydraulic source Properties Type vec of size 1 1température fixée 2enthalpie fixée optiontemperature Temperature option 1 fixed temperature 2 fixed enthalpy Properties Type vec of size 1 Default properties Inputs Modelica variable name C Implicit variable Parameters Modelica parameter name P0 Default value 100000 Is a state variable no Modelica parameter name T0 Default value 290 Is a state variable no Modelica parameter name H0 Default value 100000 Is a state variable no Modelica parameter name optiontemperature Default value 1 Is a state variable no File name of the model Puits Interfacing function SCImodulesscicosblocksmacrosHydraulicsPuitsPsci Modelica model SCImodulesscicosblocksmacrosHydraulicsPuitsmo palettes 2879 Nome SourceP Thermalhydraulic constant pressure source Block Screenshot Contents Thermalhydraulic constant pressure source Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description This thermalhydraulic component represents a thermalhydraulic constant pressure supply This block is specified with its output pressure and temperature Conventionally the flow direction is positive when the fluid flows out of the block Dialog box Pression de la source P0 Pa Pressure of the thermohydraulic source Properties Type vec of size 1 Temperature de la source T0 K palettes 2880 Temperature of the thermohydraulic source Properties Type vec of size 1 Enthalpie spécifique de la source H0 Jkg Specific enthalpie of the thermohydraulic source Properties Type vec of size 1 1température fixée 2enthalpie fixée optiontemperature Temperature option 1 fixed temperature 2 fixed enthalpy Properties Type vec of size 1 Default properties Outputs Modelica variable name C Implicit variable Parameters Modelica parameter name P0 Default value 300000 Is a state variable no Modelica parameter name T0 Default value 290 Is a state variable no Modelica parameter name H0 Default value 100000 Is a state variable no Modelica parameter name optiontemperature Default value 1 Is a state variable no File name of the model Source Interfacing function SCImodulesscicosblocksmacrosHydraulicsSourcePsci Modelica model SCImodulesscicosblocksmacrosHydraulicsSourcemo palettes 2881 Nome VanneReglante Thermalhydraulic control valve Block Screenshot Contents Thermalhydraulic control valve Palette Description Dialog box Default properties Interfacing function Modelica model Palette ThermalHydraulics palette Description The VanneReglante block represents a variable orifice control valve The flow rate through the valve is proportional to the valve opening where is the valve opening is the pressure difference and is the flow rate This model is only used for the laminar flow regimes is a constant depending on the valve geometry and mass density of fluid Dialog box Cvmax palettes 2882 Cvmax maximum opening of the valve Properties Type vec of size 1 prho Fluid density Properties Type vec of size 1 Default properties Inputs Modelica variable name C1 Implicit variable Modelica variable name Ouv Explicit variable Outputs Modelica variable name C2 Implicit variable Parameters Modelica parameter name Cvmax Default value 800542 Is a state variable no Modelica parameter name prho Default value 0 Is a state variable no File name of the model VanneReglante Interfacing function SCImodulesscicosblocksmacrosHydraulicsVanneReglantesci Modelica model SCImodulesscicosblocksmacrosHydraulicsVanneReglantemo 20 User defined functions palette palettes 2883 Nome Userdefinedfunctionspal User defined functions palette Block Screenshot Module xcos Description The user defined function contains blocks that allow you to model the component behaviour The output is expressed as a function of the input Blocks cblock C file function CBLOCK New C EXPRESSION Mathematical expression fortranblock Fortran genericblock3 Generic block MBLOCK Modelica generic block PDE 1D PDE block scifuncblockm Scilab function block SUPERf Super block TEXTf Text palettes 2884 Nome CBLOCK New C Block Screenshot Contents New C Palette Description Dialog box Default properties Interfacing function Authors Palette User defined functions palette Description This block creates skeleton of the Ccomputing function It also creates library file and object files palettes 2885 Dialog box simulation function Name of the function to be generated Properties Type str of size 1 is block implicit If yes y is selected it calls implicit solver dasrt else n it calls explicit solver lsodar Properties Type str of size 1 input ports sizes Number of regular input ports Properties Type vec of size 1 output ports sizes Number of regular output ports Properties Type vec of size 1 palettes 2886 input event ports sizes Number of event input ports Properties Type vec of size 1 output events ports sizes Number of event output ports Properties Type vec of size 1 initial continuous state Initial Conditions Properties Type vec of size 1 number of zero crossing surfaces Select to enable zero crossing detection Properties Type vec of size 1 initial discrete state Initial conditions of the discrete states Properties Type vec of size 1 Real parameters vector Real Parameter vector that the function accepts Properties Type vec of size 1 Integer parameters vector Integer Parameter vector that the function accepts Properties Type vec of size 1 initial firing vector A vector Size of this vector corresponds to the number of event outputs The value of the entry specifies the time of the preprogrammed event firing on the output event port If less than zero no event is preprogrammed Properties Type vec of size sum6 direct feedthrough The input to the block at the current time determine the output of the block at the current time This forces the input to feed through to the output as if the system were operating at steadystate Properties Type str of size 1 time dependence Create a signal that specifies the time dependence Properties Type str of size 1 palettes 2887 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function Interfacing function SCImodulesscicosblocksmacrosMiscCBLOCKsci Authors Ramine Nikoukhah INRIA palettes 2888 Nome EXPRESSION Mathematical expression Block Screenshot Contents Mathematical expression Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette User defined functions palette Description The Expression block applies the specified Scilab functions to its input Dialog box number of inputs Block input can be a scalar or vector palettes 2889 Properties Type vec of size 1 scilab expression The Scilab expression applied to the input Properties Type vec of size 1 use zerocrossing Select to enable zero crossing detection Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode yes regular inputs port 1 size 11 type 1 port 2 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function evaluateexpr Interfacing function SCImodulesscicosblocksmacrosMiscEXPRESSIONsci Computational function SCImodulesscicosblockssrccevaluateexprc Type 4 Authors Ramine Nikoukhah INRIA palettes 2890 Nome MBLOCK Modelica generic block Block Screenshot Contents Modelica generic block Palette Description Dialog box Default properties Interfacing function Authors Palette User Defined function palette Description The block MBlock provides an easy way to build a xcos block whose behavior is specified by a Modelica program Using this block the user will be able to write and compile Modelica programs in xcos without creating any interfacing function The associated Modelica program of this block can be either given in a file or written in the window opened by the block In order to link this block to other xcos blocks that may be other Modelica blocks the types of block ports as well as their associated variables should be specified palettes 2891 Dialog box Input variables In this filed the ports connected to the left hand side of the block are defined If the port is an explicit port it will be an input port In this case the variable should be declared in the Modelica program as Real If the port is an implicit port the variable desinating this port should be a connector Remind that for implicit port the notion of input and output does not exist and specifying an implicit variable in this filed is just placing the port at the left hend side of the block Input variables types In this filed the type of ports are specified ie I for implicit ports and E for explicit ports The size of the vector of input variables and the vector of inputvectortype should be equal Output variables Similar to the input variables vector the explicit output variables and implicit variables which are displayed at the right hand side of the block are specified in this filed Output variables types The type of variables given in the Output variable vector are specified ie I for implicit ports and E for explicit ports Parameters in Modelica The values of parameters declared in the Modelica program can be overloaded To overload a para meter value the name of parameters are given in this field and their corresponding values are given in the parameter values fields that are displayed in the second dialog box Parameters properties The type of the Modelica parameters For that time being one can parametrize three types of Mo delica variable 0 the parameter is set to be a Modelica parameter variable scalar or vector palettes 2892 1 the parameter is set to be an initial condition of Modelica state variable scalar or vector 2 the parameter is set to be an initial condition of Modelica state variable with the property fixedtrue scalar or vector Function name The Modelica class name is specified in this filed If the Modelica class name is specified without any path or extension an interactive window is opened and the user can write or edit the Modelica program This window is opened each time the user clicks on the block If the Modelica class name is specified with path and mo extension the compiler looks for the file and if it is found the file will be compiled otherwise a window is opened and the user can write the Modelica program This Modelica file will be saved with the given filename in the specified path The next time only inputoutput characteristics of the block can be changed and the Modelica file should be edited with another text editor Parameter values The value of Modelica parameters are given in the Set parameters values dialog box These values that can be scalar or vector can also be defined in the xcos context In order to access the xcos context click on the Diagram menu then click on the Context submenu For instan ce here is an example of overloading of parameters in a Modelica program Parameters vector SpeedPositionLength Parameters properties vector 021 Speed value 120 Position value 00 01 POS Length value 130 121 Default properties always active yes directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 port 2 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function generic palettes 2893 Interfacing function SCImodulesscicosblocksmacrosMiscMBLOCKsci Authors M NajafiA Layec INRIA palettes 2894 Nome SUPERf Super block Block Screenshot Contents Super block Palette Description Default properties Interfacing function Authors Palette User defined functions palette Description This block opens up a new Scicos window for editing a new block diagram This diagram describes the internal functions of the super block Super block inputs and outputs regular or event are designated by special input or output blocks Regular input blocks must be numbered from 1 to the number of regular input ports Regular input ports of the super block are numbered from the top of the block shape to the bottom Regular output ports must be numbered from 1 to the number of regular output ports Regular output ports of the super block are numbered from the top of the block shape to the bottom Event input blocks must be numbered from 1 to the number of event input ports Event input ports of the super block are numbered from the left of the block shape to the right Event output ports must be numbered from 1 to the number of event output ports Event output ports of the super block are numbered from the left of the block shape to the right Default properties always active no directfeedthrough no zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs palettes 2895 port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function super Interfacing function SCImodulesscicosblocksmacrosMiscSUPERfsci Authors Ramine Nikoukhah INRIA palettes 2896 Nome cblock C language Block Screenshot Contents C language Palette Description Dialog box Default properties Interfacing function Authors Palette User defined functions palette Description This block creates skeleton of the C computing function Also it creates library file and object files Dialog box input ports sizes Number of regular input ports Properties Type vec of size 1 palettes 2897 output port sizes Number of regular output ports Properties Type vec of size 1 System parameters vector Number of parameters that this function accepts Properties Type vec of size 1 function name Name of the function to be generated Properties Type str of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function Interfacing function SCImodulesscicosblocksmacrosMisccblocksci Authors Ramine Nikoukhah INRIA palettes 2898 Nome fortranblock Fortran Block Screenshot Contents Fortran Palette Description Dialog box Default properties Interfacing function Authors Palette User defined functions palette Description This block creates skeleton of the FORTRAN computing function Also it creates library file and object files Dialog box input ports sizes Number of regular input ports Properties Type vec of size 1 palettes 2899 output port sizes Number of regular output ports Properties Type vec of size 1 System parameters vector Number of parameters that this function accepts Properties Type vec of size 1 function name Name of the function to be generated Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function Interfacing function SCImodulesscicosblocksmacrosMiscfortranblocksci Authors Ramine Nikoukhah INRIA palettes 2900 Nome genericblock3 Generic block Block Screenshot Contents Generic block Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette User defined functions palette Description The block provides a generic interfacing function but the computational function needs to be defined separately either as a Scilab function or a Fortran or a C function Besides the name of the function user should specify information such as the type whether or not the block contains a direct feedth rough term The function realising computational functions of generic blocks of a Scicos diagram must be saved along with the diagram and loaded or dynamically linked before simulation palettes 2901 Dialog box Simulation function Name of the function to be loaded Properties Type str of size 1 Function type Type of the computational function supported by Scicos Properties Type vec of size 1 palettes 2902 Input ports sizes Number of regular input ports Properties Type mat of size 12 Input ports type Set the datatype of the regular input ports Properties Type vec of size 1 Iutput port sizes Number of regular input ports Properties Type mat of size 12 Output ports type Set the datatype of the regular output ports Properties Type vec of size 1 Input event ports sizes a vector of ones size of event input ports The size of the vector gives the number of event input ports Properties Type vec of size 1 Output events ports sizes a vector of ones size of event output ports The size of the vector gives the number of of event output ports Properties Type vec of size 1 Initial continuous state A column vector of Initial State Conditions Properties Type vec of size 1 Initial discrete state A column vector Initial discrete Conditions Properties Type vec of size 1 Initial object state A Scilab list that defined the initial object state oz Properties Type lis of size 1 Real parameters vector column vector Any parameters used in the block can be defined here as a column vector Properties Type vec of size 1 Integer parameters vector palettes 2903 column vector Any integer parameters used in the block can be defined here as a column vector Properties Type vec of size 1 Object parameters list A Scilab list that defined the list of the Object parameters opar Properties Type lis of size 1 Number of modes Number of Right hand side functions in the system Properties Type vec of size 1 Number of zerocrossings No of zerocrossings Properties Type vec of size 1 Initial firing vector vector Size of this vector corresponds to the number of event outputs The value of the ith entry specifies the time of the preprogrammed event firing on the ith output event port If less than zero no event is preprogrammed Properties Type vec of size sum6 Direct feedthrough character y or n specifies if block has a direct input to output feedthrough Properties Type vec of size 1 Time dependence Time dependance character y or n specifies if block output depends explicitly on time Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 palettes 2904 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function sinblk Interfacing function SCImodulesscicosblocksmacrosMiscgenericblock3sci Computational function SCImodulesscicosblockssrcfortransinblkf Type 4 Authors Alan Layec INRIA Ramine Nikoukhah INRIA palettes 2905 Nome scifuncblockm Scilab function block Block Screenshot Contents Scilab function block Palette Description Dialog box Default properties Interfacing function Computational function Palette User defined functions palette Description This block can realize any type of Scicos block The function of the block is defined interactively using dialogue boxes and in Scilab language During simulation these instructions are interpreted by Scilab the simulation of diagrams that include these types of blocks is slower For more information see Scicos reference manual palettes 2906 Dialog box input ports sizes a scalar Number of regular input ports Properties Type vec of size 1 output port sizes a scalar Number of regular output ports Properties Type vec of size 1 input event ports sizes a scalar Number of input event ports Properties Type vec of size 1 output events ports sizes a scalar Number of output event ports Properties Type vec of size 1 initial continuous state a column vector Properties Type vec of size 1 initial discrete state a column vector palettes 2907 Properties Type vec of size 1 System parameters vector a string c or d CBB or DBB other types are not supported Properties Type vec of size 1 initial firing vector vector Size of this vector corresponds to the number of event outputs The value of the ith entry specifies the time of the preprogrammed event firing on the ith output event port If less than zero no event is preprogrammed Properties Type vec of size sum4 is block always active other dialogues are opened consecutively where used may input Scilab code associated with the computations needed block initialization outputs continuous and discrete state output events date block ending Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing no mode no regular inputs port 1 size 11 type 1 regular outputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 0 continuoustime state no discretetime state no object discretetime state no name of computational function scifunc Interfacing function SCImodulesscicosblocksmacrosMiscscifuncblockmsci Computational function SCImodulesscicossrcfortranscifuncf Type 3 palettes 2908 21 Zero crossing detection palette palettes 2909 Nome Zerocrossingdetectionpal Zero crossing detection palette Block Screenshot Module xcos Description Zero crossing detection blocks are used to detect values crossing of state variables during the simula tion This blocks use the solvers ODE or DAE to do that operation Blocks CLINDUMMYf Dummy GENERALf Zero crossing NEGTOPOSf Threshold negative to positive POSTONEGf Threshold positive to negative ZCROSSf Threshold detection at zero palettes 2910 Nome GENERALf GENERALf title Block Screenshot Contents GENERALf title Palette Description Dialog box Default properties Interfacing function Computational function Palette Zero crossing detection palette Description Add here a paragraph of the function description Dialog box Input size The parameter description 1 Properties Type vec of size 1 Number of event output The parameter description 2 palettes 2911 Properties Type vec of size 1 Default properties always active no directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function zcross Interfacing function SCImodulesscicosblocksmacrosThresholdGENERALfsci Computational function SCImodulesscicosblockssrcfortranzcrossf Type 1 palettes 2912 Nome NEGTOPOSf Threshold negative to positive Block Screenshot Contents Threshold negative to positive Palette Description Default properties Interfacing function Computational function Authors Palette Zero crossing detection palette Description An output event is generated when the unique input crosses zero with a positive slope Default properties always active no directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function zcross palettes 2913 Interfacing function SCImodulesscicosblocksmacrosThresholdNEGTOPOSfsci Computational function SCImodulesscicosblockssrcfortranzcrossf Type 1 Authors Ramine Nikoukhah INRIA palettes 2914 Nome POSTONEGf Threshold positive to negative Block Screenshot Contents Threshold positive to negative Palette Description Default properties Interfacing function Computational function Authors Palette Zero crossing detection palette Description An output event is generated when the unique input crosses zero with a negative slope Default properties always active no directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function zcross palettes 2915 Interfacing function SCImodulesscicosblocksmacrosThresholdPOSTONEGfsci Computational function SCImodulesscicosblockssrcfortranzcrossf Type 1 Authors Ramine Nikoukhah INRIA palettes 2916 Nome ZCROSSf Threshold detection at zero Block Screenshot Contents Threshold detection at zero Palette Description Dialog box Default properties Interfacing function Computational function Authors Palette Zero crossing detection palette Description An output event is generated when all inputs if more than one cross zero simultaneously Dialog box Input size a positive integer Property Type vec of size 1 Default properties always active no palettes 2917 directfeedthrough yes zerocrossing yes mode no regular inputs port 1 size 11 type 1 numbersizes of activation inputs 0 numbersizes of activation outputs 1 continuoustime state no discretetime state no object discretetime state no name of computational function zcross Interfacing function SCImodulesscicosblocksmacrosThresholdZCROSSfsci Computational function SCImodulesscicosblockssrcfortranzcrossf Type 1 Authors Ramine Nikoukhah INRIA 2918 Capítulo 8 Programming xcos Blocks 1 C Computational Functions Programming xcos Blocks 2919 Nome Cmacros Utilities C macros Contents Cmacros Utilities C macros Module Description Inputsoutputs Events Parameters States and work Zero crossing surfaces and modes Authors Module xcos Description The following C macros are avialable by including the file in a C computational function Inputsoutputs Macro Description GetNinblk Get number of regular input port GetInPortRowsblkx Get number of rows first dimension of regular input port number x GetInPortColsblkx Get number of columns second dimension of re gular input port number x GetInPortSizeblkxy Get regular input port size number x y1 for the first dimension y2 for the second dimension GetInTypeblkx Get type of regular input port number x GetInPortPtrsblkx Get regular input port pointer of port number x GetRealInPortPtrsblkx Get pointer of real part of regular input port num ber x GetImagInPortPtrsblkx Get pointer of imaginary part of regular input port number x Getint8InPortPtrsblkx Get pointer of int8 typed regular input port num ber x Getint16InPortPtrsblkx Get pointer of int16 typed regular input port num ber x Getint32InPortPtrsblkx Get pointer of int32 typed regular input port num ber x Programming xcos Blocks 2920 Getuint8InPortPtrsblkx Get pointer of uint8 typed regular input port num ber x Getuint16InPortPtrsblkx Get pointer of uint16 typed regular input port number x Getuint32InPortPtrsblkx Get pointer of uint32 typed regular input port number x GetSizeOfInblkx Get the sizeof of the regular input port number x GetNoutblk Get number of regular output port GetOutPortRowsblkx Get number of rows first dimension of regular output port number x GetOutPortColsblkx Get number of columns second dimension of re gular output port number x GetOutPortSizeblkxy Get regular output port size number x y1 for the first dimension y2 for the second dimension GetOutTypeblkx Get type of regular output port number x GetOutPortPtrsblkx Get regular output port pointer of port number x GetRealOutPortPtrsblkx Get pointer of real part of regular output port num ber x GetImagOutPortPtrsblkx Get pointer of imaginary part of regular output port number x Getint8OutPortPtrsblkx Get pointer of int8 typed regular output port num ber x Getint16OutPortPtrsblkx Get pointer of int16 typed regular output port number x Getint32OutPortPtrsblkx Get pointer of int32 typed regular output port number x Getuint8OutPortPtrsblkx Get pointer of uint8 typed regular output port number x Getuint16OutPortPtrsblkx Get pointer of uint16 typed regular output port number x Getuint32OutPortPtrsblkx Get pointer of uint32 typed regular output port number x GetSizeOfOutblkx Get the sizeof of the regular output port number x Events Macro Description GetNevInblk Get the input event number GetNevOutblk Get number of event output port GetNevOutPtrsblk Get pointer of event output register Parameters Macro Description GetNiparblk Get number of integer parameters Programming xcos Blocks 2921 GetIparPtrsblk Get pointer of the integer parameters register GetNrparblk Get number of real parameters GetRparPtrsblk Get pointer of the real parameters register GetNoparblk Get number of object parameters GetOparTypeblkx Get type of object parameters number x GetOparSizeblkxy Get size of object parameters number x y1 for the first dimension y2 for the second dimension GetOparPtrsblkx Get pointer of object parameters number x GetRealOparPtrsblkx Get pointer of real object parameters number x GetImagOparPtrsblkx Get pointer of imaginary part of object parameters number x Getint8OparPtrsblkx Get pointer of int8 typed object parameters num ber x Getint16OparPtrsblkx Get pointer of int16 typed object parameters num ber x Getint32OparPtrsblkx Get pointer of int32 typed object parameters num ber x Getuint8OparPtrsblkx Get pointer of uint8 typed object parameters num ber x Getuint16OparPtrsblkx Get pointer of uint16 typed object parameters number x Getuint32OparPtrsblkx Get pointer of uint32 typed object parameters number x GetSizeOfOparblkx Get the sizeof of the object parameters number x States and work Macro Description GetNstateblk Get number of continuous state GetStateblk Get pointer of the continuous state register GetDstateblk Get number of discrete state GetNdstateblk Get pointer of the discrete state register GetNozblk Get number of object state GetOzTypeblkx Get type of object state number x GetOzSizeblkxy Get size of object state number x y1 for the first dimension y2 for the second dimension GetOzPtrsblkx Get pointer of object state number x GetRealOzPtrsblkx Get pointer of real object state number x GetImagOzPtrsblkx Get pointer of imaginary part of object state num ber x Getint8OzPtrsblkx Get pointer of int8 typed object state number x Getint16OzPtrsblkx Get pointer of int16 typed object state number x Getint32OzPtrsblkx Get pointer of int32 typed object state number x Getuint8OzPtrsblkx Get pointer of uint8 typed object state number x Programming xcos Blocks 2922 Getuint16OzPtrsblkx Get pointer of uint16 typed object state number x Getuint32OzPtrsblkx Get pointer of uint32 typed object state number x GetSizeOfOzblkx Get the sizeof of the object state number x GetWorkPtrsblkblk Get the pointer of the Work array Zero crossing surfaces and modes Macro Description GetNgblk Get number of zero crossing surface GetGPtrsblk Get pointer of the zero crossing register GetNmodeblk Get number of modes GetModePtrsblk Get pointer of the mode register Authors Alan Layec INRIA Programming xcos Blocks 2923 Nome Cstruct C Block structure of a computational function Contents Cstruct C Block structure of a computational function Module Description Inputsoutputs Events Parameters States and work Zero crossing surfaces and modes Miscallaneous Authors Module xcos Description The C structure of a xcos block defines all the fields to handle data provided by the simulator such inputsoutputs parameters states That structure of type is defined in the file and user must include that header in each computational functions in the form The fields that can be either C pointers or directly data are then accessible via the structure This access is a approach and most of users should prefer the approach for facilities purpose In the current version of xcos the structure is defined Inputsoutputs blocknin Integer that gives the number of regular input ports of the block One cant override the index when reading sizes of input ports in the array and the index when reading data in the array with a C computational function The number of regular input ports can also be got by the use of the C macros blockinsz An array of integers of size that respectively gives the first dimensions the second dimensions and the type of data driven by regular input ports Programming xcos Blocks 2924 Note that this array of size differs from the array and to provide full compatibilty with blocks that only use a single dimension Suppose that you have a block with three inputs the first is an int32 matrix of size 32 the second a single complex number matrix of size 11 and the last a real matrix of size 41 In thescicosmodel of such a block the inputs will be defined and the corresponding field at C computational function level will be coded as Do the difference here in the type numbers defined at the 213 and the type numbers defined at the 841110 The following table gives the corres pondance for all xcos type blockinptr An array of pointers of size nin1 that allow to directly access to the data contained in the regular input matrices Suppose the previous example block with three inputs an int32 matrix of size 32 a complex scalar and a real matrix of size 41 contains three pointers and should be viewed as arrays contained the data for the int32 the real and the complex matrices For ie to directly access to the data the user can use theses instructions One can also use the set of C macros to have the appropiate pointer of the data to handle and to handle number dimensions and type of regular input ports For the previous example that gives Finally note that the regular input port registers are only accessible for reading blocknout Integer that gives the number of regular output ports of the block One cant override the index when reading sizes of output ports in the array and the index when reading data in the array with a C computational function The number of regular output ports can also be got by the use of the C macros blockoutsz An array of integers of size that respectively gives the first dimensions the second dimensions and the type of data driven by regular output ports Note that this array of size differs from the array and to provide full compatibilty with blocks that only use a single dimension Suppose that you have a block with two outputs the first is an int32 matrix of size 32 the second a single complex number matrix of size 11 and the last a real matrix of size 41 In thescicosmodel of such a block the outputs will be defined and the corresponding field at C computational function level will be coded as Do the difference here in the type numbers defined Programming xcos Blocks 2925 at the 213 and the type numbers defined at the 841110 and please report to the previous table to have the correspondence for all xcos type blockoutptr An array of pointers of size nout1 that allow to directly acces to the data contained in the regular output matrices Suppose the previous example block with three outputs an int32 matrix of size 32 a complex scalar and a real matrix of size 41 contains three pointers and should be viewed as arrays contained the data for the int32 the real and the complex matrices For ie to directly access to the data the user can use theses instructions One can also use the set of C macros to have the appropiate pointer of the data to handle and to handle number dimensions and type of regular output ports For the previous example that gives Finally note that the regular output port registers must be only written for 1 Events blocknevprt Integer that gives the event input port number by which the block has been acti vated This number is a binary coding For ie if block have two event inputs ports can take the value 1 if the block has been called by its first event input port the value 2 if it has been called by the second event input port and 3 if it is called by the same event on both input port 1 and 2 Note that can be 1 if the block is internally called One can also retrieve this number by using the C macros blocknevout Integer that gives the number of event output ports of the block also called the length of the output event register One cant override the index when setting value of events in the output event register The number of event output ports can also be got by the use of the C macro blockevout Array of double of size nevout1 corresponding to the output event register That register is used to program date of events during the simulation When setting values in that array you must understand that you give a delay relative to the current time of simulator Programming xcos Blocks 2926 where is the date of the programmed event is the current time in the simulator and the value that must be informed in the output event register For ie suppose that you want generate an event with the first event output port 1ms after each calls of the block then youll use Note that every events generated from output event register will be asynchronous with event coming from event input port even if you set The event output register must be only written for 3 Parameters blocknrpar Integer that gives the length of the real parameter register One cant override the index when reading value of real parameters in the register The total number of real parameters can also be got by the use of the C macro blockrpar Array of double of size nrpar1 corresponding to the real parameter register That register is used to pass real parameters coming from the scilabxcos environment to your block model The C type of that array is or C xcos type Suppose that you have defined the following real parameters in thescicosmodel of a block you can retrieve the previous data in the C computational function with You can also use the C macro to get the pointer of the real parameter register For ie if we define the following in an interfacing function of a xcos block in the corresponding C computational function of that block well use Note that real parameters register is only accessible for reading blocknipar Integer that gives the length of the integer parameter register One cant override the index when reading value of integer parameters in the register The total number of integer parameters can also be got by the use of the C macro blockipar Array of int of size nipar1 corresponding to the integer parameter register That register is used to pass integer parameters coming from the scilabxcos environment to your block model The C type of that array is or C xcos type Suppose that you have defined the following integer parameters in thescicosmodel of a block you can retrieve the previous data in the C computational function with You can also use the C macro to get the pointer of the real parameter register Most of time in the xcos C block libraries the integer register is used to parametrize the length of real parameters For ie if you define the following in a block the array of real parameters parametrized by ipar can be retrieved in the correspondig C computational function with Note that integer parameters register is only accessible for reading blocknopar Integer that gives the number of the object parameters One cant override the index when accessing data in the arrays and in a C computational function Programming xcos Blocks 2927 This value is also accessible via the C macro blockoparsz An array of integer of size nopar2 that contains the dimensions of matrices of object parameters The first column is for the first dimension and the second for the second dimension For ie if we want the dimensions of the last object parameters well use the instructions The dimensions of object parameters can be get with the following C macro with an integer that gives the index of the object parameter blockopartyp An array of integer of size nopar1 that contains the type of matrices of object parameters The following table gives the correspondence for xcos type expressed in Scilab number in C number and also corresponding C pointers and C macros used for The type of object parameter can also be got by the use of the C macro For ie if we want the C number type of the first object parameter well use the following C instructions blockoparptr An array of pointers of size nopar1 that allow to directly acces to the data con tained in the object parameter Suppose that you have defined in the editor a block with the followingopar field inscicosmodel Then we have two object parameters one is an 32bit integer matrix with two rows and two columns and the second is a vector of complex numbers that can be understand as a matrix of size 13 At the C computational function level the instructions will respectively return the values 2123 and the instructions the values 11 and 84 will contain then two pointers and should be viewed as arrays contained data of object parameter as shown in the following figure For ie to directly access to the data the user can use theses instructions One can also use the set of C macros to have the appropiate pointer of the data to handle For the previous example that gives Note that object parameters register is only accessible for reading States and work blocknx Integer that gives the length of the continus state register One cant override the index when reading or writing data in the array or with a C computational function blockx Array of double of size nx1 corresponding to the continuous state register That gives the result of the computation of the state derivative A value of a continuous state is readable for ie the first state with the C instructions Note that on 4 user can write some initial conditions in that register Programming xcos Blocks 2928 The pointer of that array can also be retrieve via the C macro blockxd Array of double of size nx1 corresponding to the derivative of the continuous state register When systems are explicitly given in terms of Ordinary Differential Equations ODE it can be explicitly expressed or implicitly used in the residual vector when systems are expressed in terms of Differantial Algebraic Equations DAE Both systems must be programmed with For ie the Lorentz attractor written as an ODE system with three state variables of the form will be defined blockres Array of double of size nx1 corresponding to Differential Algebraic Equation DAE residual It is used to write the vector of systems that have the following form For ie the Lorentz attractor written as a DAE system with three state variables will be defined blocknz Integer that gives the length of the discrete state register One cant override the index when reading data in the array with a C computational function This value is also accessible via the C macros blockz Array of double of size nz1 corresponding to the discrete state register A value of a discrete state is directly readable for ie the second state with the C instructions Note that the state register should be only written for 4 and 2 The pointer of that array can also be retrieve via the C macro blocknoz Integer that gives the number of the discrete object states One cant override the index when accessing data in the arrays and in a C computational function This value is also accessible via the C macro blockozsz An array of integer of size noz2 that contains the dimensions of matrices of discrete object states The first column is for the first dimension and the second for the second dimension For ie if we want the dimensions of the last object state well use the instructions The dimensions of object discrete states can be get with the following C macro with an integer that gives the index of the discrete object state blockoztyp An array of integer of size noz1 that contains the type of matrices of discrete object states The following table gives the correspondence table for xcos type expressed in Scilab number in C number and also corresponding C pointers and C macros used for The type of discrete object state can also be got by the use of the C macro For ie if we want the C number type of the first discrete object state well use the following C instructions blockozptr An array of pointers of size noz1 that allow to directly acces to the data contained in the discrete object state Suppose that you have defined in the editor a block with the followingodstate field inscicosmodel Then we have two discrete object states one is an 32bit integer matrix with two rows and two Programming xcos Blocks 2929 columns and the second is a vector of complex numbers that can be understand as a matrix of size 13 At the C computational function level the instructions will respectively return the values 2123 and the instructions the values 11 and 84 will contain then two pointers and should be viewed as arrays contained data of discrete object state as shown in the following figure For ie to directly access to the data the user can use theses instructions One can also use the set of C macros to have the appropiate pointer of the data to handle For the previous example that gives Finally note that the discrete objects state should be only written for 4 and 2 blockwork A free pointer to set a working array for the block The work pointer must be firstly allocated when 4 and finally be free in the 5 Then a basic life cyle of that pointer in a C computational function should be Note that if a block use a pointer it will be called with 2 even if the block dont use discrete states The pointer of that array can also be retrieve via the C macro Zero crossing surfaces and modes blockng Integer that gives the number of zero crossing surface of the block One cant override the index when readingwriting data in the array with a C computational function The number of zero crossing surface can also be got by the use of the C macro blockg Array of double of size ng1 corresponding to the zero crossing surface register That register is used to detect zero crossing of state variable during time domain integration Note that it is accessible for writting for 9 The pointer of that array can also be retrieve via the C macro blocknmode Integer that gives the number of mode of the block One cant override the index when readingwriting data in the array with a C computational function The number of mode can also be got by the use of the C macro blockmode Array of integer of size nmode1 corresponding to the mode register That register is used to set the mode of state variable during time domain integration It is typically accessible for writting for 9 The pointer of that array can also be retrieve via the C macro Programming xcos Blocks 2930 Miscallaneous blocktype Integer that gives the type of the computational function For C blocks this number is equal to 4 blocklabel Strings array that allows to retrieve the label of the block Authors Alan Layec INRIA Programming xcos Blocks 2931 Nome Cutils Utilities C functions Contents Cutils Utilities C functions Module Description Authors Module xcos Description The header provides some utilities functions to interact with the simulator in the C computational functions void docoldrestart This function forces the solver to do a cold restart It should be used in situations where the block creates a non smooth signal Note that in most situations non smooth situations are detected by zerocrossings and this function is not needed This block is used in very exceptional situations int getphasesimulation That function returns an integer which says if the simulator is realizing time domain integration It can returns 1 The simulator is on a discrete activation time 2 The simulator is realizing a continuous time domain integration double getscicostime That function returns the current time of simulator int getblocknumber That function returns an integer the block index in the compiled structure Each block in the si mulated diagram have a single index and blocks are numbered from 1 to nblk the total number of blocks in the compiled structure void setblockerrorint Function to set a specific error during the simulation for the current block If it is used then after the execution of the computational function of the block the simulator will end and will return an error message associated to the number given in the integer argument The following calls are allowed setblockerror1 the block has been called with input out of its domain setblockerror2 singularity in a block setblockerror3 block produces an internal error Programming xcos Blocks 2932 setblockerror16 cannot allocate memory in block void endscicossim A very specific function to set the current time of the simulator to the final time integration Only expert user should use this function void setpointerxpropertyint pointer This function set a vector of integer to inform the type algebraic or differential of the continuous state variables of the block void scicosmallocsizet That function must be used to do allocation of scicos pointers inside a C computational function and in particular for 4 for the work pointer void scicosfreevoid p That function must be used to free scicos pointers inside a C computational function and in particular for 5 for the work pointer Authors Alan Layec INRIA Ramine Nikoukhah INRIA 2 Scilab Computational Functions Programming xcos Blocks 2933 Nome scistruct Scicos block structure of a scilab computational function Contents scistruct Scicos block structure of a scilab computational function Module Description Inputsoutputs Events Parameters States Zero crossing surfaces and modes Miscallaneous Authors Module xcos Description A Scicos computational function of type 5 can be realized by the use of a Scilab function That function doesnt really differs from all other scilab function one can use all functions and instructions of the scilab language inside that function to do the computation Such a function must be written in a file with extension sci must be loaded inside scilab by the common loading scilab function and must have two right hand side arguments and one left hand side argument as the following calling sequence When the simulator is calling such a computational function it build a scilab structure in the previous exemple this is the named rhslhs arguments from his own internal C reprensation of a block structure see for more details about the C structure of scicos blocks That scilab structure is a scilab typed list variable that have the following fields Each fields are then accessible inside the scilab computational function by the use of Inputsoutputs blocknin a scalar that gives the number of regular input ports This is a read only data blockinsz a vector of size that gives the dimensions and types of the regular input ports are the first dimensions are the second dimensions are the type of data C coding Programming xcos Blocks 2934 This is a read only data blockinptr a list of size that enclosed typed matrices for regular input ports Each element corres pond to only one regular input port Then ith matrix of the blockinptr list will have the dimensions and the type The data type that can be provided by regular input ports are 1 matrix of real numbers 2 matrix of complex numbers 3 matrix of int32 numbers 4 matrix of int16 numbers 5 matrix of int8 numbers 6 matrix of uint32 numbers 7 matrix of uint16 numbers 8 matrix of uint8 numbers This is a read only data blocknout a scalar that gives the number of regular output ports This is a read only data blockoutsz a vector of size that gives the dimensions and types of the regular output ports are the first dimensions are the second dimensions are the type of data C coding This is a read only data blockoutptr a list of size that enclosed typed matrices for regular output ports Each element correspond to only one regular output port Then ith matrix of the blockoutptr list will have the dimensions and the type The data type that can be provided by regular output ports are 1 matrix of real numbers 2 matrix of complex numbers 3 matrix of int32 numbers 4 matrix of int16 numbers 5 matrix of int8 numbers 6 matrix of uint32 numbers 7 matrix of uint16 numbers 8 matrix of uint8 numbers Values of regular output ports will be saved in theC structure of the block only for 6 and 1 Programming xcos Blocks 2935 Events blocknevprt a scalar given the event input port number binary coding which have activated the block This is a read only data blocknevout a scalar given the number of output event port of the block This is a read only data blockevout a vector of size corresponding to the register of output event Values of output event register will be saved in theC structure of the block only for 3 Parameters blocknrpar a scalar given the number of real parameters This is a read only data blockrpar a vector of size corresponding to the real parameter register This is a read only data blocknipar a scalar given the number of integer parameters This is a read only data blockipar a vector of size correspondig to the integer parameter register This is a read only data blocknopar a scalar given the number of object parameters This is a read only data blockoparsz a matrix of size that respectively gives the first and the second dimension of object parameters This is a read only data blockopartyp a vector of size given the C coding type of data This is a read only data blockopar a list of size given the values of object parameters Each element of can be either a typed matrix or a list Only matrix that encloses numbers of type real complex int32 int16 int8 uint32 uint16 and uint8 are allowed all other types of scilab data will be enclosed in a sublist This is a read only data States blocknz a scalar given the number of discrete state for the block This is a read only data blockz a vector of size corresponding to the discrete state register Values of discrete state register will be saved in theC structure of the block only for 4 6 2 and 5 blocknoz a scalar that gives the number of discrete object state This is a read only data blockozsz a matrix of size that respectively gives the first and the second dimension of discrete object state This is a read only data blockoztyp a vector of size given the C coding type of data blockoz a list of size given the values of discrete object states Each element of can be either a typed matrix or a list Only matrix that encloses numbers of type real complex int32 int16 int8 uint32 uint16 and uint8 are allowed all other types of scilab data will be enclosed in a sublist Values of discrete object state will be saved in theC structure of the block only for 4 6 2 and 5 blocknx a scalar given the number of continuous state for the block This is a read only data blockx a vector of size given the value of the continuous state register Values of the continuous state register will be saved in theC structure of the block only for 4 6 and 2 Programming xcos Blocks 2936 blockxd a vector of size given the value of the derivative continuous state register Values of the derivative continuous state register will be saved in theC structure of the block only for 4 6 0 and 2 blockres a vector of size corresponding to the Differential Algebraic Equation DAE residual Values of that register will be saved in theC structure of the block only for 0 and 10 Zero crossing surfaces and modes blockng a scalar given the number of zero crossing surfaces for the block This is a read only data blockg a vector of size corresponding to the zero crossing register Values of that register will be saved in theC structure of the block only for 9 blocknmode a scalar given the number of mode for the block This is a read only data blockmode a vector of size that corresponds to the mode register Values of that register will be saved in theC structure of the block only for 9 with 1 Miscallaneous blocktype a scalar given the type of the block This is a read only data blocklabel a string given the label of the block This is a read only data Authors Alan Layec INRIA 3 Utilities Functions Programming xcos Blocks 2937 Nome curblock Return the current called xcos block during the simulation Module xcos blkcurblock Parameters blk the current block number in the compiled structure Authors Ramine Nikoukhah INRIA Programming xcos Blocks 2938 Nome getblocklabel Get the label of a scicos block Module xcos labelgetblocklabelblk Parameters blk Integer parameter Set the index of a block in the compiled structure label String parameter Gives the string of the label of the block numbered blk Programming xcos Blocks 2939 Nome getscicosvars Supervisor utility function myvargetscicosvarsstr myvargetscicosvarsstr1str2 Module xcos Description That utility function is used to retrieve working arrays of Scicos simulator and compiler during simu lation It can be used inside a Scilab block to get information of all type of blocks That function is very useful to debug diagrams and to do prototypes of simulations myvargetscicosvarsstr myvargetscicosvarsstr1str2 Parameters strstr1str2 That parameter can be a string or a matrix of string The following entries are allowed x get the continuous state register nx get the length of the continuous state register xptr get the pointers register of the continuous state register zcptr get the pointers register of the zerocrossing surfaces register z get the discrete state register nz get the length of the continuous state register zptr get the pointers register of the discrete state register noz get the number of elements of the discrete object state list oz get the discrete object state list ozsz get the size of the elements of the discrete object state list oztyp get the type of the elements of the discrete object state list ozptr get the pointers register of the discrete object state list rpar get the real parameter register rpptr get the pointers register of the real parameter register ipar get the integer parameter register ipptr get the pointers register of the integer parameter register opar get the object parameter list Programming xcos Blocks 2940 oparsz get the size of the elements of the object parameter list opartyp get the type of the elements of the object parameter list opptr get the pointers register of the object parameter list outtb get the output register inpptr get the pointers register of the number of regular input ports outptr get the pointers register of the number of regular output ports inplnk get the pointers register of the links connected to regular input ports outlnk get the pointers register of the links connected to regular output ports subs not used tevts get the current date register of the agenda evtspt get the current event register of the agenda pointi get the next event to be activated iord get the vector of blocks activated at the start of the simulation oord get the vector of blocks whose outputs affects computation of continuous state derivatives zord get the vector of blocks whose outputs affects computation of zerocrossing surfaces funtyp get the vector of type of computational functions ztyp get the pointers vector for blocks which use zerocrossing surfaces cord get the vector of blocks whose outputs evolve continuously ordclk get the matrix associated to blocks activated by output activation ports clkptr get the pointers vector for output activation ports ordptr get the pointers vector to ordclk designating the part of ordclk corresponding to a given activation critev get the vector of the critical events mod get the vector pointers of block modes nmod get the length of the vector pointers of block modes iz get the register that store pointers of block work izptr get the pointers vector of the register that store C pointers of block work nblk get the number of block outtbptr get the register that store C pointers of outtb Programming xcos Blocks 2941 outtbpsz get the register that store the size of the elements of outtb outtbtyp get the register that store the type of the elements of outtb nlnk get the number of output ncord get the number of blocks whose outputs evolve continuously nordptr get the number of blocks whose outputs evolve by activation iwa nd blocks get a scilab list that contains all block structures contains in the diagram ng get length of the zerocrossing surfaces register g get the zerocrossing surfaces register t0 get the current time of the simulation tf get the final time of the simulation Atol get the integrator absolute tolerance for the numerical solver rtol get the integrator relative tolerance for the numerical solver ttol get the tolerance on time of the simulator deltat get the maximum integration time interval hmax get the maximum step size for the numerical solver nelem get the number of elements in outtb outtbelem get the vector of the number of elements in outtb myvar That output parameter can be an int32 matrix a double matrix or a Tlist This is given by the input parameter See Also DEBUGSCICOS Debug block Scicos Block Authors Alan Layec INRIA Ramine Nikoukhah INRIA Programming xcos Blocks 2942 Nome phasesimulation Get the current simulation phase psimphasesimulation Module xcos Description That function says if the Scicos simulator is realizing the time domain integration psimphasesimulation Parameters psim get the current phase of the simulation 1 The simulator is on a discrete activation time 2 The simulator is realizing a continuous time domain integration Programming xcos Blocks 2943 Nome pointerxproperty Get the type of a continuous time state variable xproppointerxproperty Module xcos Description This function returns a vector that informs the type algebraic or differential of the continuous state variables of a block xproppointerxproperty Parameters xprop The value gives the type of the states 1 an algebraic state 1 a differential state See Also setxproperty Set the type of a continuous time state variable Scilab Function Programming xcos Blocks 2944 Nome scicostime Returns the current time during simulation Module xcos tscicostime Parameters t that is the current simulated time returned in real number Programming xcos Blocks 2945 Nome setblockerror set the block error number setblockerrorn Module xcos Description Function to set a specific error during the simulation for the current block If it is used then after the execution of the computational function of the block the simulator will end and will return an error message associated to the number given in argument setblockerrorn Parameters n an error number The following calls are allowed setblockerror1 the block has been called with input out of its domain setblockerror2 singularity in a block setblockerror3 block produces an internal error setblockerror16 cannot allocate memory in block Authors Alan Layec INRIA Programming xcos Blocks 2946 Nome setxproperty Set the type of a continuous time state variable setxpropertyxprop Module xcos Description This function set a vector to inform the type algebraic or differential of the continuous state variables of a block setxpropertyxprop Parameters xprop The value gives the type of the states 1 an algebraic state 1 a differential state See Also pointerxproperty Get the type of a continuous time state variable Scilab Function 2947 Capítulo 9 Scilab Data Structures 1 Blocks Scilab Data Structures 2948 Nome scicosblock Define a block structure Module xcos block Basic structure that define a xcos block That structure includes fields graphics model gui and doc Size 5 Type scilab list graphics Scilab object including graphical information concerning the features of the block Size 14 Type scilab list model Scilab list that contains the features of the block used for the compilation Size 23 Type Scilab list gui The name of the Scilab GUI function associated with the block Size 1 Type string doc Field used for documentation of the block Size 1 Type string File content SCImodulesscicosmacrosscicosscicosscicosblocksci Scilab Data Structures 2949 Nome scicosgraphics Define a graphics structure Module xcos graphics Scilab object including graphical information concerning the features of the block Size 14 Type scilab list orig Vector xoyo where xo is the x coordinate of the block origin and yo is the y coordinate of the block origin xoyo is the coordinate of downleft point of the block shape Size 2 Type row vector of real sz Vector wh where w is the block width and h the block height Size 2 Type row vector of real flip Set the block orientation If true the input ports are on the left of the box and output ports are on the right If false the input ports are on the right of the box and output ports are on the left Size 1 Type boolean theta Set the angle of the Scicos object This value is in degree and is included in 360360 Size 1 Type real exprs Strings including formal expressions used in the dialog box of the block Scilab Data Structures 2950 Size number of formal expressions Type column vector of strings pin Vector pini is the number of the link connected to the ith regular input port counting from one or 0 if this port is not connected Size number of regular input ports Type column vector of integers pout Vector pouti is the number of the link connected to the ith regular output port counting from one or 0 if this port is not connected Size number of regular output ports Type column vector of integers pein Vector peini is the number of the link connected to the ith event input port counting from one or 0 if this port is not connected Size number of events input ports Type column vector of integers peout Vector peouti is the number of the link connected to the ith event output port counting from one or 0 if this port is not connected Size number of events output ports Type column vector of integers gri Strings including Scilab graphics expressions for customizing the block graphical aspect This field may be set with Icon submenu Size Type column vector of strings id A string including an identification for the block The string is displayed under the block in the diagram Size 1 Type string inimplicit A vector of strings including E or I Scilab Data Structures 2951 E and I stand respectively for explicit and implicit port and this vector indicates the nature of each input port For regular blocks not implicit this vector is empty or contains only E Size nul or number of regular input ports Type column vector of strings outimplicit A vector of strings including E or I E and I stand respectively for explicit and implicit port and this vector indicates the nature of each output port For regular blocks not implicit this vector is empty or contains only E Size nul or number of regular output ports Type column vector of strings File content SCImodulesscicosmacrosscicosscicosscicosgraphicssci Scilab Data Structures 2952 Nome scicosmodel Define a model structure Module xcos model Scilab list that contains the features of the block used for the compilation Size 23 Type Scilab list sim A list containing two elements The first element is a string containing the name of the computa tional function C Fortranor Scilab The second element is an integer specifying the type of the computational function Currently type 4 and 5 are used but older types continue to work to ensure backward compatibility For some older case sim can be a single string and that means that the type is supposed to be 0 Size 2 Type Scilab list in A vector specifying the number and size of the first dimension of regular input ports indexed from top to bottom of the block If no input port exist in The size can be negative equal to zero or positive If a size is less than zero the compiler will try to find the appropriate size If a size is equal to zero the compiler will affect this dimension by added all positive size found in that vector If a size is greater than zero then the size is explicitly given Size number of regular input ports Type column vector of integer numbers in2 A vector specifying the second dimension of regular input ports indexed from top to bottom of the block in with in2 formed then the regular input sizes matrix For compatibility this dimension can stay empty That means that the dimensions of input ports will be in1 The size can be negative equal to zero or positive Scilab Data Structures 2953 If a size is less than zero the compiler will try to find the appropriate size If a size is equal to zero the compiler will affect this dimension by added all positive size found in that vector If a size is greater than zero then the size is explicitly given Size number of regular input ports Type column vector of integer numbers intyp A vector specifying the types of regular input ports Its sizes is equal to the sizes of in The types of regular input ports can be 1 real matrix 2 complex matrix 3 int32 matrix 4 int16 matrix 5 int8 matrix 6 uint32 matrix 7 uint16 matrix 8 uint8 matrix Size number of regular input ports Type column vector of integer numbers out A vector specifying the number and size of the first dimension of regular output ports indexed from top to bottom of the block If no output port exist out The size can be negative equal to zero or positive If a size is less than zero the compiler will try to find the appropriate size If a size is equal to zero the compiler will affect this dimension by added all positive size found in that vector If a size is greater than zero then the size is explicitly given Size number of regular output ports Scilab Data Structures 2954 Type column vector of integer numbers out2 A vector specifying the second dimension of regular output ports indexed from top to bottom of the block out with out2 formed then the regular output sizes matrix For compatibility this dimension can stay empty That means that the dimensions of output ports will be out1 That dimension can be negative equal to zero or positive If a size is less than zero the compiler will try to find the appropriate size If a size is equal to zero the compiler will affect this dimension by added all positive size found in that vector If a size is greater than zero then the size is explicitly given Size number of regular output ports Type column vector of integer numbers outtyp A vector specifying the types of regular output ports Its sizes is equal to the sizes of out The types of regular output ports can be 1 real matrix 2 complex matrix 3 int32 matrix 4 int16 matrix 5 int8 matrix 6 uint32 matrix 7 uint16 matrix 8 uint8 matrix Size number of regular output ports Type column vector of integer numbers evtin A vector specifying the number and sizes of activation inputs Currently activation ports can be only of size one If no event input port exists evtin must be equal to Scilab Data Structures 2955 Size number of input event ports Type column vector of integer numbers evtout A vector specifying the number and sizes of activation outputs Currently activation ports can be only of size one If no event output port exists evtout must be equal to Size number of output event ports Type column vector of integer numbers state Vector containing initial values of continuoustime state Must be if no continuous state Size number of continuoustime state Type column vector of real numbers dstate Vector containing initial values of discretetime state Must be if no discrete state Size number of discretetime state Type column vector of real numbers odstate List containing initial values of objects state Must be list if no objects state Objects state can be any types of scilab variable In the computational function case of type 4 C blocks only elements containing matrix of real complex int32 int16 int8 uint32 uit16 and uint8 will be correctly provided for readindwriting Size number of objects state Type scilab list of scilab objects rpar The vector of floating point block parameters Must be if no floating point parameters Size number of real parameters Type column vector of real numbers ipar Scilab Data Structures 2956 The vector of integer block parameters Must be if no integer parameters Size number of integer parameters Type column vector of integer numbers opar List of objects block parameters Must be list if no objects parameters Objects parameters can be any types of scilab variable In the computational function case of type 4 C blocks only elements containing matrix of real complex int32 int16 int8 uint32 uit16 and uint8 will be correctly provided for reading Size number of objetcs parameters Type list of scilab object blocktype Character that can be set to c or d indifferently for standard blocks x is used if we want to force the computational function to be called during the simulation phase even if the block does not contribute to computation of the state derivative l m and s are reserved Not to be used Size 1 Type Character firing Vector of initial event firing times of size equal to the number of activation output ports see evout It contains output initial event dates Events generated before any input event arises Negative values stands for no initial event on the corresponding port Size number of output event ports Type column vector of real numbers deput Boolean vector depu dept depu true if block is always active output depends continuously of the time dept true if block has direct feedthrough ie at least one of the outputs depends directly not through the states on one of the inputs In other words when the computational function is called with flag 1 the value of an input is used to compute the output Size 2 Scilab Data Structures 2957 Type Boolean vector label String that defines a label It can be used to identify a block in order to access or modify its para meters during simulation Size 1 Type string nzcross Number of zerocrossing surfaces Size Number of zerocrossing surfaces Type column vector of integer numbers nmode Length of the mode register Note that this gives the size of the vector mode and not the total number of modes in which a block can operate in Suppose a block has 3 modes and each mode can take two values then the block can have up to 238 modes Size Number of modes Type column vector of integer numbers equations Used in case of implicit blocks Data structure of type modelica which contains modelica code description if any That list contains four entries model a string given the name of the file that contains the modelica function inputs a colunm vector of strings that contains the names of the modelica variables used as inputs outputs a colunm vector of strings that contains the names of the modelica variables used as outputs parameters a list with two entries The first is a vector of strings for the name of modelica variable names used as parameters and the second entries is a list that contains the value of parameters Names of modelica states can also be informed with parameters In that case a third entry is used to do the difference between parameters and states For ie moparameterslistCvlistCv01 means that C is a parameter0 of value C and v is a state1 with initial value v Scilab Data Structures 2958 Size 5 Type scilab list File content SCImodulesscicosmacrosscicosscicosscicosmodelsci 2 CompilationSimulation Scilab Data Structures 2959 Nome scicoscpr Compiled Scicos structure Module xcos cpr The Scilab object cpr contains the result of the compilation That structure includes fields state sim cor and corinv Size 5 Type scilab list state Scilab typed list of type xcs It contains all the states of the model that is everything than can evolve during the simulation state contains x z oz iz tevts evtspt pointi and outtb Size 9 Type scilab tlist sim Scilab typed list of type scs It contains static arrays coming from the result of the compilation That arrays does not evolve during the simulation Size 33 Type scilab tlist cor It is a list with same recursive structure as scsm Each leaf contains the index of associated block in sim data structure Size number of objects in scsm Type scilab list corinv corinvi is the path of i th block defined in sim data structure in the scsm data structure Size number of blocks in the compiled structre Type scilab list File content SCImodulesscicosmacrosscicosscicosscicoscprsci Scilab Data Structures 2960 Nome scicossim Define a sim structure Module xcos sim Scilab typed list of type scs It contains static arrays coming from the result of the compilation That arrays does not evolve during the simulation Size 33 Type scilab tlist funs A list containing names of the computational functions or scilab functions Size number of blocks Type list of strings andor scilab function xptr A vector pointer to the continuous time state register x The continuoustime state of block i is statexsimxptrisimxptri11 Size number of blocks 1 Type column vector of integers zptr A vector pointer to the discrete time state register z The discretetime state of block i is statezsimzptrisimzptri11 Size number of blocks 1 Type column vector of integers ozptr A vector pointer to the object discrete state register oz The object discrete state of block i is stateozsimozptrisimozptri11 Size number of blocks 1 Type column vector of integers zcptr A vector pointer to the zerocrossing surfaces register That vector gives by block the used number of the zerocrossing Size number of blocks 1 Scilab Data Structures 2961 Type column vector of integers inpptr siminpptri1siminpptri gives the number of regular input ports of the i block inpptri points to the beginning of ith block inputs within the indirection table inplnk Size number of blocks 1 Type column vector of integers outptr simoutptri1simoutptri gives the number of regular ouyput ports of the i block outptri points to the beginning of ith block outputs within the indirection table outlnk Size number of blocks 1 Type column vector of integers inplnk cprsiminplnkcprsiminpptri1j is the index of the link connected to the jth input port of the ith block where j goes from 1 to cprsiminpptri1cprsiminpptri Size total number of regular input port Type column vector of integers outlnk cprsimoutlnkcprsimoutptri1j is the index of the link connected to the jth output port of the ith block where j goes from 1 to cprsimoutptri1cprsimoutptri Size total number of regular output port Type column vector of integers rpar Vector of real parameters that is obtained by concatenating the real parameters registers of all the blocks Size total number of real parameters Type column vector of real numbers rpptr A vector pointer to the real parameters register rpar The real parameters of block i are simrparsimrpptrisimrpptri11 Size number of blocks 1 Type column vector of integer ipar Vector of integer parameters that is obtained by concatenating the integer parameters registers of all the blocks Scilab Data Structures 2962 Size total number of integer parameters Type column vector of integer ipptr A vector pointer to the integer parameters register ipar The integer parameters of block i are simiparsimipptrisimipptri11 Size number of blocks 1 Type column vector of real numbers opar List of object parameters that is obtained by concatenating the list of object parameters of all the blocks Size total number of object parameters Type list of scilab objects opptr A vector pointer to the object parameters list opar The object parameters of block i are simoparsimopptrisimopptri11 Size number of blocks 1 Type column vector of integers clkptr A vector pointer to output activation ports cprsimclkptricprsimclkptri11 gives the number of output event ports of the block i Size number of blocks 1 Type column vector of integers ordptr A vector pointer to ordclk designating the part of ordclk corresponding to a given activation cprsimordptricprsimordptri11 points to the region within ordclk indicates the number of blocks activated by the output event ports numbered i Size number of sources of activation 1 Type column vector of integers execlk Unused Size Type matrix of real ordclk A matrix associated to blocks activated by output activation ports The first column contains the block number and the second the event code by which the block should be called Scilab Data Structures 2963 Size total number of blocks summed by source of activations Type matrix of integers cord A matrix associated to always active blocks The first column contains the block number and the second the event code by which the block should be called Size ncord Type matrix of integers oord Subset of cord Blocks of that matrix have outputs which affect computation of continuous state derivatives Size noord Type matrix of integers zord Subset of zord Blocks of that matrix have outputs which affect computation of zerocrossing sur faces Size nzord Type matrix of integers critev A vector of size equal to the number of activations and containing zeros and ones The value one indicates that the activation is critical in the sense that the continuoustime solver must be cold restarted Size number of source of activation Type column vector of integers nb Number of blocks Note that the number of blocks may differ from the original number of blocks in the diagram because cpass2 may duplicate some conditional blocks Size 1 Type integer ztyp A vector of size equal to the number of blocks A 1 entry indicates that the block may have zerocrossings even if it doesnt in the context of the diagram Usually not used by the simulator Size number of blocks Type column vector of integers Scilab Data Structures 2964 nblk Not used Set to nb Size 1 Type integer ndcblk Not used Size Type integer subscr Not used Size 0 Type empty real funtyp A vector of size equal to the number of blocks indicating the type of the computational function of the block Block type can be 0 through 5 Currently only type 4 C language and type 5 Scilab language computational functions should be used But older blocks can also be used Size number of blocks Type column vector of integer iord A matrix associated to blocks that must be activated at the start of the simulation This includes blocks inheriting from constant blocks and always active blocks Size niord Type matrix of integers labels A string vector of size equal to the number of blocks containing block labels Size numbers of blocks Type column vector of strings modptr A vector pointer to the block modes Size number of blocks 1 Type column vector of integer File content SCImodulesscicosmacrosscicosscicosscicossimsci Scilab Data Structures 2965 Nome scicosstate Define a state structure Module xcos state Scilab typed list of type xcs It contains all the states of the model that is everything than can evolve during the simulation state contains x z oz iz tevts evtspt pointi and outtb Size 9 Type scilab tlist x The continuoustime state register which is obtained by concatenating the continuoustime states of all the blocks Size total of all the size of continuoustime state registers Type column vector of real numbers z The discretetime state register which is obtained by concatenating the discretetime states of all the blocks Size total of all the size of discretetime state registers Type column vector of real number oz The list of the object discretetime state which is obtained by concatenating the object discretetime states of all the blocks Size total of all the size of object state Type list of scilab object iz Vector of size equal to the number of blocks That vector is used to store pointers of the working state register work If a block needs to allocate memory at initialization flag 4 the associated pointer is saved here Size number of blocks Type column vector of real numbers tevts Scilab Data Structures 2966 Vector of size equal to the number of activation sources It contains the scheduled times for pro grammed activations in evtspt Size number of activation sources Type column vector of integers evtspt Vector of size equal to the number of activation sources It is an event scheduler Size number of activation sources Type column vector of integers pointi The number of the next programmed event Size 1 Type integer outtb Scilab list containing all output registers of blocks Each element of that list contains typed ma trixbased data Size number of regular output ports Type list of scilab matrix File content SCImodulesscicosmacrosscicosscicosscicosstatesci 3 Diagram Scilab Data Structures 2967 Nome scicosdiagram Define a scsm structure Module xcos diagram Size 4 Type scilab list props Diagram properties This entry contains various informations such some main diagram initials values This variable is a tlist of type and contains wpar title tol tf context options and doc Size 11 Type Scilab tlist of type objs List of objects included in the Scicos diagram The objects used in scicos areblock link and Text The objects can also be deleted object data structure Deleted object data structure is marked listDeleted Size total number of objects in the diagram Type Scilab tlist of type or Text version A string that gives the version of the Scicos diagram This is used to provide compatibility with old diagram Note that you can get the current version of Scicos by using the entry About scicos in the help menu or by using the function getscicosversion Size 1 Type String File content SCImodulesscicosmacrosscicosscicosscicosdiagramsci Scilab Data Structures 2968 Nome scicosparams Define a param structure Module xcos params Size 11 Type scilab list wpar This vector is not currently used It may be used in the future to code window sizes of the editor Size 6 Type column vector or real title Vector of character strings where the first one is the diagram title and default name of save file name and the second one is the path of the directory of the file name Size 2 Type row vector of strings tol A vector containing simulation parameters including various tolerances used by the solver atol Integrator absolute tolerance for the numerical solver rtol Integrator relative tolerance for the numerical solver ttol Tolerance on time If an integration period is less than ttol the numerical solver is not called deltat Maximum integration time interval If an integration period is larger than deltat the numerical solver is called more than once in such a way that for each call the integration period remains below deltat scale Scilab Data Structures 2969 Realtime scaling the value 0 corresponds to no realtime scaling It associates a Scicos simulation time to the real time in seconds A value of 1 means that each Scicos unit of time corresponds to one second solver Choice of numerical solver The value 0 implies an ODE solver and 100 implies a DAE solver hmax Maximum step size for the numerical solver 0 means no limit Size 7 Type column vector of real tf Final time simulation The simulation stops at this time The default value is 100000 Size 1 Type real context A vector of strings containing Scilab instructions defining Scilab variables to be used inside blocks dialog box as symbolic parameters All valid Scilab instructions can be used and also comments Size number of lines of the context Type column vector of strings void1 unused field Size Type options Scilab object of type scsopt defining graphical properties of the editor such as background color and link color The fields are the following Scilab Data Structures 2970 3D A list with two entries The first one is a boolean indicating whether or not blocks should have 3D aspect The second entry indicates the color in the current colormap to be used to create the 3D effect The default is 33 which corresponds to gray added by Scicos to the standard colormap which contains 32 colors The default value is listt33 Background Vector with two entries background and foreground colors The default value is 81 link Default link colors for regular and activation links These colors are used only at link construction Changing them does not affect already constructed links The default value is 15 which corresponds to black and red if the standard Scilab colormap is used ID A list of two vectors including font number and sizes The default value is 5141 Cmap An n3 matrix containing RGB values of colors to be added to the colormap The default value is 080808 ie the color gray Size 6 Type scilab tlist of type scsopt void2 unused field Size Type void3 unused field Scilab Data Structures 2971 Size Type doc User defined diagram documentation structure Size 1 Type Strings File content SCImodulesscicosmacrosscicosscicosscicosparamssci 4 Links Scilab Data Structures 2972 Nome scicoslink Define a link structure Module xcos link Size 8 Type scilab list xx Vector of x coordinates of the link path A link is defined as a polyline line Size number of points of the link Type column vector of real numbers yy Vector of y coordinates of the link path A link is defined as a polyline line Size number of points of the link Type column vector of real numbers id Character string the link identification Size 1 Type string thick Vector of size two defining line thickness Size 2 Type row vector of integers ct The first entry of this vector designates the color and the second the nature of the link The second entry is 1 for a regular link 1 for an activation link and 2 for an implicit link Size 2 Type row vector of integers from Scilab Data Structures 2973 Vector of size three including the block number port number and port type 0 for output 1 for input at the origin of the link Note that the third entry may be 1 if the link is implicit otherwise it is zero Size 3 Type row vector of integers to Vector of size three including the block number port number and port type 0 for output 1 for input at the destination of the link Note that the third entry may be 1 if the link is implicit otherwise it is zero Size 3 Type row vector of integers File content SCImodulesscicosmacrosscicosscicosscicoslinksci 2974 Capítulo 10 Scilab Utilities Functions Scilab Utilities Functions 2975 Nome buildouttb Build of the sublist cprstateouttb outtbbuildouttblnkszlnktyp Module xcos Description Build an initialized outtb list outtbbuildouttblnkszlnktyp Parameters outtb a list of size n lnksz That parameter gives the size of Scilab object in outtb This matrix of integer or real numbers can have a n2 or 2n size lnktyp That parameters gives the type of Scilab object in outtb 1 double 2 complex 3 int32 4 int16 5 int8 6 uint32 7 uint16 8 uint8 else double This matrix of integer or real numbers can have a n1 or 1n size Authors Alan Layec INRIA Scilab Utilities Functions 2976 Nome createpalette Palette generator routinesIntFunc createpalettePath Module xcos Description This function generates a palette if Path is a string indicating the directoy in which the interfacing functions of the blocks are to be found If Path is not present or if it is t then standard scicos palettes are regenerated If f then only IntFunc list of interfacing functions is returned List of routines is empty in this case routinesIntFunc createpalettePath Parameters Path a string given the directory path that contains Scicos blocks interfacing functions routines a vector of strings that contains names of computational functions used in scicos blocks IntFunc a vector of strings that contains names of interfacing functions used in scicos blocks File content SCImodulesscicosmacrosscicosutilscreatepalettesci Scilab Utilities Functions 2977 Nome getscicosversion Get the current Scicos version scicosver getscicosversion Module xcos Description This function is used to know the current version number of Scicos scicosver getscicosversion Parameters scicosver a string given the current number version of Scicos Example Get the scicos version getscicosversion File content SCImodulesscicosmacrosscicosutilsgetscicosversionsci Authors Alan Layec INRIA Scilab Utilities Functions 2978 Nome scicosdebug Set the level of the Scicos debugging scicosdebuglevel levelscicosdebug Module xcos Description This Scilab function is used to set the debug level of a Scicos simulation One can used it in the Calc mode of the Scicos editor or as an instruction in a Scilab block or in an interfacing function scicosdebuglevel levelscicosdebug Parameters level setget the current level of the Scicos simulation debugging 0 no debugging 1 light debugging information printout 2 more information printout and execution of Debug Block if any in diagram 3 silent debugging mode no information printout and execution of Debug Block if any in diagram See Also DEBUGSCICOS Debug block Scicos Block Authors Alan Layec INRIA Ramine Nikoukhah INRIA Scilab Utilities Functions 2979 Nome var2vec Transform a scilab variable in a vector of double vecvar2vecvar Module xcos Description var2vec vec2var functions are used inside the interfacing functions of Scilab blocks to give the possibility to the user to handle Scilab objects with the real parameter rpar and with the discrete state register z vecvar2vecvar Parameters var Input parameter Can be any types of Scilab objects vec Output parameter A vector of real numbers Example alistcos112 a a1 cos a2 11 2 bvar2veca b 4244314 1273313 8488314 2122314 4941324 8488314 5093313 2122314 2122314 9881324 11 2 See Also vec2var Transform a vector of double in a scilab variable Scilab Function Scilab Utilities Functions 2980 Nome vec2var Transform a vector of double in a scilab variable varvec2varvec Module xcos Description var2vec vec2var functions are used inside the interfacing functions of Scilab blocks to give the possibility to the user to handle Scilab objects with the register of real parameters rpar and with the discrete state register z varvec2varvec Parameters vec Input parameter A vector of real numbers var Output parameter Can be any types of Scilab objects Example alistcos112 a a1 cos a2 11 2 bvar2veca b 4244314 1273313 8488314 2122314 4941324 8488314 5093313 2122314 2122314 9881324 11 2 cvec2varb c c1 cos c2 11 2 Scilab Utilities Functions 2981 See Also var2vec Transform a scilab variable in a vector of double Scilab Function 2982 Nome xcos Block diagram editor and GUI for the hybrid simulator xcosfilename xcosscsmlist Module xcos Description Xcos is a visual editor for constructing models of hybrid dynamical systems Invoking Xcos with no argument opens up an empty Xcos window Models can then be assembled loaded saved compiled simulated using GUI of Xcos Xcos serves as an interface to the various block diagram compilers and the hybrid simulator scicosim xcosmydiagramxcos Parameters filename a character string containing the path of the diagram file cos cosf or xcos extension If no input argument is used an empty diagram is opened default name Untitled scsmlist a Xcos diagram structure after edition Example Open a new diagram xcos xcos Load a diagram xcos SCIscicosdemosbouncecosf Load a structure loadmondiagrcos xcosscsm See Also scicosim Scicos batch simulation function Scilab Function scicossimulate Function for running xcos simulation in batch mode Scilab Function Menu entries 2983 Nome Menuentries Editor menu entries File menu FileNew Clicking on the New menu item loads an empty diagram in the active editor xcos window If the previous content of the window is not saved it will be lost With this menu you can open a new diagram or a new palette FileOpen Ctrlo Select the Open menu item to load an ASCII or binary file containing a saved block diagram or palette A dialog box allows user choosing the file FileSave Ctrls Select the save menu item to save the block diagram in a binary file already selected by a previous select the Save As menu item If you select this menu item and you have never clicked on the Save As menu item the diagram is saved in the current directory as windownamecos where windowname is the name of the window appearing on top of the window usually Untitled or Super Block The cos binary files are machine independent FileSave As CtrlShifts Select the Save As menu item to save the block diagram or palette in a file A dialog box allows choosing the file which must have a cos or cosf extension The diagram takes the name of the file Menuentries 2984 without the extension If extension is cosf an ASCII formatted save is performed instead of binary save Formatted save is slower than regular save FileExport Ctrle This menu is used to export a figure of the current xcos diagram The export can be done directly in postscript format or done first in a graphic window to export in a second step in all the format that scilab can provide FileRecent Files Via this menu you have a quick access to the recent opened files FilePrint Ctrlp Print the current diagram onto a printer FileClose Ctrlw If several diagram are opened the Close action closes the current diagram If only one diagram is opened the Close action will close xcos and closes the viewport and palettes windows if these windows are opened FileQuit Ctrlq If several diagram are opened the Quit action will close xcos and closes the viewport and palettes windows if these windows are opened It will close all the opened diagram Edit menu Menuentries 2985 EditUndo Ctrlz Select the Undo menu item to undo the last edit operation EditRedo Ctrly Select the Redo menu item to redo the last undo edit operation EditCut Ctrlx Cut is used to remove the selected object from the diagram and keep a copy in the clipboard if the object is a block EditCopy Ctrlc Copy is used to place a copy of the selected object in the clipboard if the object is a block EditPaste Ctrlv Paste places the object in the Clipboard in the diagram EditDelete Delete To delete blocks or a links select first the Delete menu item then click successively on the selected objects with left button When you delete a block all links connected to it are deleted as well EditSelect all Ctrla Select all the blocks in the current diagram EditInvert selection Invert the current selection EditBlock Parameters Ctrlb Open the block configuration window for the current selected block EditRegion to superblock Convert a selection of blocks into a superblock Menuentries 2986 View menu ViewZoom in Ctrlplus When you select this menu item the diagram is zoomed in by a factor of 10 ViewZoom out Ctrlminus When you select this menu item the diagram is zoomed out by a factor of 10 ViewFit diagram to view When you select this menu item the diagram is fit to the size of the current window ViewNormal 100 Resize the work area so as the diagram fits onto this work area ViewPalette browser Open the palette browser ViewDiagram browser Displays a window which lists all the blocks of a diagram and print some informations related to the scsm structure of the blocks ViewViewport Menuentries 2987 Display the viewport The viewport is an image of the current diagram With the viewport you can move the working area onto a piece of the diagram You can zoom and unzoom part of a diagram Above you have an example of the viewport which is used to zoom on a part of a diagram and on the right the xcos window displays the zoomed part of the diagram ViewDetails Displays a window which lists all the selected blocks of a diagram and print some informations related to the scsm structure of these blocks Menuentries 2988 Simulation menu SimulationSetup In the main Xcos window clicking on the Setup menu item invokes a dialog box that allows you to change integration parameters Final integration time integration ends at this time it always starts from 0 Real time scaling forces real time simulation by setting xcos unit of time to 1 second Absolute and relative error tolerances solver properties Time tolerance the smallest time interval for which the ode solver is used to update continuous states Max integration time interval the maximum time interval for each call to solver it must be reduced if the error message too many calls is encountered Solver choose the numerical solver to be used Max step size max time step taken by solver Execution trace and Debug Set Xcos in debug mode Allows diagram debugging SimulationSet Context When you select this menu item you obtain a dialog to enter Scilab instructions for defining symbo lic Xcos parameters used in block definitions or to do whatever you want These instructions will be Menuentries 2989 evaluated each time the diagram is loaded If you change the value of a symbolic Xcos parameters in the context all the blocks are updated Eval is performed SimulateCompile Select the Compile menu item to compile the block diagram This menu item need never be used since compilation is performed automatically if necessary before the beginning of every simulation Run menu item Normally a new compilation is not needed if only system parameters and internal states are modified In some cases however these modifications are not correctly updated and a manual compilation may be needed before a Restart or a Continue Please report if you encounter such a case Simulatestart Select the Run menu item to start the simulation If the system has already been simulated a dialog box appears where you can choose to Continue Restart or End the simulation SimulationStop You may interrupt the simulation by clicking on the stop button change any of the block para meters and continue the simulation with the new values Format menu FormatRotate Ctrlr Rotate allows to turn a block on the Left Each time the block is turned left his angle is decresead of 45 degrees If no blocks or many blocks are selected this is the block under the mouse pointer which turns Menuentries 2990 FormatFlip Ctrlf To reverse the positions of the regular inputs and outputs of a block placed on its sides select the Flip menu item first and then click on the selected block This does not affect the order nor the position of the input and output event ports which are numbered from left to right FormatShowHide shadow This menu allows to select 3D shape for selected blocks and associated parameters FormatAlign Blocks When you select several blocks it is possible to align them vertically Top Bottom and Middle and horizontally Left Right Center Format Border Color This menu allows to change the border color FormatLine Color This menu allows to change the line color FormatLink Style Menuentries 2991 This menu allows to the the style of the link Horizontal Straight Vertical FormatDiagram background This menu allows to change the background color FormatGrid This menu allows to activate desactivate the grid Using a grid it is easier to place a block on the working area Tools menu ToolsCode generation This menu allows to generate the simulation code associated with a discrete time Super Block The code generation is obtained simply by selecting this menu and then the desired Super Block If the Super Block satisfies the required conditions a dialog box pops up to ask for a block name a directory where to put the generated files and for optional libraries requested by the linker Given this information the code is generated compiled and linked with Scilab The Super Block is auto Menuentries 2992 matically replaced by a new block which implements the generated code It is then possible to run the modified diagram The code for standalone use is also generated Help menu HelpXcos Help This menu opens the help browser HelpBlock Help To get help on a Xcos object a block select first an object a block and then click on this menuHelp menu item and then on the selected object or menu item HelpXcos Demos The Demos menu allows to open some examples of Xcos diagram HelpAbout Xcos About xcos item display the current version of Xcos and gives some useful informations Parte LVI scilab editor 2994 Name editerror opens in scilab editor the source of the last recorded error answ editerrorclearerror Parameters clearerror boolean if true the error condition is cleared if false it is kept as in lasterror answ a string stating which source file is open or why no file was open Description This function opens in scilab editor the source of the function which caused the last recorded error This function works only for functions which are defined in libraries ie not for internal functions nor with functions defined online nor loaded with individual exec or getd This is since Scilab presently retains only the path to libraries and not to individual function sources Correspondance between the function name foo and function filename foosci is tacitly assumed Examples acosh abc editerror See Also lasterror errclear Authors Enrico Segre Allan CORNET 2995 Name Editor Embedded Scilab text editor editor editorfile editorfile1 file2 editorfile linenumber editorfile1 file2 linenumber1 linenumber2 Parameters file a string the file we want to open file1 file2 a matrix of string files we want to open linenumber an integer number of the line we want to highlight at the opening of the file linenumber1 linenumber2 a matrix of integer each opened file will have its corresponding line highlighted Description Editor is an embedded Scilab text editor It can be started with a fresh text buffer pressing the Editor button on top of the main Scilab window or from Scilab command line with the instruction editor or it can open specific files if invoked with any of the calling sequences above whithout any parameters it opens editor with a blank file The same invocation adds further files to an already opened Editor Keyboard shortcuts are defined for most possible editing actions and reported by the menu entries editor can be started in the following ways By the menu Applications Choose Applications Editor From the command line editor editorfile editorfile1 file2 editorfile linenumber editorfile1 file2 linenumber1 linenumber2 Menus and Shortcuts Menu File Editor 2996 Commande Shortcut Description New CTRLN Open a new file Open CTRLO Open an existing file Recent Files Display files recently opened Save CTRLS Save a file Save as CTRLMAJS Save a file as Page Setup Setup page for printing Print Preview CTRLMAJP Open a print preview window Print CTRLP Print a file Close CTRLW Close a file Quit CTRLQ Close Editor Menu Edit Commande Shortcut Description Undo CTRLZ Undo action Redo CTRLY Redo action Cut CTRLX Cut the selection Copy CTRLC Copy the selection Paste CTRLV Paste the selection Select All CTRLA Select the entire document Delete Delete the selection Comment Selection CTRLD Comment selected lines Uncomment Selection CTRLMAJD Uncomment selected lines Tabify Selection TAB Tabify selected lines Untabify Selection MAJTAB Untabify selected lines Indent CTRLI Indent selected lines Menu Search Commande Shortcut Description FindReplace CTRLF Find andor Replace an element Goto line CTRLG Goto line Menu View Commande Shortcut Description ShowHide Toolbar Option to show or hide the tool bar Highlight current line CTRLJ Highlight the current line Line Numbers CTRLB Display documents line num bers Set Colors Color settings for documents Set Fonts Font settings for documents Reset default font Reset default font settings for documents Editor 2997 Menu Document Commande Shortcut Description Syntaxe Type Syntaxe type settings default type is Scilab Encoding Encoding settings default type is UTF8 Encoding Colorize Colorize the document Auto Indent Activate the automatic indenta tion Menu Execute Commande Shortcut Description Load Into Scilab CTRLL Load the entire document into the Scilab console Evaluate Selection Load the selection into the Scilab console Execute Into Scilab CTRLE If the file exist execute the con tent of the file Remarks Document The default text colourisation is the Scilabs syntaxe colourisation The autoindent mode indent a line according to Scilabs syntaxe after a return action Bugs You can reported bugs in the Bugzilla httpbugzillascilaborg There are still a few bugs that we are trying to fix details can be found in the given link by filtering entries with the Editor element Examples editor without parameters editor editor with a file name editorSCImodulestimemacrosdatenumsci editor with a matrix of files name editorSCImodulestimemacrosdatenumsciSCImodulestimemacrosdatevecsci editor with a file name and the line number to highlight editorSCImodulestimemacrosdatenumsci 5 editor with a matrix of files name and the corresponding matrix of lines to highlight the files name matrix and the lines to highlight matrix should have the same size editorSCImodulestimemacrosdatenumsciSCImodulestimemacrosdatevecsci 510 Author Sylvestre KOUMAR Parte LVII API Scilab 3000 Índice 11 Scilab Gateway API 3001 1 How to 3001 CheckColumn 3023 CheckDimProp 3024 CheckDims 3025 CheckLength 3026 CheckLhs 3027 CheckRhs 3028 CheckRow 3029 CheckSameDims 3030 CheckScalar 3032 CheckSquare 3033 CheckVector 3034 CreateListVarFrom 3035 CreateListVarFromPtr 3038 CreateVar 3041 FindOpt 3043 FirstOpt 3045 GetListRhsVar 3047 GetRhsVar 3049 GetType 3051 IsOpt 3052 Lhs 3054 LhsVar 3055 NumOpt 3057 OverLoad 3059 Rhs 3061 Scierror 3062 Scilab C Types 3063 getoptionals 3065 istk 3067 scitypes 3068 sciprint 3071 stk 3072 12 listmanagement 3073 Boolean reading Scilab gateway 3074 Boolean writing Scilab gateway 3086 Boolean sparse reading Scilab gateway 3090 Boolean sparse writing Scilab gateway 3102 Create List Scilab gateway 3106 Double reading Scilab gateway 3110 Double writing Scilab gateway 3122 Get child item Scilab gateway 3126 Item Number Scilab gateway 3129 Integer reading Scilab gateway 3132 Integer writing Scilab gateway 3144 Pointer reading Scilab gateway 3149 Pointer writing Scilab gateway 3161 Polynomial reading Scilab gateway 3165 Polynomial writing Scilab gateway 3177 Sparse reading Scilab gateway 3181 Sparse writing Scilab gateway 3193 String reading Scilab gateway 3197 String writing Scilab gateway 3209 3001 Capítulo 11 Scilab Gateway API 1 How to Scilab Gateway API 3002 Name Calling a scilab function macros from a C gateway Calling a scilab function macros from a C interface Calling a scilab function macros from a C interface WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead When you write a interface with scilab you can need to call another function directly from your function You can pass a pointer on scilab function to your function The source files of this example are stored in the directory examplescallscifunction How to use this example exec callscifunctionsce launch scilab v callscifunc3012scilabfoo you pass a pointer on a scilab function scilabfoo macro to your function callscifunc C2Fscifunction calls another scilab function here scilabfoo You need to indicate position of the first element Rhs in the Scilab memory pointer on scilab function number of Lhs output of scilab function called number of Rhs input of scilab function called The script callscifunctionsce used to build and load the C interface into Scilab is the following filesscicallscifuncc Defines the list of file ilibbuildcallscifunccallscifuncscicallscifuncfiles Build the files and creates the loader exec loadersce function r scilabfooxy r x y endfunction v callscifunc3012scilabfoo dispresult stringv v callscifunc300120scilabfoo dispresult stringv ulink unload the dynamic library The file scicallscifuncc is the following include stackch include Scierrorh include localizationh Scilab Gateway API 3003 int scicallscifuncchar fname int m1 0 n1 0 l1 0 int m2 0 n2 0 l2 0 int m3 0 n3 0 l3 0 int rm1 0 rn1 0 rl1 0 int mout 1 nout 1 lout 0 double v1 0 v2 0 r 0 int positionFirstElementOnStackForScilabFunction 0 int numberOfRhsOnScilabFunction 0 int numberOfLhsOnScilabFunction 0 int pointerOnScilabFunction 0 CheckRhs33 CheckLhs11 if GetType1 scimatrix Scierror999s Wrong type for input argument d A real expected fname1 return 0 GetRhsVar1 MATRIXOFDOUBLEDATATYPE m1 n1 l1 if m1 n1 n1 1 v1 stkl1 else Scierror999s Wrong size for input argument d A scalar expected fname1 return 0 if GetType2 scimatrix Scierror999s Wrong type for input argument d A real expected fname2 return 0 GetRhsVar2 MATRIXOFDOUBLEDATATYPE m2 n2 l2 if m2 n2 n2 1 v2 stkl2 else Scierror999s Wrong size for input argument d A scalar expected fname2 return 0 if GetType3 scicfunction Scierror999s Wrong type for input argument d A scilab function expected fname3 return 0 get pointer on external function here scilabfoo GetRhsVar3 EXTERNALDATATYPE m3 n3 l3 Scilab Gateway API 3004 r scilabfoox y rhs eq 2 lhs eq 1 Position first element in the Scilab memory to use by Scilab Function v callscifunc300120scilabfoo On stack 300 is on Top position 1 120 second position scilabfoo third position we want to pass 300 120 to scilab Function First position is here 1 positionFirstElementOnStackForScilabFunction 1 numberOfRhsOnScilabFunction 2 numberOfLhsOnScilabFunction 1 pointerOnScilabFunction l3 r scilabfoox y Scifunction call a scilab function ScifunctionpositionFirstElementOnStackForScilabFunction pointerOnScilabFunction numberOfLhsOnScilabFunction numberOfRhsOnScilabFunction result r is now on position positionFirstElementOnStackForScilabFunction on stack GetRhsVar1 MATRIXOFDOUBLEDATATYPE rm1 rn1 rl1 r stkrl1 CreateVarRhs1 MATRIXOFDOUBLEDATATYPE mout nout lout stklout r LhsVar1 Rhs 1 return 0 The main function in this C file is Scifunction It allows to call a Scilab function inside a C interface See Also CheckLhs CheckRhs stk LhsVar GetType Scierror Rhs Lhs scitypes Scilab Gateway API 3005 Nome How to access a matrix How to access a matrix using the C gateway functions Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The goal is to get a matrix of doubles send to a function written in C For this we will wrote a C gateway function in which we will retrieve the matrix we will perform some simple steps in this C function First we will get an access to the matrix in the Scilab memory We will perform some simple operations on the matrix in this example we will multiply by 2 each elements of the matrix We will return the result to Scilab This example is available in the directory SCImodulescoreexamplesex1 The C function include stackch int scimultiplybytwochar fname int minvar ninvar linvar int moutvar noutvar loutvar int irow jcol double pMatrix NULL First access to the input variable a matrix of doubles GetRhsVar1 MATRIXOFDOUBLEDATATYPE minvar ninvar linvar Create the returned variable a matrix of doubles moutvar minvar noutvar ninvar CreateVar2 MATRIXOFDOUBLEDATATYPE moutvar noutvar loutvar pMatrix stklinvar Perform some simple operations on the matrix forirow0 irowminvar irow forjcol0 jcolninvar jcol pMatrixirow jcol moutvar 2 pMatrixirow jcol minvar Return the output variable LhsVar1 2 return 0 Scilab Gateway API 3006 This file must be saved as multiplybytwoc The main thing to highlight is that to build a C gateway function we need to include the header stack ch In this header we find the prototypes and macros of the main C gateway functions To be able to build and link such a C function to scilab we need to write a Scilab script which will compile this C function and then create a loader script which will link the C function to a Scilab function The builder script This is the buildersce must be run from this directory lines0 ilibname libmultiplybytwo files multiplybytwoc libs table multiplybytwo scimultiplybytwo ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags This file must be saved as buildersce This script will tell Scilab which files must be compiled here its multiplybytwoc what will be the name of the shared library here its libmultiplybytwo and which C symbol will be linked to a Scilab function here we will link the scimultiplybytwo C symbol to the Scilab function multiplybytwo To build this function we just need to to exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce The script loadersce is normally automatically built by buildersce Testing our new function We now write a simple example to test our new function A 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Scilab Gateway API 3007 B multiplybytwoA dispB The script must be saved as testsce Lets run our scripts and see what is the result exec buildersce Generate a gateway file Generate a loader file Generate a Makefile ilibgenMake Copy compilation files Makefile libtool to TMPDIR ilibgenMake Copy multiplybytwoc to TMPDIR ilibgenMake Copy libmultiplybytwoc to TMPDIR ilibgenMake Modification of the Makefile in TMPDIR Running the makefile exec loadersce Shared archive loaded Link done exec testsce 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 This simple function has produced a new matrix which corresponds to the matrix transmitted as an input argument and for which each element of the matrix has been multiplied by 2 Rebuilding a gateway function Lets imagine that our gateway function has already been build and we would like to make some changes in our function multiply by 3 instead of 2 How do we perform such a changes without restarting Scilab First we need to list all the dynamic libraries which has been loaded into Scilab The can be done using the linkshow function linkshow Number of entry points 1 Shared libraries 0 1 libraries Entry point libmultiplybytwo in shared library 0 ans 0 Here in our current Scilab session only 1 dynamic library has been loaded This library has a reference number For our library its 0 Now that we know the reference number of our library we are able to unload this library using the function ulink0 0 is the reference number of our library Scilab Gateway API 3008 perform some modification in the source code of our C gateway function replace multiply by 2 by 3 rebuild the C gateway function exec buildersce load the modified C gateway function into scilab exec loadersce This is what is done is the following example ulink0 exec buildersce Generate a gateway file Generate a loader file Generate a Makefile ilibgenMake Copy compilation files Makefile libtool to TMPDIR ilibgenMake Copy multiplybytwoc to TMPDIR ilibgenMake Copy libmultiplybytwoc to TMPDIR ilibgenMake Modification of the Makefile in TMPDIR Running the makefile exec loadersce Shared archive loaded Link done exec testsce 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 See Also GetRhsVar Scilab C Types CreateVar LhsVar stk ilibbuild link ulink Scilab Gateway API 3009 Nome How to check parameters how to check parameter send to an interface using the C gateway functions Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The goal is to get a set of parameters via a set of C gateway functions and then to perform some checks in the C function This example is available in the directory coreexamplescheckproperties The C function include stackch include sciprinth int scicheckproperties1char fname int m1 n1 l1 int m2 n2 l2 int m3 n3 l3 int m4 n4 l4 int m5 n5 l5 CheckRhs55 CheckLhs01 Getting first argument GetRhsVar1 d m1 n1 l1 CheckVector1m1n1 Check that first argument is a vector CheckLength1m1n14 Check vector length Getting second argument GetRhsVar2 d ampm2 ampn2 ampl2 CheckRow2m2n2 Checks that second argument is a row vector CheckColumn can also be used CheckDimProp12 m1 n1 n2 Check compatibility beetween arg 1 and arg 2 We want m1n1 n2 Getting third argument GetRhsVar3 d m3 n3 l3 CheckSameDims13m1n1m3n3 Checks that arg 1 and arg3 have same dimensions Scilab Gateway API 3010 Getting fourth argument GetRhsVar4dm4n4l4 CheckScalar4m4n4 arg 4 must be scalar Getting fourth argument GetRhsVar5dm5n5l5 CheckSquare5m5n5 square matrix CheckDims5m5m555 check dimensions LhsVar10 return 0 We must be careful on the scilab name function 8 chars max int scicheckproperties2char fname int m1n1l1 CheckRhs11 CheckLhs01 switchVarType1 case 1 GetRhsVar1 d m1 n1 l1 sciprint1 is a scalar matrix break case 10 GetRhsVar1 c m1 n1 l1 sciprint1 is a string break case 5 sciprint1 is a sparse trying to overload OverLoad1 LhsVar1 0 return 0 This file must be saved as checkpropertiesc The main thing to highlight is that to build a C gateway function we need to include the header stack ch In this header we find the prototypes and macros of the main C gateway functions We also need to include sciprinth because we use the sciprint function Scilab Gateway API 3011 To be able to build and link such a C function to Scilab we need to write a Scilab script which will compile this C function and then create a loader script which will link the C function to a Scilab function The builder script This is the buildersce must be run from this directory lines0 ilibname libcheckproperties files checkpropertiesc libs table checkproperties1 scicheckproperties1 chprop2 scicheckproperties2 We must be careful when we choose a scilab function name in case of overloading We Scilab name function must be 8 char max ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags This file must be saved as buildersce This script will tell Scilab which files must be compiled here its checkpropertiesc what will be the name of the shared library here its libcheckproperties and which C symbol will be linked to a Scilab function here we will link the scicheckproperties1 C symbol to the Scilab function checkproperties1 For the other C function we must be careful on the name of the Scilab function we will choose Because this function will be overloading the current overloading process of Scilab works only on Scilab primitives Scilab function wrote in C which have a name which is maximum 8 char wide For this function we will link the scicheckproperties2 C symbol to the Scilab function chprop2 To build this function we just need to to exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce The script loadersce is normally automatically built by buildersce Testing our new function We now write a simple example to test our new functions Scilab Gateway API 3012 checks arguments compatibility checkproperties112343456678990rand55 first argument can have different types chprop2122 chprop2foo overload case deffspchprop2spdispsparse overloaded chprop2sparse123 tests which give an error message with checkproperties1 try checkproperties112343456678990rand55 catch displasterror end try checkproperties112343456678990rand55 catch displasterror end try checkproperties112343456678990rand55 catch displasterror end try checkproperties1123434566789rand55 catch displasterror end try checkproperties112343456678990rand44 catch displasterror end The script must be saved as checkpropertiessce Lets run our scripts and see what is the result exec buildersce Génère un fichier gateway Génère un fichier loader Génère un Makefile Makelib Exécute le makefile Compilation de checkpropertiesc Scilab Gateway API 3013 Construction de la bibliothèque partagée soyez patient exec loadersce Bibliothèque partagée chargée Link done exec checkpropertiessce 1 is a scalar matrix 1 is a string 1 is a sparse trying to overload sparse overloaded checkproperties1 Les paramètres first et third a des dimensions incompatibles 1x4 4x1 checkproperties1 second paramètre devrait être un vecteur ligne checkproperties1 Les paramètres first et third a des dimensions incompatibles 4x1 1x4 checkproperties1 fourth paramètre devrait être un scalaire checkproperties1 Argument numéro 5 na pas les bonnes dimensions 44 55 attendues See Also GetRhsVar CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckDimProp CheckLength CheckSameDims CheckSquare OverLoad ilibbuild Scilab Gateway API 3014 Nome How to create and access a list How to create and access a list using the C gateway functions Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The goal is to get a mtlist to get some elements stored in that this and to send a new mtlist using a function written in C For this we will wrote two C gateway function in which we will retrieve the mtlist and we will create a new mtlist The C function access to a mtlist This example is available in SCImodulescoreexampleprintlist Lets initialize a mlist in Scilab A mlistmytypevar1var2a string1 2 3 4 This mlist is of type mytype typeofAmytype and it has 2 elements Avar1 which is equal to a string Avar2 which is equal to 1 2 3 4 We now create a C function called sciprintlist which will print the elements stored in the list include stackch include sciprinth int sciprintlistchar fname int mlistin nlistin llistin int mtype ntype int mvar1 nvar1 lvar1 int mvar2 nvar2 lvar2 char LabelList NULL CheckRhs11 We accept only 1 parameter GetRhsVar1mmlistinnlistinllistin Get a mlist Get the type and the name of the variables the first element of the mlist GetListRhsVar11SmtypentypeLabelList if strcmpLabelList0mytype0 sciprinterror you must ship a mlist or type mytype return 0 Get the first variable a string GetListRhsVar12cmvar1nvar1lvar1 Scilab Gateway API 3015 sciprintvar1 s cstklvar1 Get the second variable a double matrix GetListRhsVar13dmvar2nvar2lvar2 sciprintvar2 f f f f stklvar20 stklvar21 stklvar22 stklvar23 return 0 To be able to build and link such a C function to scilab we need to write a Scilab script which will compile this C function and then create a loader script which will link the C function to a Scilab function The C file is available in the example directory It is named printlistc The builder script This is the buildersce must be run from this directory lines0 ilibname libprintlist files printlistc libs table printlist sciprintlist ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags programlisting paraThis file must be saved as builderscepara paraThis script will tell Scilab which files must be compiled here its printlistc what will be the name of the shared library here its libprintlist and which C symbol will be linked to a Scilab function here we will link the sciprintlist C symbol to the Scilab function printlistpara paraTo build this function we just need to topara programlisting role CDATA exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce Scilab Gateway API 3016 The script loadersce is normally automatically built by buildersce Lets test our new function exec buildersce exec loadersce A mlistmytypevar1var2a string1 2 3 4 printlistA The C function creation of a mtlist This example is available in SCImodulescoreexamplecreatelist We now write a simple example to test our new function to create a mtlist A createlist dispA First lets write the C function include stackch include stringh int scicreatelistchar fname int mlistout nlistout int mvar1 nvar1 lvar1 llistvar1 int mvar2 nvar2 lvar2 llistvar2 int mmlist nmlist lmlist The labels of our mlist static const char ListLabels mylistvar1var2 First we create the variables using a classical way The size of the Scilab variables mvar1 1 nvar1 strlena string1 a null terminated string mvar2 2 nvar2 2 A 2x2 double matrix mmlist 3 nmlist 1 A mlist with 3 elements Creation of the Scilab variables Avar1 CreateVar1 c mvar1 nvar1 lvar1 Avar2 CreateVar2 d mvar2 nvar2 lvar2 A CreateVar3 m mmlist nmlist lmlist We store values in the create variables The matrix will be stored in Avar2 stklvar20 1 stklvar21 2 stklvar22 3 stklvar23 4 Scilab Gateway API 3017 The string will be stored in Avar1 strncpycstklvar1a string0nvar1 mlistout 3 nlistout 1 now affect the variable to the mlist The labels it corresponds to A mlistmylistvar1var2 CreateListVarFromPtr3 1 S mlistout nlistout ListLabels The value stored in Avar1 it corresponds to A a string CreateListVarFrom3 2 c mvar1 nvar1 llistvar1 lvar1 The value stored in Avar2 it corresponds to A 1 23 4 CreateListVarFrom3 3 d mvar2 nvar2 llistvar2 lvar2 We return only the mlist which has been created at position 3 LhsVar1 3 return 0 Some important comments related to the CreateVarPosmm n l function When called on a mlist only the m parameter is taken in account the n parameter is not used So be careful mlist 3 nlist 1 CreateVar1 m mlist nlist llist creates a mlist with 3 elements but mlist 1 nlist 3 CreateVar1 m mlist nlist llist creates a mlist with only 1 element Another important thing when we create a list element using CreateListVarFrom it is not recommen ded to access the created variable using for example stkllistvar2 because CreateListVarFrom performs type transformation on the list variables The builder script This is the buildersce must be run from this directory lines0 ilibname libcreatelist files createlistc libs table createlist scicreatelist ldflags Scilab Gateway API 3018 cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags This file must be saved as buildersce This script will tell Scilab which files must be compiled here its createlistc what will be the name of the shared library here its libcreatelist and which C symbol will be linked to a Scilab function here we will link the scicreatelist C symbol to the Scilab function createlist To build this function we just need to to exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce The script loadersce is normally automatically built by buildersce Lets test our new function exec buildersce exec loadersce A createlist disptypeofA dispgetfield1A dispAvar1 dispAvar2 See Also GetRhsVar GetListRhsVar CreateVar CreateListVarFrom CreateListVarFromPtr LhsVar stk ilibbuild Scilab Gateway API 3019 Nome How to deal with optional parameters how to deal with optional parameters send to an interface using the C gateway functions Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The goal is to get a set of optional parameters via a C gateway and then to perform some checks in the C function number of optional parameters does an optional parameters exists etc This example is available in the directory coreexamplesoptionalparameters The C function include stackch int ex2cdouble a int ma int na double b int mb int nb int i fori0imanai ai 2ai fori0imbnbi bi 3bi return0 int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 default values if optional arguments are not given v199 and v23 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts Scilab Gateway API 3020 sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername iopos Rhs if opts0position1 iopos opts0position iopos opts0m 1 opts0n 1 opts0type d CreateVaropts0position opts0type opts0m opts0n opts0l stkopts0l 990 if opts1position1 iopos opts1position iopos opts1m 1 opts1n 1 opts1type d CreateVaropts1position opts1type opts1m opts1n opts1l stkopts1l 3 ex2cstkopts0lopts0mopts0n stkopts1lopts1mopts1n return the first argument unchanged then v1 and v2 LhsVar1 1 LhsVar2 opts0position LhsVar3 opts1position return 0 This file must be saved as optionalparametersc The main thing to highlight is that to build a C interface function we need to include the header stack ch In this header we find the prototypes and macros of the main C interface functions We also need to include sciprinth because we use the sciprint function To be able to build and link such a C function to scilab we need to write a Scilab script which will compile this C function and then create a loader script which will link the C function to a Scilab function The builder script This is the buildersce must be run from this directory Scilab Gateway API 3021 lines0 ilibname liboptionalparameters files optionalparametersc libs table optionalparameters scioptionalparameters ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags This file must be saved as buildersce This script will tell Scilab which files must be compiled here its optionalparametersc what will be the name of the shared library here its liboptionalparameters and which C symbol will be linked to a Scilab function here we will link the scioptionalparameters C symbol to the Scilab function optionalparameters To build this function we just need to to exec buildersce Now we are able to test our new C function First lets load this new function in scilab exec loadersce The script loadersce is normally automatically built by buildersce Testing our new function We now write a simple example to test our new functions Example with optional argument specified with the argvalue syntax abc ex12cx1 v1 arg1 v2 arg2 arg1 default value 99 arg2 default value 3 only v1 and v2 are recognized as optional argument names the return value are a x1 b 2v2 c 3v2 abc optionalparameterstest dispa a b stringb c stringc abc optionalparameterstestv11020 dispa a b stringb c stringc abc optionalparameterstestv11020v28 dispa a b stringb c stringc Scilab Gateway API 3022 abc optionalparameterstestv28v110 dispa a b stringb c stringc The script must be saved as optionalparameterssce Lets run our scripts and see what is the result exec buildersce Génère un fichier gateway Génère un fichier loader Génère un Makefile Makelib Exécute le makefile Compilation de optionalparametersc Construction de la bibliothèque partagée soyez patient exec loadersce Bibliothèque partagée chargée Link done exec optionalparameterssce number of optional parameters 0 first optional parameters 2 FindOptv1 0 FindOptv2 0 a test b 198 c 9 number of optional parameters 1 first optional parameters 2 FindOptv1 2 FindOptv2 0 parameter 2 is optional v1 a test b 20 c 9 a test b 40 c 9 number of optional parameters 2 first optional parameters 2 FindOptv1 2 FindOptv2 3 parameter 2 is optional v1 parameter 3 is optional v2 a test b 20 c 24 a test b 40 c 24 number of optional parameters 2 first optional parameters 2 FindOptv1 3 FindOptv2 2 parameter 2 is optional v2 parameter 3 is optional v1 a test b 20 c 24 See Also GetRhsVar CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckDimProp CheckLength CheckSameDims CheckSquare OverLoad ilibbuild Scilab Gateway API 3023 Name CheckColumn C interface function which checks if a parameter send to the C function is a column vector or not CheckColumnStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the argument for which we want to perform the check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a column vector or not You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function takes one input parameters and prints the integer correspon ding to the type of the variable sent as parameter in the Scilab console If the test fails we return from the C interface and an adequate error message is printed in the Scilab console include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckColumn1m1n1 Check that first argument is a column vector return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3024 Name CheckDimProp C interface function which checks the comatibility between 2 arguments send to the C function CheckColumnStackPosvar1StackPosvar2expression Parameters StackPosvar1 the position in the Scilab memory of the first parameter for which we want to perform the check input parameter StackPosvar2 the position in the Scilab memory of the second variable for which we want to perform the check input parameter expression a boolean expression which represent the size check we want to perform Description C interface function which checks the compatibility between 2 arguments send to the C function You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 int m2 n2 l2 CheckRhs22 GetRhsVar1 d m1 n1 l1 GetRhsVar2 d m2 n2 l2 Check compatibility beetween arg 1 and arg 2 We want m1n1 n2 CheckDimProp12 m1 n1 n2 return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckLength CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3025 Name CheckDims C interface function which checks if a parameter send to the C function has the required dimensions CheckDimsStackPosmvarnvarmrequirednrequired Parameters StackPos the position in the Scilab memory of the parameter for which we want to know the type input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory input parameter nvar the number of columns of the parameter at position StackPos in the Scilab memory input para meter mrequired the required number of lines input parameter nrequired the required number of columns input parameter Description C interface function which checks if a parameter send to the C function has the required dimensions You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckDims1m1n114 Check that argument is a 1x4 matrix return 0 See Also CheckColumn CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3026 Name CheckLength C interface function which checks the length of a vector send as a parameter to the C function CheckLengthStackPosmvarmrequired Parameters StackPos the position in the Scilab memory of the parameter for which we want to check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory input parameter mrequired the required number of lines input parameter Description C interface function which checks the length of a vector send as a parameter to the C function You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckLength1m1n14 Check that vector has 4 elements return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDim Prop CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3027 Name CheckLhs C macro which checks the number of output arguments present in the calling Scilab function CheckLhsnbminparamsnbmaxparams Parameters nbminparams the minimum number of output arguments which must be present in the calling Scilab function nbmaxparams the maximum number of output arguments which must be present in the calling Scilab function Description C macro which checks the number of output arguments present in the calling Scilab function You must include stackch to benefit from this function If the number of arguments is not between nbminparams and nbmaxparams we quit the C inter face return 0 and an error is returned in the Scilab console Since CheckLhs is doing a return 0 within the gateway function it is important to call this macro before any memory allocation in order to avoid any memory leak WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C gateway function checks for a number of output arguments which must be between 2 and 3 include stackch int scimychecklhschar fname CheckLhs23 return 0 Now some functions testing this interface AB mychecklhs OK 2 output arguments ABC mychecklhs OK 3 output arguments A mychecklhs ERROR 1 output argument ABCD mychecklhs ERROR 4 output arguments See Also CheckRhs Scilab Gateway API 3028 Name CheckRhs C macro which checks the number of input arguments present in the calling Scilab function CheckRhsnbminparamsnbmaxparams Parameters nbminparams The minimum number of input arguments which must be present in the calling Scilab function nbmaxparams the maximum number of input arguments which must be present in the calling Scilab function Description C macro which checks the number of input arguments present in the calling Scilab function You must include stackch to benefit from this function If the number of input arguments is not between nbminparams and nbmaxparams we quit the C interface return 0 and an error is returned in the Scilab console Since CheckRhs is doing a return 0 within the gateway function it is important to call this macro before any memory allocation in order to avoid any memory leak WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C gateway function checks for a number of input arguments which must be bet ween 2 and 3 include stackch int scimycheckrhschar fname CheckRhs23 return 0 Now some functions testing this interface mycheckrhsAB OK 2 output arguments mycheckrhsABC OK 3 output arguments mycheckrhsA ERROR 1 output argument mycheckrhsABCD ERROR 4 output arguments See Also CheckLhs Scilab Gateway API 3029 Name CheckRow C interface function which checks if a parameter send to the C function is a row vector or not CheckRowStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the parameter for which we want to know the type input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a row vector or not You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckRow1m1n1 Check that first argument is a row vector return 0 See Also CheckColumn CheckDims CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3030 Name CheckSameDims C interface function which checks if two parameters send to the C function have the same size CheckSameDimsStackPosvar1StackPosvar2mvar1nvar1mvar2nvar2 Parameters StackPosvar1 the position in the Scilab memory of the first parameter for which we want to perform the check input parameter StackPosvar2 the position in the Scilab memory of the second parameter for which we want to perform the check input parameter mvar1 the number of lines of the parameter at position StackPosvar1 in the Scilab memory nvar1 the number of columns of the parameter at position StackPosvar1 in the Scilab memory mvar2 the number of lines of the parameter at position StackPosvar2 in the Scilab memory nvar2 the number of columns of the parameter at position StackPosvar2 in the Scilab memory Description C interface function which checks if two parameters send to the C function have the same size You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function takes one input parameters and prints the integer correspon ding to the type of the variable sent as parameter in the Scilab console include stackch int scicheckpropertieschar fname int m1 n1 l1 int m2 n2 l2 CheckRhs22 GetRhsVar1 d m1 n1 l1 GetRhsVar2 d m2 n2 l2 CheckSameDims12m1n1m2n2 Check that both vectors have the same size Scilab Gateway API 3031 return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDim Prop CheckLength CheckSquare How to check parameters Scilab Gateway API 3032 Name CheckScalar C interface function which checks if a parameter send to the C function is a scalar or not CheckScalarStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the parameter for which we want to perform the check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a scalar or not You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function takes one input parameters and prints the integer correspon ding to the type of the variable sent as parameter in the Scilab console If the test fails we return from the C interface and an adequate error message is printed in the Scilab console include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckScalar1m1n1 Check that first argument is a scalar return 0 See Also CheckColumn CheckDims CheckRow CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3033 Name CheckSquare C interface function which checks if a parameter send to the C function is a square matrix or not CheckSquareStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the parameter for which we want to perform the check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a square matrix or not You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckSquare1m1n1 Check that first argument is a square matrix return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDim Prop CheckLength CheckSameDims How to check parameters Scilab Gateway API 3034 Name CheckVector C interface function which checks if a parameter send to the C function is a vector column or row or not CheckVectorStackPosmvarnvar Parameters StackPos the position in the Scilab memory of the parameter for which we want to perform the check input parameter mvar the number of lines of the parameter at position StackPos in the Scilab memory nvar the number of columns of the parameter at position StackPos in the Scilab memory Description C interface function which checks if a parameter send to the C function is a vector column or row or not You must include stackch to benefit from this function If the test fails we return from the C interface and an adequate error message is printed in the Scilab console WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples include stackch int scicheckpropertieschar fname int m1 n1 l1 CheckRhs11 GetRhsVar1 d m1 n1 l1 CheckVector1m1n1 Check that first argument is a vector column or row return 0 See Also CheckColumn CheckDims CheckRow CheckScalar CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3035 Nome CreateListVarFrom a C interface function which allows to create a new Scilab parameter in a mtlist CreateListVarFromStackPosType mrows ncols lstacklistpos lstackpos Parameters StackPos the rank of the parameter to be created input parameter Type the Scilab type of the parameter to be created input parameter Can be see Scilab C Type for more informations STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the matrix to be created input parameter ncols the number of columns of the matrix to be created input parameter lstacklistpos the position in the Scilab memory of the created variable in the listoutput parameter lstackpos the position in the Scilab memory of the created variable input parameter Description A C interface function which allows to create a new Scilab variable in a mtlist Scilab Gateway API 3036 WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples include stackch include stringh int scicreatelistchar fname int mlistout nlistout int mvar1 nvar1 lvar1 llistvar1 int mvar2 nvar2 lvar2 llistvar2 int mmlist nmlist lmlist The labels of our mlist static const char ListLabels mylistvar1var2 First we create the variables using a classical way The size of the Scilab variables mvar1 1 nvar1 strlena string1 a null terminated string mvar2 2 nvar2 2 A 2x2 double matrix mmlist 3 nmlist 1 A mlist with 3 elements Creation of the Scilab variables Avar1 CreateVar1 c mvar1 nvar1 lvar1 Avar2 CreateVar2 d mvar2 nvar2 lvar2 A CreateVar3 m mmlist nmlist lmlist We store values in the create variables The matrix will be stored in Avar2 stklvar20 1 stklvar21 2 stklvar22 3 stklvar23 4 The string will be stored in Avar1 strncpycstklvar1a string0nvar1 mlistout 3 nlistout 1 now affect the variable to the mlist The labels it corresponds to A mlistmylistvar1var2 CreateListVarFromPtr3 1 S mlistout nlistout ListLabels The value stored in Avar1 it corresponds to A a string CreateListVarFrom3 2 c mvar1 nvar1 llistvar1 lvar1 The value stored in Avar2 it corresponds to A 1 23 4 CreateListVarFrom3 3 d mvar2 nvar2 llistvar2 lvar2 We return only the mlist which has been created at position 3 LhsVar1 3 return 0 Scilab Gateway API 3037 This example is available in SCImodulescoreexamplecreatelist See Also Scilab C Type istk LhsVar CreateVar Scilab Gateway API 3038 Nome CreateListVarFromPtr a C interface function which allows to create a new Scilab parameter from a pointer in a mtlist CreateListVarFromStackPos Type mrows ncols lstacklistpos void Pointer Parameters StackPos the rank of the parameter to be created input parameter Type the Scilab type of the parameter to be created input parameter Can be see Scilab C Type for more informations STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the matrix to be created input parameter ncols the number of columns of the matrix to be created input parameter lstacklistpos the position in the Scilab memory of the created parameter in the list output parameter Pointer the pointer to the data area input parameter Description A C interface function which allows to create a new Scilab parameter from a pointer in a mtlist Scilab Gateway API 3039 WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples include stackch include stringh int scicreatelistchar fname int mlistout nlistout int mvar1 nvar1 lvar1 llistvar1 int mvar2 nvar2 lvar2 llistvar2 int mmlist nmlist lmlist The labels of our mlist static const char ListLabels mylistvar1var2 First we create the variables using a classical way The size of the Scilab variables mvar1 1 nvar1 strlena string1 a null terminated string mvar2 2 nvar2 2 A 2x2 double matrix mmlist 3 nmlist 1 A mlist with 3 elements Creation of the Scilab variables Avar1 CreateVar1 c mvar1 nvar1 lvar1 Avar2 CreateVar2 d mvar2 nvar2 lvar2 A CreateVar3 m mmlist nmlist lmlist We store values in the create variables The matrix will be stored in Avar2 stklvar20 1 stklvar21 2 stklvar22 3 stklvar23 4 The string will be stored in Avar1 strncpycstklvar1a string0nvar1 mlistout 3 nlistout 1 now affect the variable to the mlist The labels it corresponds to A mlistmylistvar1var2 CreateListVarFromPtr3 1 S mlistout nlistout ListLabels The value stored in Avar1 it corresponds to A a string CreateListVarFrom3 2 c mvar1 nvar1 llistvar1 lvar1 The value stored in Avar2 it corresponds to A 1 23 4 CreateListVarFrom3 3 d mvar2 nvar2 llistvar2 lvar2 We return only the mlist which has been created at position 3 LhsVar1 3 return 0 Scilab Gateway API 3040 This example is available in SCImodulescoreexamplecreatelist See Also Scilab C Type istk LhsVar CreateVar Scilab Gateway API 3041 Nome CreateVar a C gateway function which allows to create a new Scilab parameter CreateVarStackPos Type mrows ncols lstackpos Parameters StackPos The rank of the parameter to be created input argument Type The Scilab C Type of the parameter to be created input argument STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the matrix to be created input argument ncols the number of columns of the matrix to be created input argument lstackpos the position in the Scilab memory of the created parameter output argument Description A C gateway function which allows to create a new Scilab parameter WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples Scilab Gateway API 3042 include stackch int scimyoneschar fname int mrow ncol lpos mrow 1 ncol 1 We create a scalar CreateVar1 MATRIXOFINTEGERDATATYPE mrow ncol lpos istklpos 1 LhsVar1 1 return 0 See Also Scilab C Type istk LhsVar Scilab Gateway API 3043 Name FindOpt C gateway function find the position of an optional argument given its name Pos FindOptvarname opts Parameters varname the name of the optional parameter opts a C list of optional parameters typedef struct rhsopts int position stack position 1 if not present char name the name of the variable char type a Scilab type like d representing the type of the variable int mn the size of the variable unsigned long int l a pointer to the Scilab stack rhsopts Pos the rank of the optional parameter if it has been found in the parameters sent to the C function 0 otherwise Description A C gateway function which find the position of an optional argument given its name You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding Scilab Gateway API 3044 nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3045 Name FirstOpt C gateway function which returns the position of the first optional parameter Pos FirstOpt Parameters Pos the position of the first optional parameter Rhs 1 if no optional parameters have been given to the function Description A C gateway function which returns the position of the first optional parameter You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts Scilab Gateway API 3046 if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3047 Nome GetListRhsVar a C gateway function which allows to access a parameter stored in a mtlist trans mitted to a Scilab function GetListRhsVarStackPosListPos Type mrows ncols lstackpos Parameters StackPos the rank of the mtlist to be accessed input parameter ListPos the rank in the list of the parameter to be accessed input parameter Type the Scilab type of the parameter to be accessed input parameter Can be see Scilab C Type for more informations STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the accessed parameter output parameter ncols the number of columns of the accessed parameter output parameter lstackpos the position on the stack of the accessed parameter output parameter Description A C gateway function which allows to access a parameter stored in a mtlist transmitted to a Scilab function Scilab Gateway API 3048 WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples In this example the function has one input parameter It gets a mlist and the prints some informations related to the content of the mlist include stackch include sciprinth int sciprintlistchar fname int mlistin nlistin llistin int mtype ntype int mvar1 nvar1 lvar1 int mvar2 nvar2 lvar2 char LabelList NULL CheckRhs11 We accept only 1 parameter GetRhsVar1mmlistinnlistinllistin Get a mlist Get the type and the name of the variables the first element of the mlist GetListRhsVar11SmtypentypeLabelList if strcmpLabelList0mytype0 sciprinterror you must ship a mlist or type mytype return 0 Get the first variable a string GetListRhsVar12cmvar1nvar1lvar1 sciprintvar1 s cstklvar1 Get the second variable a double matrix GetListRhsVar13dmvar2nvar2lvar2 sciprintvar2 f f f f stklvar20 stklvar21 stklvar22 stklvar23 return 0 This example is available in SCImodulescoreexampleprintlist See Also Scilab C Type istk LhsVar Scilab Gateway API 3049 Nome GetRhsVar a C gateway function which allows to access an argument transmitted to a Scilab func tion GetRhsVarStackPos Type mrows ncols lstackpos Parameters StackPos The rank of the variable to be accessed input argument Type The Scilab C Type of the parameter to be accessed input argument STRINGDATATYPE c MATRIXOFSTRINGDATATYPE S MATRIXOFDOUBLEDATATYPE d MATRIXOFRATIONALDATATYPE r MATRIXOFVARIABLESIZEINTEGERDATATYPE I MATRIXOFINTEGERDATATYPE i MATRIXOFBOOLEANDATATYPE b MATRIXOFCOMPLEXDATATYPE z SPARSEMATRIXDATATYPE s TYPEDLISTDATATYPE t MATRIXORIENTEDTYPEDLISTDATATYPE m SCILABPOINTERDATATYPE p GRAPHICALHANDLEDATATYPE h EXTERNALDATATYPE f MATRIXOFPOLYNOMIALDATATYPE x mrows the number of lines of the accessed parameter output argument ncols the number of columns of the accessed parameter output argument lstackpos the position in the Scilab memory of the accessed parameter output argument Description A C gateway function which allows to access a argument transmitted to a Scilab function WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Scilab Gateway API 3050 Examples In this example the function has two input arguments the number of columns first argument the number of lines second argument The goal of this function is to created a matrix of integers equal to 1 include stackch include stringh int scimyoneschar fname int mparam1 nparam1 lparam1 int mparam2 nparam2 lparam2 int moutrow noutcol loutpos int i int pOutPos NULL GetRhsVar1 MATRIXOFINTEGERDATATYPE mparam1 nparam1 lparam1 GetRhsVar2 MATRIXOFINTEGERDATATYPE mparam2 nparam2 lparam2 We create a matrix of ints equal to 1 moutrow istklparam1 The first dimension of the matrix to be created is stored in the first input parameter noutcol istklparam2 The second dimension of the matrix to be created is stored in the second input parameter CreateVar3 MATRIXOFINTEGERDATATYPE moutrow noutcol loutpos pOutPos istkloutpos Get a pointer to the area allocated by CreateVar a pointer to an integer fori0imoutrownoutrowi pOutPosi 1 A concise way to write the preceding line of code fori0imoutrownoutrowi istkloutposi 1 LhsVar1 3 We return the 3rd Scilab variable of our gateway return 0 See Also Scilab C Type istk LhsVar Scilab Gateway API 3051 Name GetType C gateway function which returns the type of a parameter in the Scilab memory SciType GetTypeStackPos Parameters StackPos the position on the Scilab memory of the parameter for which we want to know the type input argument SciType the type defined in the scitypes enum which you can find in stackch of the parameter at position StackPos in the Scilab memory Description GetType is a C gateway function which returns the type of a parameter in the Scilab memory You must include stackch to benefit from this function WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples In this example the C gateway function takes one input argument and prints the integer corresponding to the type of the variable sent as argument in the Scilab console include stackch include sciprinth int scimygettypechar fname sciprintThe type of the first argument is d GetType1 return 0 See Also sciprint scitypes Scilab Gateway API 3052 Name IsOpt C gateway function which checks if a parameter is optional and returns the name of the parameter Res IsOptPosbuffername Parameters Pos the position in the Scilab memory of the parameter to be checked input parameter buffername an array of char of size csiz which correspond to the maximum length of a Scilab variable in which the name of the parameter will be copied if the position Pos is optional output parameter Res 1 if Pos has an optional parameter 0 otherwise Description C gateway function which checks if a parameter is optional and returns the name of the parameter You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 Scilab Gateway API 3053 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3054 Name Lhs A C gateway function which provides the number of output arguments present in the calling Scilab function nbparams Lhs Parameters nbparams the number of output arguments present in the calling Scilab function Description Lhs provides a C gateway function which provides the number of output arguments present in the calling Scilab function You must include stackch to benefit from this function Note Lhs means Left Hand Side WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C gateway function can take several output arguments and prints in the Scilab console the integer corresponding to the number of output arguments detected in the calling Scilab function include stackch include sciprinth int scimylhschar fname sciprintThe number of output arguments is d Lhs return 0 See Also sciprint Rhs Scilab Gateway API 3055 Nome LhsVar a C gateway function which specifies which parameters created inside the C gateway will be returned as an output argument into Scilab LhsVarRankPos RankVar Parameters RankPos as integer providing the rank of the output argument RankVar the rank of the parameter created inside the C gateway to be returned as an Scilab output argument Description A C gateway function which specifies which variables created inside the C interface will be returned as an output argumen into Scilab WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples This example takes a matrix of doubles as input and returns the number of lines first output argument the number of rows second output argument We create an intermediate Scilab parameter which will handle an integer but will neither be used nor returned as an output argument TODO insert an example in the Scilab language include stackch int scimysizedoublechar fname int minrow nincol linpos int moutlinesrow noutlinescol loutlinespos int moutcolumnsrow noutcolumnscol loutcolumnspos int mnop nnop lnop GetRhsVar1 MATRIXOFDOUBLEDATATYPE minrow nincol linpos moutlinesrow 1 noutlinescol 1 We create a scalar moutcolumnsrow 1 noutcolumnscol 1 We create a scalar mnop 1 nnop 1 We create a scalar CreateVar2 MATRIXOFINTEGERDATATYPE moutlinesrow noutlinescol loutlinespos CreateVar3 MATRIXOFINTEGERDATATYPE mnop nnop lnop CreateVar4 MATRIXOFINTEGERDATATYPE moutcolumnsrow noutcolumnscol loutcolumnspos istkloutlinespos minrow the outlinespos parameter handles the number of lines of the matrix sent as argument istklnop 1 store a mere value but will neither be used nor returned to Scilab Scilab Gateway API 3056 istkloutcolumnspos nincol the outcolumnspos parameter handles the number of columns of the matrix sent as argument LhsVar1 2 We set the parameter 2 as an output argument LhsVar2 4 We set the parameter 4 as an output argument return 0 See Also Scilab C Type istk CreateVar GetRhsVar Scilab Gateway API 3057 Name NumOpt C gateway function which returns the number of optional parameters sent to a C function Res NumOpt Parameters Res the number of optional parameters detected Description A C gateway function which returns the number of optional parameters sent to a C function You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername Scilab Gateway API 3058 sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3059 Name OverLoad C gateway function which tells Scilab to look for another overloaded function OverLoadStackPos Parameters StackPos the position in the Scilab memory of the parameter for which we want to take into account for the overloading process input argument Description A C gateway function which tells Scilab to look for another overloaded function Scilab then appends to the name of the function a prefix like sp if the parameter taken into account is sparse and look for the overloaded function You must include stackch to benefit from this function Be careful with the Scilab name of the function Indeed the current overloading process of Scilab works only on Scilab primitives Scilab function wrote in C which must have a Scilab name which is maximum 8 char wide WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function takes one input parameters and prints the integer correspon ding to the type of the variable sent as parameter in the Scilab console include stackch include sciprinth int scicheckproperties2char fname int m1n1l1 CheckRhs11 CheckLhs01 switchVarType1 case scimatrix GetRhsVar1 d m1 n1 l1 sciprint1 is a scalar matrix break case scistrings GetRhsVar1 c m1 n1 l1 sciprint1 is a string break case scisparse sciprint1 is a sparse trying to overload OverLoad1 LhsVar1 0 Scilab Gateway API 3060 return 0 programlisting paraThe buildersce script look like thispara programlisting role exampleCDATA This is the buildersce must be run from this directory lines0 ilibname libcheckproperties files checkpropertiesc libs table chprop2 scicheckproperties2 We must be careful when we choose a scilab function name in case of overloading We Scilab name function must be 8 char max ldflags cflags fflags ilibbuildilibnametablefileslibsMakelibldflagscflagsfflags And now an example of use of this new function chprop2122 chprop2foo overload case deffspchprop2spdispsparse overloaded chprop2sparse123 See Also CheckColumn CheckDims CheckRow CheckScalar CheckVector CheckDimProp CheckLength CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3061 Name Rhs A C gateway function which provides the number of input arguments present in the calling Scilab function nbparams Rhs Parameters nbparams the number of input arguments present in the calling Scilab function Description A C gateway function which provides the number of input arguments present in the calling Scilab function You must include stackch to benefit from this function Note Rhs means Right Hand Side WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C interface function can take several input arguments and prints in the Scilab console the integer corresponding to the number of input arguments detected in the calling Scilab function include stackch include sciprinth int scimyrhschar fname sciprintThe number of input parameters is d Rhs return 0 See Also sciprint Lhs Scilab Gateway API 3062 Name Scierror C gateway function which displays an error message to the user same profil as the printf function and returns an integer value specifying an error level void Scierrorerrorlevelformatvalue1valuen Parameters errorlevel an integer value specifying an error level format a char string Specifies a character string combining literal characters with conversion specifi cations valuei Specifies the data to be converted according to the format parameter returns If the operation is successfull this function returns the number of characters printed not including the trailing 0 used to end output to strings If an error occurred a negative value is returned Description Scierror is a C gateway function which displays an error message to the user same profil as the printf function and returns an integer value specifying an error level You must include Scierrorh to benefit from this function This header is provided in the outputstream module this directory should be included by default Examples In this example the C gateway function prints an error message and returns the error level 133 include stackch include Scierrorh int scimyscierrorchar fname Scierror133An error has occured d 1 return 0 See Also printfconversion printf sciprint Scilab Gateway API 3063 Nome Scilab C Types the C types available in a C gateway Description WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead The stringchar datatype in the Scilab memory STRINGDATATYPE c The stringchar datatype in the Scilab memory MATRIXOFSTRINGDATATYPE S A matrix of double if the size of the matrix is 11 it is a single value MATRIXOFDOUBLEDATATYPE d A matrix of rational if the size of the matrix is 11 it is a single value MATRIXOFRATIONALDATATYPE r A matrix of integer if the size of the matrix is 11 it is a single value MATRIXOFVARIABLESIZEINTEGERDATATYPE I A matrix of little integer little because in reality this int is a complex with the imaginary part set to 0 if the size of the matrix is 11 it is a single value MATRIXOFINTEGERDATATYPE i A matrix of boolean if the size of the matrix is 11 it is a single value MATRIXOFBOOLEANDATATYPE b A matrix of complex if the size of the matrix is 11 it is a single value MATRIXOFCOMPLEXDATATYPE z A sparse matrix if the size of the matrix is 11 it is a single value SPARSEMATRIXDATATYPE s Scilab Gateway API 3064 A list LISTDATATYPE l A typed list TYPEDLISTDATATYPE t A Matrix oriented typed list mlist object are very similar to tlist objects But if M is an mlist for any index i which is not a field name Mi is not the i th field of the list but is interpreted as the i th entry of M seen as a vector This is the only difference between mlist and tlist MATRIXORIENTEDTYPEDLISTDATATYPE m The scilab pointer datatype in the Scilab memory SCILABPOINTERDATATYPE p The scilab graphic handle datatype in the Scilab memory GRAPHICALHANDLEDATATYPE h An external is a function or routine which is used as an argument of some highlevel primitives such as ode optim schur EXTERNALDATATYPE f A matrix of polynomial coeff if the size of the matrix is 11 it is a single value MATRIXOFPOLYNOMIALDATATYPE x See Also mlist list tlist CreateVar GetRhsVar Scilab Gateway API 3065 Name getoptionals C gateway function which initialize the list of optional parameters res getoptionalsfname opts Parameters fname the name passed to the C gateway The name of the calling function of type char input pa rameter opts a C list of optional parameters typedef struct rhsopts int position stack position 1 if not present char name the name of the variable char type a Scilab type like d representing the type of the variable int mn the size of the variable unsigned long int l a pointer to the Scilab stack rhsopts res if no optional parameters has been sent the res 0 Otherwise res 1 Description A C gateway function which initialize the list of optional parameters You must include stackch to benefit from this function WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples A more complete example is available in the directory SCImodulescoreexam pleoptionalparameters include stackch int scioptionalparameterschar fname int m1n1l1 optional names must be stored in alphabetical order in opts static rhsopts opts 1v1d000 1v2d000 1NULLNULL00 int minrhs 1 maxrhs 1 int minlhs 1 maxlhs 3 int nopt iopos res char buffernamecsiz csiz used for character coding Scilab Gateway API 3066 nopt NumOpt CheckRhsminrhsmaxrhsnopt CheckLhsminlhsmaxlhs first non optional argument GetRhsVar 1 c m1 n1 l1 if getoptionalsfnameopts0 return 0 sciprintnumber of optional parameters d NumOpt sciprintfirst optional parameters d FirstOpt sciprintFindOptv1 d FindOptv1 opts sciprintFindOptv2 d FindOptv2 opts if IsOpt1buffername sciprintparameter 1 is optional s buffername if IsOpt2buffername sciprintparameter 2 is optional s buffername if IsOpt3buffername sciprintparameter 3 is optional s buffername return 0 See Also CheckDims CheckRow CheckScalar CheckVector CheckOverLoad CheckDimProp Check Length CheckSameDims CheckSquare How to check parameters Scilab Gateway API 3067 Nome istk Return a pointer to an integer to access data stored at a given position in the Scilab memory istklstackpos Parameters lstackpos the position in the Scilab memory of the parameter to be accessed input argument Description This C gateway function returns a pointer to an integer to access data stored at a given position in the Scilab memory WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples include stackch int scimyoneschar fname int mrow ncol lpos mrow 1 ncol 1 We create a scalar CreateVar1 MATRIXOFINTEGERDATATYPE mrow ncol lpos istklpos 1 We store the value 1 in the memory allocated for output parameter 1 LhsVar1 1 return 0 See Also Scilab C Type CreateVar LhsVar Scilab Gateway API 3068 Name scitypes a C enumeration which defines the types available for a variable Description A C enumeration which defines the types available for a variable You must include stackch to benefit from this type definition The list of available types is the following 1 scimatrix a matrix of doubles 2 scipoly a polynomials matrix 4 sciboolean a boolean matrix 5 scisparse a sparse matrix 6 scibooleansparse a sparse boolean matrix 7 scimatlabsparse a sparse matlab matrix 8 sciints a matrix of integers 9 scihandles a graphical handle 10 scistrings a matrix of strings 11 sciufunction an uncompiled Scilab function 13 scicfunction a compiled Scilab function 14 scilib a library of Scilab functions 15 scilist a Scilab list 16 scitlist a Scilab tlist 17 scimlist a Scilab mlist 128 scipointer was scilufactpointer before Scilab 52 a pointer Integers or enumeration types can be used to check the type of the variables Using the enumeration type is recommended because of the explicit meaning of the value of the enumeration type If this function is used it is probable that GetType will also be used WARNING This API is deprecated from Scilab 520 and is going to be removed with Scilab 60 Please use API Scilab the new Scilab API Examples In this example the C gateway function takes one argument Through a switch case structure we display the type of the variable sent as a parameter include stackch include sciprinth int scimyscitypesrhschar fname switchGetType1 case scimatrix Scilab Gateway API 3069 sciprintA matrix of doubles break case scipoly sciprintA matrix of polynomials break case sciboolean sciprintA matrix of booleans break case scisparse sciprintA sparse matrix of doubles break case scibooleansparse sciprintA sparse matrix of booleans break case scimatlabsparse sciprintA sparse matlab matrix break case sciints sciprintA matrix of integers break case scihandles sciprintA graphic handle break case scistrings sciprintA matrix of strings break case sciufunction sciprintAn uncompiled Scilab function break case scicfunction sciprintA compiled Scilab function break case scilib sciprintA library of Scilab functions break case scilist sciprintA Scilab list break case scitlist sciprintA Scilab tlist break case scimlist sciprintA Scilab mlist break case scipointer case scilufactpointer Renamed in version 52 sciprintA pointer break default sciprintUnknown type Should never happen return 0 Scilab Gateway API 3070 See Also sciprint GetType Scilab Gateway API 3071 Name sciprint A C gateway function which displays standard messages to the user same profil as the C printf function void sciprintformatvalue1valuen Parameters format a char string Specifies a character string combining literal characters with conversion specifi cations valuei Specifies the data to be converted according to the format parameter s d Description This C gateway function provides the capabilities to display messages to the Scilab user Basically it emulates the C language printf function You must include sciprinth to benefit from this function This header is provided in the outputstream module this directory should be included by default Note that if you want to trigger an error the function Scierror is more appropriate Examples In this example the C gateway function prints several messages illustrating the use of the sciprint function in the Scilab console include stackch include sciprinth int scimysciprintchar fname sciprintprinting an integer d 1 sciprintprinting a double f 21 sciprintprinting a string s test return 0 See Also printfconversion printf Scierror Scilab Gateway API 3072 Nome stk Return a pointer to a double to access data stored at a given position in the Scilab memory stklstackpos Parameters lstackpos the position in the Scilab memory of the variable to be accessed input argument Description This C gateway function returns a pointer to a double to access data stored at a given position in the Scilab memory WARNING this API is deprecated It will be removed in Scilab 6 Please use the new API instead Examples include stackch int scimyoneschar fname int mrow ncol lpos mrow 1 ncol 1 We create a scalar CreateVar1 MATRIXOFDOUBLEDATATYPE mrow ncol lpos stklpos 10 We store the value 10 in the area allocated by CreateVar LhsVar1 1 We set the parameter 1 created by CreateVar as an output parameter of the gateway function return 0 See Also Scilab C Type CreateVar LhsVar Capítulo 12 listmanagement listmanagement 3074 Name Boolean reading Scilab gateway How to read matrix of boolean in a list Input argument profile SciErr getMatrixOfBooleanInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piBool Named variable profile SciErr readMatrixOfBooleanInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piBool Return address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of boolean in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos listmanagement 3075 int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings listmanagement 3076 iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab listmanagement 3077 return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL listmanagement 3078 double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr listmanagement 3079 printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL listmanagement 3080 ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem listmanagement 3081 return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec listmanagement 3082 case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr listmanagement 3083 printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL listmanagement 3084 ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3085 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3086 Name Boolean writing Scilab gateway How to add matrix of boolean in a list Create from existing data Input argument profile SciErr createMatrixOfBooleanInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piBool Named variable profile SciErr createMatrixOfBooleanInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable piBool Address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocMatrixOfBooleanInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable piParent Address of the parent of the new item iItemPos Position of the new item in the list listmanagement 3087 iRows Number of rows of the new variable iCols Number of columns of the new variable piBool Returns address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of boolean in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3088 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal listmanagement 3089 ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3090 Name Boolean sparse reading Scilab gateway How to read boolean sparse in a list Input argument profile SciErr getBooleanSparseMatrixInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos Named variable profile SciErr readBooleanSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piNbItem Return number of non zero value piNbItemRow Return number of item in each rows size iRows piColPos Return column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read boolean sparse in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint listmanagement 3091 int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse listmanagement 3092 iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3093 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 listmanagement 3094 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3095 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos listmanagement 3096 SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else listmanagement 3097 sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr listmanagement 3098 printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default listmanagement 3099 return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 listmanagement 3100 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr listmanagement 3101 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3102 Name Boolean sparse writing Scilab gateway How to add boolean sparse matrix in a list Input argument profile SciErr createBooleanSparseMatrixInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos Named variable profile SciErr createBooleanSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add boolean sparse matrix in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 listmanagement 3103 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3104 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 listmanagement 3105 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3106 Name Create List Scilab gateway How to get create a list in Scilab memory Input argument profile SciErr createListvoid pvCtx int iVar int iNbItem int piAddress SciErr createMListvoid pvCtx int iVar int iNbItem int piAddress SciErr createTListvoid pvCtx int iVar int iNbItem int piAddress Named variable profile SciErr createNamedListvoid pvCtx char pstName int iNbItem int piAddress SciErr createNamedTListvoid pvCtx char pstName int iNbItem int piAddress SciErr createNamedMListvoid pvCtx char pstName int iNbItem int piAddress Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iNbItem Number of items in the list piAddress Return address of the list SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the address of a list in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 listmanagement 3107 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 listmanagement 3108 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 listmanagement 3109 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3110 Name Double reading Scilab gateway How to read matrix of double in a list Input argument profile SciErr getMatrixOfDoubleInListvoid pvCtx int piParent int iItemPos int piRows int piCols double pdblReal SciErr getComplexMatrixOfDoubleInListvoid pvCtx int piParent int iItemPos int piRows int piCols double pdblReal double pdblImg Named variable profile SciErr readMatrixOfDoubleInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols double pdblReal SciErr readComplexMatrixOfDoubleInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable pdblReal Return address of real part data array size iRows iCols pdblImg Return address of imaginary part data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of double in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint listmanagement 3111 int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse listmanagement 3112 iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3113 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 listmanagement 3114 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3115 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos listmanagement 3116 SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else listmanagement 3117 sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr listmanagement 3118 printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default listmanagement 3119 return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 listmanagement 3120 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr listmanagement 3121 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3122 Name Double writing Scilab gateway How to add matrix of double in a list Create from existing data Input argument profile SciErr createMatrixOfBooleanInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piBool Named variable profile SciErr createMatrixOfBooleanInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable pdblReal Address of real data array size iCols iRows pdblImg Address of imaginary data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocMatrixOfDoubleInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols double pdblReal SciErr allocComplexMatrixOfDoubleInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable piParent Address of the parent of the new item listmanagement 3123 iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable pdblReal Return address of real data array size iCols iRows pdblImg Return address of imaginary data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of double in a list Two types of functions can be used to write in the memory of Scilab Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3124 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 listmanagement 3125 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3126 Name Get child item Scilab gateway How to get the address of a list child SciErr getListItemAddressvoid pvCtx int piAddress int iItemNum int piItemAddress Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the list iItemNum Item number piItemAddress Return address of the item SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the address of a list child Gateway Source int getlistinfoint piAddress void insertindentvoid static int iLocalTab 0 int commonlistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getlistinfopiAddr LhsVar1 0 return 0 int getlistinfoint piAddress SciErr sciErr listmanagement 3127 int i 0 int iRet 0 int iItem 0 get list item number failed if variable is not a kind of list sciErr getListItemNumberpvApiCtx piAddress iItem ifsciErriErr printErrorsciErr 0 sciprintThis variable is not a list return 0 sciprintList d items address 0x08X iItem piAddress fori 0 i iItem i int iType 0 int piAddrChild NULL sciErr getListItemAddresspvApiCtx piAddress i 1 piAddrChild ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddrChild iType ifsciErriErr printErrorsciErr 0 return 0 ifiType scilist iType scitlist iType scimlist insertindent sciprintChild d i 1 iLocalTab iRet getlistinfopiAddrChild iLocalTab ifiRet return 1 else insertindent sciprintChild d address 0x08X i 1 piAddrChild return 0 void insertindentvoid int i 0 fori 0 i iLocalTab i listmanagement 3128 sciprint Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l5 listl1l2l3 l4 listl5 listl5l5 l6 uint16100020003000 l listl1l2l3l6l4l5 commonlistl listmanagement 3129 Name Item Number Scilab gateway How to get the number of items in a list list mlist tlist SciErr getListItemNumbervoid pvCtx int piAddress int piNbItem Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the list piNbItem Return the number of items SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the number of items in a list list mlist tlist Gateway Source int getlistinfoint piAddress void insertindentvoid static int iLocalTab 0 int commonlistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getlistinfopiAddr LhsVar1 0 return 0 int getlistinfoint piAddress SciErr sciErr int i 0 int iRet 0 listmanagement 3130 int iItem 0 get list item number failed if variable is not a kind of list sciErr getListItemNumberpvApiCtx piAddress iItem ifsciErriErr printErrorsciErr 0 sciprintThis variable is not a list return 0 sciprintList d items address 0x08X iItem piAddress fori 0 i iItem i int iType 0 int piAddrChild NULL sciErr getListItemAddresspvApiCtx piAddress i 1 piAddrChild ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarTypepvApiCtx piAddrChild iType ifsciErriErr printErrorsciErr 0 return 0 ifiType scilist iType scitlist iType scimlist insertindent sciprintChild d i 1 iLocalTab iRet getlistinfopiAddrChild iLocalTab ifiRet return 1 else insertindent sciprintChild d address 0x08X i 1 piAddrChild return 0 void insertindentvoid int i 0 fori 0 i iLocalTab i sciprint listmanagement 3131 Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l5 listl1l2l3 l4 listl5 listl5l5 l6 uint16100020003000 l listl1l2l3l6l4l5 commonlistl listmanagement 3132 Name Integer reading Scilab gateway How to read matrix of integer in a list Input argument profile Signed integer SciErr getMatrixOfInteger8InListvoid pvCtx int piParent int iItemPos int piRows int piCols char pcData SciErr getMatrixOfInteger16InListvoid pvCtx int piParent int iItemPos int piRows int piCols short psData SciErr getMatrixOfInteger32InListvoid pvCtx int piParent int iItemPos int piRows int piCols int piData Unsigned integer SciErr getMatrixOfUnsignedInteger8InListvoid pvCtx int piParent int iItemPos int piRows int piCols unsigned char pucData SciErr getMatrixOfUnsignedInteger16InListvoid pvCtx int piParent int iItemPos int piRows int piCols unsigned short pusData SciErr getMatrixOfUnsignedInteger32InListvoid pvCtx int piParent int iItemPos int piRows int piCols unsigned int puiData Named variable profile Signed integer SciErr readMatrixOfIntger8InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols char pcData SciErr readMatrixOfIntger16InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols short psData SciErr readMatrixOfIntger32InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piData Unsigned integer SciErr readMatrixOfUnsignedInteger8InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols unsigned char pucData SciErr readMatrixOfUnsignedInteger16InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols unsigned short pusData SciErr readMatrixOfUnsignedInteger32InNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols unsigned int puiData Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable pcData pucData psData pusData piData puiData Return address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number listmanagement 3133 Description This help describes how to read matrix of integer in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 listmanagement 3134 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 listmanagement 3135 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal listmanagement 3136 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi listmanagement 3137 ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3138 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 listmanagement 3139 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos listmanagement 3140 SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 listmanagement 3141 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3142 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3143 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3144 Name Integer writing Scilab gateway How to add matrix of integer in a list Create from existing data Input argument profile Signed integer SciErr createMatrixOfInteger8InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols char pcData SciErr createMatrixOfInteger16InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols short psData SciErr createMatrixOfInteger32InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piData Unsigned integer SciErr createMatrixOfUnsignedInteger8InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned char pucData SciErr createMatrixOfUnsignedInteger16InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned short pusData SciErr createMatrixOfUnsignedInteger32InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned int puiData Named variable profile Signed integer SciErr createMatrixOfInteger8InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols char pcData SciErr createMatrixOfInteger16InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols short psData SciErr createMatrixOfInteger32InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int piData Unsigned integer SciErr createMatrixOfUnsignedInteger8InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols unsigned char pucData SciErr createMatrixOfUnsignedInteger16InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols unsigned short pusData SciErr createMatrixOfUnsignedInteger32InNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols unsigned int puiData Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable listmanagement 3145 iCols Number of columns of the new variable pcData8 psData16 piData32 pucData8 pusData16 puiData32 Address of data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile Signed integer SciErr allocMatrixOfInteger8InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols char pcData SciErr allocMatrixOfInteger16InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols short psData SciErr allocMatrixOfInteger32InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int piData Unsigned integer SciErr allocMatrixOfUnsignedInteger8InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned char pucData SciErr allocMatrixOfUnsignedInteger16InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned short pusData SciErr allocMatrixOfUnsignedInteger32InListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols unsigned int puiData Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable pcData8 psData16 piData32 pucData8 pusData16 puiData32 Return address of data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of integer in a list Two types of functions can be used to write in the memory of Scilab listmanagement 3146 Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3147 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr listmanagement 3148 printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3149 Name Pointer reading Scilab gateway How to read pointer in a list Input argument profile SciErr getPointerInListvoid pvCtx int piParent int iItemPos void pvPtr Named variable profile SciErr readPointerInNamedListvoid pvCtx char pstName int piParent int iItemPos void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list pvPtr Return pointer on data SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read pointer in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos listmanagement 3150 int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break listmanagement 3151 case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 listmanagement 3152 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL listmanagement 3153 sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3154 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 listmanagement 3155 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 listmanagement 3156 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData listmanagement 3157 break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3158 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr listmanagement 3159 printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3160 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3161 Name Pointer writing Scilab gateway How to add pointer in a list Input argument profile SciErr createPointerInListvoid pvCtx int iVar int piParent int iItemPos void pvPtr Named variable profile SciErr createPointerInNamedListvoid pvCtx char pstName int piParent int iItemPos void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list pvPtr Address of the pointer SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add pointer in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 listmanagement 3162 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos listmanagement 3163 ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref listmanagement 3164 if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3165 Name Polynomial reading Scilab gateway How to read matrix of polynomial in a list Input argument profile SciErr getMatrixOfPolyInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbCoef double pdblReal SciErr getComplexMatrixOfPolyInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbCoef double pdblReal double pdblImg Named variable profile SciErr readMatrixOfPolyInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbCoef double pdblReal SciErr readComplexMatrixOfPolyInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbCoef double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piNbCoef Return number of coefficient for each polynomial must be allocated pdblReal Address of array of double with imaginary part of coefficient size iCols iRows must be allocated pdblImg Address of array of double with imaginary part of coefficient size iCols iRows must be allocated SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of polynomial in a list Gateway Source static int iTab 0 void insertindentvoid listmanagement 3166 int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos listmanagement 3167 break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild listmanagement 3168 ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 listmanagement 3169 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr listmanagement 3170 printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff listmanagement 3171 return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr listmanagement 3172 sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL listmanagement 3173 ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData listmanagement 3174 break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination listmanagement 3175 sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 listmanagement 3176 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3177 Name Polynomial writing Scilab gateway How to add matrix of polynomial in a list Input argument profile SciErr createMatrixOfPolyInListvoid pvCtx int iVar int piParent int iItemPos char pstVarName int iRows int iCols int piNbCoef double pdblReal SciErr createComplexMatrixOfPolyInListvoid pvCtx int iVar int piParent int iItemPos char pstVarName int iRows int iCols int piNbCoef double pdblReal double pdblImg Named variable profile SciErr createMatrixOfPolyInNamedListvoid pvCtx char pstName int piParent int iItemPos char pstVarName int iRows int iCols int piNbCoef double pdblReal SciErr createComplexMatrixOfPolyInNamedListvoid pvCtx char pstName int piParent int iItemPos char pstVarName int iRows int iCols int piNbCoef double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list pstVarName Variable name in polynomials Scilab5 4 characters max iRows Number of rows of the new variable iCols Number of columns of the new variable piNbCoef Number of coefficient for each polynomial pdblReal Address of array of double with real part of coefficient size iCols iRows pdblImg Address of array of double with imaginary part of coefficient size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of polynomial in a list listmanagement 3178 Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3179 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr listmanagement 3180 printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3181 Name Sparse reading Scilab gateway How to read sparse in a list Input argument profile SciErr getSparseMatrixInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal SciErr getComplexSparseMatrixInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Named variable profile SciErr readSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal SciErr readComplexSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piNbItem Return number of non zero value piNbItemRow Return number of item in each rows size iRows piColPos Return column position for each item size iNbItem pdblReal Return array on real part data size iNbItem pdblImg Return array on imaginary part data size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read sparse in a list listmanagement 3182 Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType listmanagement 3183 case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr listmanagement 3184 printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 listmanagement 3185 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr listmanagement 3186 printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar listmanagement 3187 fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg listmanagement 3188 else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 listmanagement 3189 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData listmanagement 3190 break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr listmanagement 3191 printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 listmanagement 3192 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3193 Name Sparse writing Scilab gateway How to add sparse matrix in a list Create from existing data Input argument profile SciErr createSparseMatrixInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr createComplexSparseMatrixInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Named variable profile SciErr createSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr createComplexSparseMatrixInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem pdblReal Address of real data array size iNbItem pdblImg Address of imaginary data array size iNbItem SciErr Error structure where is stored errors messages history and first error number listmanagement 3194 Description This help describes how to add sparse matrix in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr listmanagement 3195 printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 listmanagement 3196 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end listmanagement 3197 Name String reading Scilab gateway How to read matrix of string in a list Input argument profile SciErr getMatrixOfStringInListvoid pvCtx int piParent int iItemPos int piRows int piCols int piLength char pstStrings Named variable profile SciErr readMatrixOfStringInNamedListvoid pvCtx char pstName int piParent int iItemPos int piRows int piCols int piLength char pstStrings Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piParent Address of the parent of the new item pstName Name of the variable for named functions iItemPos Position of the new item in the list piRows Return number of rows of the variable piCols Return number of columns of the variable piLength Address of array of strings length must be allocated size piRows piCols pstStrings Address of array of char must be allocated size piRows piCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of string in a list Gateway Source static int iTab 0 void insertindentvoid int i 0 fori 0 i iTab i sciprint listmanagement 3198 int getinfoint iRhs int piParent int piAddr int iItemPos int getlistinfoint iRhs int piParent int piAddr int iItemPos int getdoubleinfoint iRhs int piParent int piAddr int iItemPos int getpolyinfoint iRhs int piParent int piAddr int iItemPos int getbooleaninfoint iRhs int piParent int piAddr int iItemPos int getsparseinfoint iRhs int piParent int piAddr int iItemPos int getbsparseinfoint iRhs int piParent int piAddr int iItemPos int getintegerinfoint iRhs int piParent int piAddr int iItemPos int getstringinfoint iRhs int piParent int piAddr int iItemPos int getpointerinfoint iRhs int piParent int piAddr int iItemPos int commonreadchar fnameunsigned long fnamelen SciErr sciErr int iItem 0 int iRet 0 int piAddr NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 getinfo1 NULL piAddr 0 LhsVar1 0 return 0 int getinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRet 0 int iType 0 sciErr getVarTypepvApiCtx piAddr iType switchiType case scimatrix iRet getdoubleinfoiRhs piParent piAddr iItemPos break case scipoly iRet getpolyinfoiRhs piParent piAddr iItemPos break case sciboolean iRet getbooleaninfoiRhs piParent piAddr iItemPos break case scisparse iRet getsparseinfoiRhs piParent piAddr iItemPos break case scibooleansparse iRet getbsparseinfoiRhs piParent piAddr iItemPos break case sciints listmanagement 3199 iRet getintegerinfoiRhs piParent piAddr iItemPos break case scistrings iRet getstringinfoiRhs piParent piAddr iItemPos break case scilist insertindent sciprintList iRet getlistinfoiRhs piParent piAddr iItemPos break case scitlist insertindent sciprintTList iRet getlistinfoiRhs piParent piAddr iItemPos break case scimlist insertindent sciprintMList iRet getlistinfoiRhs piParent piAddr iItemPos break case scipointer iRet getpointerinfoiRhs piParent piAddr iItemPos break default insertindent sciprintUnknown type return 1 return iRet int getlistinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRet 0 int iItem 0 int piChild NULL sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr printErrorsciErr 0 return 0 sciprintd iItem fori 0 i iItem i sciErr getListItemAddresspvApiCtx piAddr i 1 piChild ifsciErriErr printErrorsciErr 0 return 0 iTab iRet getinfoiRhs piAddr piChild i 1 listmanagement 3200 iTab return 0 int getdoubleinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 double pdblReal NULL double pdblImg NULL ifiItemPos 0 not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal pdblImg else sciErr getMatrixOfDoubleInListpvApiCtx piParent iItemPos iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintDouble d x d iRows iCols return 0 int getpolyinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iLen 0 int iRows 0 int iCols 0 listmanagement 3201 char pstVar16 int piCoeff NULL double pdblReal NULL double pdblImg NULL sciErr getPolyVariableNamepvApiCtx piAddr pstVar iLen ifsciErriErr printErrorsciErr 0 return 0 ifiItemPos 0 not in list sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 else sciErr getMatrixOfPolypvApiCtx piAddr iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 else listmanagement 3202 sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piCoeff intmallocsizeofint iRows iCols sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff NULL ifsciErriErr printErrorsciErr 0 return 0 pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piCoeffi pdblImgi doublemallocsizeofdouble piCoeffi ifisVarComplexpvApiCtx piAddr sciErr getComplexMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal pdblImg else sciErr getMatrixOfPolyInListpvApiCtx piParent iItemPos iRows iCols piCoeff pdblReal ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintPoly d x d varname s iRows iCols pstVar fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg freepiCoeff return 0 int getbooleaninfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 listmanagement 3203 int piBool NULL ifiItemPos 0 sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool else sciErr getMatrixOfBooleanInListpvApiCtx piParent iItemPos iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean d x d iRows iCols return 0 int getsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL ifiItemPos 0 Not in list ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos pdblReal else ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal pdblImg else sciErr getSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos pdblReal listmanagement 3204 insertindent sciprintSparse d x d Items d iRows iCols iItem return 0 int getbsparseinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iRows 0 int iCols 0 int iItem 0 int piNbRow NULL int piColPos NULL ifiItemPos 0 Not in list sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iItem piNbRow piColPos else sciErr getBooleanSparseMatrixInListpvApiCtx piParent iItemPos iRows iCols iItem piNbRow piColPos ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintBoolean Sparse d x d Items d iRows iCols iItem return 0 int getintegerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int iPrec 0 int iRows 0 int iCols 0 char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL ifiItemPos 0 Not in list sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3205 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8pvApiCtx piAddr iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16pvApiCtx piAddr iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32pvApiCtx piAddr iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddr iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddr iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddr iRows iCols puiData break default return 1 else sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr printErrorsciErr 0 return 0 switchiPrec case SCIINT8 sciErr getMatrixOfInteger8InListpvApiCtx piParent iItemPos iRows iCols pcData break case SCIINT16 sciErr getMatrixOfInteger16InListpvApiCtx piParent iItemPos iRows iCols psData break case SCIINT32 sciErr getMatrixOfInteger32InListpvApiCtx piParent iItemPos iRows iCols piData break case SCIUINT8 sciErr getMatrixOfUnsignedInteger8InListpvApiCtx piParent iItemPos iRows iCols pucData break case SCIUINT16 sciErr getMatrixOfUnsignedInteger16InListpvApiCtx piParent iItemPos iRows iCols pusData break case SCIUINT32 sciErr getMatrixOfUnsignedInteger32InListpvApiCtx piParent iItemPos iRows iCols puiData break default return 1 listmanagement 3206 ifsciErriErr printErrorsciErr 0 return 0 insertindent ifiPrec 10 sciprintUnsigned sciprintInteger d bits d x d iPrec 10 8 iRows iCols return 0 int getstringinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr int i int iRows 0 int iCols 0 int piLen NULL char pstData NULL ifiItemPos 0 Not in list sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 listmanagement 3207 else sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination sciErr getMatrixOfStringInListpvApiCtx piParent iItemPos iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 ifsciErriErr printErrorsciErr 0 return 0 insertindent sciprintStrings d x d iRows iCols return 0 int getpointerinfoint iRhs int piParent int piAddr int iItemPos SciErr sciErr void pvPtr NULL ifiItemPos 0 sciErr getPointerpvApiCtx piAddr pvPtr else sciErr getPointerInListpvApiCtx piParent iItemPos pvPtr ifsciErriErr listmanagement 3208 printErrorsciErr 0 return 0 insertindent sciprintPointer 0x08X pvPtr return 0 Scilab test script function readall d 123456789commonreadd spoly0xp1s2s2p p 2p s 3p 2 s 2 612 4 p s 2commonreadp b tftfftcommonreadb spsparse2100012100012100012100012commonreadsp bspsparse1245310tttcommonreadbsp i8 int8123commonreadi8 ui32 uint32321commonreadui32 str may the puffin be withyoucommonreadstr if withmoduleumfpack then Cp taucschfactsp l listlistd p listb sp listi8 bsp listui32 str Cp else l listlistd p listb sp listi8 bsp listui32 str end commonreadl endfunction readall listmanagement 3209 Name String writing Scilab gateway How to add matrix of string in a list Input argument profile SciErr createMatrixOfStringInListvoid pvCtx int iVar int piParent int iItemPos int iRows int iCols char pstStrings Named variable profile SciErr createMatrixOfStringInNamedListvoid pvCtx char pstName int piParent int iItemPos int iRows int iCols char pstStrings Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piParent Address of the parent of the new item iItemPos Position of the new item in the list iRows Number of rows of the new variable iCols Number of columns of the new variable pstStrings Address of array of char size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add matrix of string in a list Gateway Source int listcreatelistchar fnameunsigned long fnamelen SciErr sciErr int piAddr NULL int piChild NULL double pdblData1 135246 double pdblData2 642531 char pstData maybethewithpuffinyou short psData 142536 double pdblPoly1 1 double pdblPoly2 21 double pdblPoly3 123 listmanagement 3210 double pdblPoly4 4321 double pdblPoly5 12345 double pdblPoly6 654321 double pdblPoly pdblPoly1 pdblPoly3 pdblPoly5 pdblPoly2 pdblPoly4 pdblPoly6 int piCoef 135246 int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int piBool 101010101 double pdblDataPtr NULL sciErr createListpvApiCtx 1 8 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexMatrixOfDoubleInListpvApiCtx Rhs 1 piAddr 1 3 2 pdblData1 pdblData2 ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfStringInListpvApiCtx Rhs 1 piAddr 2 2 3 pstData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfInteger16InListpvApiCtx Rhs 1 piAddr 3 2 3 psData ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfPolyInListpvApiCtx Rhs 1 piAddr 4 x 3 2 piCoef pdblPoly ifsciErriErr printErrorsciErr 0 return 0 sciErr createComplexSparseMatrixInListpvApiCtx Rhs 1 piAddr 5 3 10 4 piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfBooleanInListpvApiCtx Rhs 1 piAddr 6 3 3 piBool ifsciErriErr listmanagement 3211 printErrorsciErr 0 return 0 sciErr createBooleanSparseMatrixInListpvApiCtx Rhs 1 piAddr 7 3 10 4 piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 add list in list sciErr createListInListpvApiCtx Rhs 1 piAddr 8 3 piChild ifsciErriErr printErrorsciErr 0 return 0 sciErr createMatrixOfDoubleInListpvApiCtx Rhs 1 piChild 1 3 2 pdblData1 ifsciErriErr printErrorsciErr 0 return 0 sciErr createSparseMatrixInListpvApiCtx Rhs 1 piChild 2 3 10 4 piNbItemRow piColPos pdblSReal ifsciErriErr printErrorsciErr 0 return 0 pdblDataPtr doublemallocsizeofdouble 4 pdblDataPtr0 1 pdblDataPtr1 2 pdblDataPtr2 3 pdblDataPtr3 4 sciErr createPointerInListpvApiCtx Rhs 1 piChild 3 pdblDataPtr ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 1 return 0 Scilab test script sizeref 8 typeref constantstringint16polynomial sparse boolean boolean sparse list listmanagement 3212 dimref list32232332310333103 l listcreatelist if sizel sizeref then errorfailed end for i 1 sizeref if typeofli typerefi then errorfailed end if sizeli dimrefi then errorfailed end end 3213 Name apiscilab apiscilab is the Scilab interface to readwrite data fromto Scilab memory Description In the previous versions of Scilab there was no clear or easy way to extend Scilab or to use it as an embedded application Since Scilab 520 these issues have been tackled by API Scilab Its provides a new consistent doc umented and easy way API This API provides functions to readwrite data fromto Scilab memory It provides many advantages Management of all Scilab data types Consistency over all data types Error management Fully documented Fully tested by unitary tests Straight and named access See the callscilab API to variables And it will be maintained over future versions of Scilab Usually this API is used to extend Scilab capabilities but can be used in other contexts Libraires or CC functions Many librairies have been developped on the freeOpen source or proprietary markets This library can be loaded and used in a high level language like Scilab API Scilab provides the capabilities to interact with such libraries Scilab can be used as computing engine from a third party software This feature is called callscilab when Scilab is used from CC code or javasci when used from Java Access to variable is done through their names named variable Note that old APIs stackXh will not be available after Scilab 60 included See Also Compile and run with callscilab Matrix Management Boolean Management Complex Manage ment String Management CallScilab Authors Sylvestre Ledru 3214 Name Boolean reading Scilab gateway How to read matrix of boolean Input argument profile SciErr getMatrixOfBooleanvoid pvCtx int piAddress int piRows int piCols int piBool Named variable profile SciErr readNamedMatrixOfBooleanvoid pvCtx char pstName int piRows int piCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows of the variable piCols Return number of columns of the variable piBool Return address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read matrix of boolean Gateway Source int readwritebooleanchar fnameunsigned long fnamelen SciErr sciErr int i first variable info real matrix of double int iRows 0 int iCols 0 int piAddr NULL int piBool NULL check input and output arguments CheckRhs11 CheckLhs11 Boolean reading Scilab gateway 3215 get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 get size and data from Scilab memory sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 Do something with data fori 0 i iRows iCols i piBooli piBooli 0 1 0 sciErr createMatrixOfBooleanpvApiCtx Rhs 1 iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script a t f t f t f t f t aref f t f t f t f t f b readwritebooleana if orb aref then errorfailed end 3216 Name Boolean writing Scilab gateway How to write matrices of boolean Input argument profile SciErr createMatrixOfBooleanvoid pvCtx int iVar int iRows int iCols int piBool Named variable profile SciErr createNamedMatrixOfBooleanvoid pvCtx char pstName int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions piRows Return number of rows of the variable piCols Return number of columns of the variable piBool Return address of data array size iRows iCols SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocMatrixOfBooleanvoid pvCtx int iVar int iRows int iCols int piBool Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable iRows Number of rows of the new variable iCols Numbers of columns of the new variable piBool Returns address of real data array size iCols iRows Boolean writing Scilab gateway 3217 SciErr Error structure where is stored errors messages history and first error number Description This help describes how to write matrix of boolean Gateway Source int readwritebooleanchar fnameunsigned long fnamelen SciErr sciErr int i first variable info real matrix of double int iRows 0 int iCols 0 int piAddr NULL int piBool NULL check input and output arguments CheckRhs11 CheckLhs11 get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 get size and data from Scilab memory sciErr getMatrixOfBooleanpvApiCtx piAddr iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 Do something with data fori 0 i iRows iCols i piBooli piBooli 0 1 0 sciErr createMatrixOfBooleanpvApiCtx Rhs 1 iRows iCols piBool ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Boolean writing Scilab gateway 3218 Scilab test script a t f t f t f t f t aref f t f t f t f t f b readwritebooleana if orb aref then errorfailed end 3219 Name Boolean sparse reading Scilab gateway How to read boolean sparse in a gateway Input argument profile SciErr getBooleanSparseMatrixvoid pvCtx int piAddress int piRows int piCols int piNbItem int piNbItemRow int piColPos Named variable profile SciErr readNamedBooleanSparseMatrixvoid pvCtx char pstName int piRows int piCols int piNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows of the variable piCols Return number of columns of the variable piNbItem Return number of non zero value piNbItemRow Return number of item in each rows size iRows piColPos Return column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to read boolean sparse Gateway Source int readwritebsparsechar fnameunsigned long fnamelen SciErr sciErr int i 0 int j 0 int k 0 first variable info real matrix of double int iRows 0 int iCols 0 int piAddr NULL int iNbItem 0 Boolean sparse read ing Scilab gateway 3220 int piNbItemRow NULL int piColPos NULL int iCol 0 int iNewCol 0 int iNewItem 0 int piNewRow NULL int piNewCol NULL check input and output arguments CheckRhs11 CheckLhs11 get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 get size and data from Scilab memory sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iNbItem piNbItemRow piColPos ifsciErriErr printErrorsciErr 0 return 0 Do something with data convert T F and F T iNewItem iRows iCols iNbItem piNewRow intMALLOCsizeofint iRows piNewCol intMALLOCsizeofint iNewItem fori 0 i iRows i piNewRowi iCols piNbItemRowi forj 0 j iCols j int iFind 0 fork 0 k piNbItemRowi k ifpiColPosiCol k j 1 iFind 1 break ifiFind 0 piNewColiNewCol j 1 Boolean sparse read ing Scilab gateway 3221 iCol piNbItemRowi sciErr createBooleanSparseMatrixpvApiCtx Rhs 1 iRows iCols iNewItem piNewRow piNewCol ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script a sparset f t f t f t f t aref sparsef t f t f t f t f b readwritebsparsea if orb aref then errorfailedend 3222 Name Boolean sparse writing Scilab gateway How to add boolean sparse matrix in a gateway Input argument profile SciErr createBooleanSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos Named variable profile SciErr createNamedBooleanSparseMatrixvoid pvCtx char pstName int iRows int iCols int iNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocBooleanSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable iRows Number of rows of the new variable iCols Number of columns of the new variable Boolean sparse writ ing Scilab gateway 3223 iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add boolean sparse matrix in a list Gateway Source int readwritebsparsechar fnameunsigned long fnamelen SciErr sciErr int i 0 int j 0 int k 0 first variable info real matrix of double int iRows 0 int iCols 0 int piAddr NULL int iNbItem 0 int piNbItemRow NULL int piColPos NULL int iCol 0 int iNewCol 0 int iNewItem 0 int piNewRow NULL int piNewCol NULL check input and output arguments CheckRhs11 CheckLhs11 get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 get size and data from Scilab memory sciErr getBooleanSparseMatrixpvApiCtx piAddr iRows iCols iNbItem piNbItemRow piColPos ifsciErriErr Boolean sparse writ ing Scilab gateway 3224 printErrorsciErr 0 return 0 Do something with data convert T F and F T iNewItem iRows iCols iNbItem piNewRow intMALLOCsizeofint iRows piNewCol intMALLOCsizeofint iNewItem fori 0 i iRows i piNewRowi iCols piNbItemRowi forj 0 j iCols j int iFind 0 fork 0 k piNbItemRowi k ifpiColPosiCol k j 1 iFind 1 break ifiFind 0 piNewColiNewCol j 1 iCol piNbItemRowi sciErr createBooleanSparseMatrixpvApiCtx Rhs 1 iRows iCols iNewItem piNewRow piNewCol ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script a sparset f t f t f t f t aref sparsef t f t f t f t f b readwritebsparsea if orb aref then errorfailedend 3225 Name Variable Reference Scilab gateway How to get the address of an argument or a variable in a gateway Input argument profile SciErr getVarAddressFromPositionvoid pvCtx int iVar int piAddress Named variable profile SciErr getVarAddressFromNamevoid pvCtx char pstName int piAddress Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position of the argument in the function call pstName Scilab variable name piAddress Return address of the Scilab variable SciErr Error structure where is stored errors messages history and first error number Description This function retrieves the address of an argument in a gateway Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false iBool sciErriErr 0 1 0 Variable Reference Scilab gateway 3226 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed char pstUnsigned unsigned Variable Reference Scilab gateway 3227 char pstSign pstSigned int iPrec 0 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr sciprintd iItem Variable Reference Scilab gateway 3228 return sciErr Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3229 Name Variable dimension Scilab gateway How to get the dimensions of an argument or a variable stored as matrix Input argument profile SciErr getVarDimensionvoid pvCtx int piAddress int piRows int piCols Named variable profile SciErr getNamedVarDimensionvoid pvCtx char pstName int piRows int piCols Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress The address of the variable pstName Scilab variable name piRows Return number of rows piCols Return number of columns SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the dimensions of a variable in a gateway Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint Variable dimension Scilab gateway 3230 1 for true 0 for false iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints Variable dimension Scilab gateway 3231 char pstSigned signed char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr Variable dimension Scilab gateway 3232 return sciErr sciprintd iItem return sciErr Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3233 Name Variable Type Scilab gateway How to get the type of an argument or a variable within a gateway Input argument profile SciErr getVarTypevoid pvCtx int piAddress int piType Named variable profile SciErr getNamedVarTypevoid pvCtx char pstName int piType Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress The address of the variable pstName Scilab variable name piType Scilab type of the variable scimatrix scistrings sciints Note that the list of the different variable types is available as an enum in stackch SciErr Error structure where is stored errors messages history and first error number Description This help describes how to retrieve the Scilab type of a variable in a gateway Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false Variable Type Scilab gateway 3234 iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed Variable Type Scilab gateway 3235 char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr Variable Type Scilab gateway 3236 sciprintd iItem return sciErr Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3237 Name Variable Complexity Scilab gateway How to get the argument or variable complexity Input argument profile int isVarComplexvoid pvCtx int piAddress Named variable profile int isNamedVarComplexvoid pvCtx char pstName Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the variable pstName Scilab variable name Returned value 0 for real variables and 1 for complex variables Description This help describes how to retrieve the variable complexity Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr Variable Complexi ty Scilab gateway 3238 printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 Variable Complexi ty Scilab gateway 3239 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr sciprintd iItem return sciErr Variable Complexi ty Scilab gateway 3240 Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3241 Name Matrix Type Scilab gateway How to know if an argument or a variable is stored as a matrix Input argument profile int isVarMatrixTypevoid pvCtx int piAddress Named variable profile int isNamedVarMatrixTypevoid pvCtx char pstName Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the variable Returned value 1 if the variable is stored as matrix otherwise 0 Description This help describes how to know if a variable is stored as a matrix In some cases exemple list a variable is not stored as a standard Scilab matrix This function pro vides a way to handle both cases Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr Matrix Type Scilab gateway 3242 printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 Matrix Type Scilab gateway 3243 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr sciprintd iItem return sciErr Matrix Type Scilab gateway 3244 Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3245 Name Double reading Scilab gateway How to read matrices of double in a gateway Input argument profile SciErr getMatrixOfDoublevoid pvCtx int piAddress int piRows int piCols double pdblReal SciErr getComplexMatrixOfDoublevoid pvCtx int piAddress int piRows int piCols double pdblReal double pdblImg Named variable profile SciErr readNamedMatrixOfDoublevoid pvCtx char pstName int piRows int piCols double pdblReal SciErr readNamedComplexMatrixOfDoublevoid pvCtx char pstName int piRows int piCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns pdblReal Return address of real data array size iCols iRows pdblImg Return address of imaginary data array size iCols iRows This argument does not exist with getMatrixOfDouble and readNamedMatrixOfDouble SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of doubles can be handled through the Scilab API Gateway Source int readdoublechar fnameunsigned long fnamelen int i first variable info real matrix of double int iType 0 int iRows 0 int iCols 0 int iComplex 0 int piAddr NULL double pdblReal NULL Double reading Scilab gateway 3246 double pdblImg NULL SciErr sciErr check input and output arguments CheckRhs11 CheckLhs11 First variable get variable address of the first input argument sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 check type sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr iType scimatrix printErrorsciErr 0 return 0 get complexity iComplex isVarComplexpvApiCtx piAddr check complexity ifiComplex get size and data from Scilab memory sciErr getComplexMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal pdblImg else get size and data from Scilab memory sciErr getMatrixOfDoublepvApiCtx piAddr iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 Do something with data if variable is complex switch real part and imaginary part otherwise multiply by 1 ifiComplex sciErr createComplexMatrixOfDoublepvApiCtx Rhs 1 iRows iCols pdblImg pdblReal else Double reading Scilab gateway 3247 fori 0 i iRows iCols i pdblReali pdblReali 1 sciErr createMatrixOfDoublepvApiCtx Rhs 1 iRows iCols pdblReal ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script a 0 1 2 3 4 5 6 7 8 9 10 11 b 23i 122i 221i 320i 419i 518i 617i 716i 815i 914i 1013i 1112i 1211i 1310i 149i 158i 167i 176i 185i 194i 203i 212i 221i 23 a2 readdoublea b2 readdoubleb if ora2 a 1 then errorfailed end if orb2 imagb realb i then errorfailed end 3248 Name Double writing Scilab gateway How to write matrices of doubles in a gateway Create from existing data Input argument profile SciErr createMatrixOfDoublevoid pvCtx int iVar int iRows int iCols double pdblReal SciErr createComplexMatrixOfDoublevoid pvCtx int iVar int iRows int iCols double pdblReal double pdblImg Named variable profile SciErr createNamedMatrixOfDoublevoid pvCtx char pstName int iRows int iCols double pdblReal SciErr createNamedComplexMatrixOfDoublevoid pvCtx char pstName int iRows int iCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Numbers of columns of the new variable pdblReal Address of real data array size iCols iRows pdblImg Address of imaginary data array size iCols iRows This argument does not exist with cre ateMatrixOfDouble and createNamedMatrixOfDouble SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocMatrixOfDoublevoid pvCtx int iVar int iRows int iCols double pdblReal SciErr allocComplexMatrixOfDoublevoid pvCtx int iVar int iRows int iCols double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable Double writing Scilab gateway 3249 iRows Number of rows of the new variable iCols Numbers of columns of the new variable pdblReal Returns address of real data array size iCols iRows pdblImg Returns address of imaginary data array size iCols iRows This argument does not exist with allocMatrixOfDouble SciErr Error structure where is stored errors messages history and first error number Gateway Source int writedoublechar fnameunsigned long fnamelen SciErr sciErr int ij first variable info real matrix of double 3 x 4 int iRows1 3 int iCols1 4 double pdblReal1 NULL second variable info complex matrix of double 4 x 6 int iRows2 4 int iCols2 6 double pdblReal2 NULL double pdblImg2 NULL First variable alloc array of data in OS memory pdblReal1 doublemallocsizeofdouble iRows1 iCols1 fill array with incremental values 0 1 2 3 4 5 6 7 8 9 10 11 fori 0 i iRows1 i forj 0 j iCols1 j pdblReal1i iRows1 j i iCols1 j can be written in a single loop fori 0 i iRows1 iCols1 i pdblReal1i i Double writing Scilab gateway 3250 create a variable from a existing data array sciErr createMatrixOfDoublepvApiCtx Rhs 1 iRows1 iCols1 pdblReal1 ifsciErriErr printErrorsciErr 0 return 0 after creation we can free memory freepdblReal1 Second variable reserve space in scilab memory and fill it sciErr allocComplexMatrixOfDoublepvApiCtx Rhs 2 iRows2 iCols2 pdblReal2 pdblImg2 ifsciErriErr printErrorsciErr 0 return 0 fill array with incremental values for real part and decremental for imaginary part 23i 122i 221i 320i 419i 518i 617i 716i 815i 914i 1013i 1112i 1211i 1310i 149i 158i 167i 176i 185i 194i 203i 212i 221i 23 fori 0 i iRows2 i forj 0 j iCols2 j pdblReal2i iRows2 j i iCols2 j pdblImg2 i iRows2 j iRows2 iCols2 1 i iCols2 j can be written in a single loop fori 0 i iRows2 iCols2 i pdblReal2i i pdblImg2 i iRows2 iCols2 1 i DO NOT FREE MEMORY in this case its the Scilab memory assign allocated variables to Lhs position LhsVar1 Rhs 1 LhsVar2 Rhs 2 return 0 Scilab test script aref 0 1 2 3 4 5 6 7 8 9 10 11 Double writing Scilab gateway 3251 bref 23i 122i 221i 320i 419i 518i 617i 716i 815i 914i 1013i 1112i 1211i 1310i 149i 158i 167i 176i 185i 194i 203i 212i 221i 23 ab writedouble if ora aref then errorfailedend if orb bref then errorfailedend 3252 Name Integer Precision Scilab gateway How to get precision of an integer matrix SciErr getMatrixOfIntegerPrecisionvoid pvCtx int piAddress int piPrecision SciErr getNamedMatrixOfIntegerPrecisionvoid pvCtx char pstName int piPrecision Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the variable pstName Name of the variable for named functions piPrecision Return precision of an integer variable SCIINT8 SCIUINT8 SCIINT16 SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get precision of an integer matrix Gateway Source SciErr printfinfoint iVar int commonfunctionchar fnameunsigned long fnamelen SciErr sciErr int i int piAddr1 NULL int iBool 0 fori 0 i Rhs i sciErr printfinfoi 1 ifsciErriErr printErrorsciErr 0 break sciprint 1 for true 0 for false iBool sciErriErr 0 1 0 sciErr createMatrixOfBooleanpvApiCtx 1 1 1 iBool ifsciErriErr printErrorsciErr 0 Integer Precision Scilab gateway 3253 return 0 assign allocated variables to Lhs position LhsVar1 1 return 0 SciErr printfinfoint iVar SciErr sciErr int piAddr NULL int iType 0 int iRows 0 int iCols 0 int iItem 0 int iComplex 0 sciErr getVarAddressFromPositionpvApiCtx iVar piAddr ifsciErriErr return sciErr sciprintVariable d information iVar sciErr getVarTypepvApiCtx piAddr iType ifsciErriErr return sciErr sciprint Type switchiType case scimatrix sciprintdouble break case scipoly sciprintpolynomial break case sciboolean sciprintboolean break case scisparse sciprintsparse break case scibooleansparse sciprintbooleansparse break case sciints char pstSigned signed char pstUnsigned unsigned char pstSign pstSigned int iPrec 0 sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr iPrec Integer Precision Scilab gateway 3254 ifsciErriErr return sciErr ifiPrec 10 pstSign pstUnsigned sciprints integer d bits pstSign iPrec 10 8 break case scistrings sciprintstrings break case scilist sciprintlist break case scitlist sciprinttlist break case scimlist sciprintmlist break default sciprintNot manage by this function return sciErr ifisVarComplexpvApiCtx piAddr sciprint Complex Yes sciprint Dimensions ifisVarMatrixTypepvApiCtx piAddr sciErr getVarDimensionpvApiCtx piAddr iRows iCols ifsciErriErr return sciErr sciprintd x d iRows iCols else sciErr getListItemNumberpvApiCtx piAddr iItem ifsciErriErr return sciErr sciprintd iItem return sciErr Integer Precision Scilab gateway 3255 Scilab test script l1 12i3i23i l2 maythepuffinbewithyou l3 int8123 l4 uint16100020003000 l5 listl1l2l3 l listl1l2l3l4l5 commonfunctionl1 3256 Name Integer reading Scilab gateway How to read matrices of integer in a gateway Input argument profile Signed integer SciErr getMatrixOfInteger8void pvCtx int piAddress int piRows int piCols char pcData8 SciErr getMatrixOfInteger16void pvCtx int piAddress int piRows int piCols short psData16 SciErr getMatrixOfInteger32void pvCtx int piAddress int piRows int piCols int piData32 Unsigned integer SciErr getMatrixOfUnsignedInteger8void pvCtx int piAddress int piRows int piCols unsigned char pucData8 SciErr getMatrixOfUnsignedInteger16void pvCtx int piAddress int piRows int piCols unsigned short pusData16 SciErr getMatrixOfUnsignedInteger32void pvCtx int piAddress int piRows int piCols unsigned int puiData32 Named variable profile Signed integer SciErr readNamedMatrixOfInteger8void pvCtx char pstName int piRows int piCols char pcData8 SciErr readNamedMatrixOfInteger16void pvCtx char pstName int piRows int piCols short psData16 SciErr readNamedMatrixOfInteger32void pvCtx char pstName int piRows int piCols int piData32 Unsigned integer SciErr readNamedMatrixOfUnsignedInteger8void pvCtx char pstName int piRows int piCols unsigned char pucData8 SciErr readNamedMatrixOfUnsignedInteger16void pvCtx char pstName int piRows int piCols unsigned short pusData16 SciErr readNamedMatrixOfUnsignedInteger32void pvCtx char pstName int piRows int piCols unsigned int puiData32 Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns pcData8 pucData8 psData16 pusData16 piData32 puiData32 Returns address of array size piRows piCols SciErr Error structure where is stored errors messages history and first error number Integer reading Scilab gateway 3257 Description This help describes how matrices of integer can be handled through the Scilab API Gateway Source void createoutputint iCoeff int iSize int iRows int iCols void pvDataIn int readintegerchar fnameunsigned long fnamelen SciErr sciErr output variable info int iRows8 0 int iCols8 0 int iRows16 0 int iCols16 0 int iRows32 0 int iCols32 0 int iRowsu8 0 int iColsu8 0 int iRowsu16 0 int iColsu16 0 int iRowsu32 0 int iColsu32 0 int iPrec 0 int piAddr8 NULL int piAddr16 NULL int piAddr32 NULL int piAddru8 NULL int piAddru16 NULL int piAddru32 NULL char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL char pcDataOut NULL short psDataOut NULL int piDataOut NULL unsigned char pucDataOut NULL unsigned short pusDataOut NULL unsigned int puiDataOut NULL check inputouput arguments count CheckRhs66 CheckLhs66 get varialbe address sciErr getVarAddressFromPositionpvApiCtx 1 piAddr8 ifsciErriErr Integer reading Scilab gateway 3258 printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 2 piAddru8 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 3 piAddr16 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 4 piAddru16 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 5 piAddr32 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 6 piAddru32 ifsciErriErr printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr8 iPrec ifsciErriErr iPrec SCIINT8 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru8 iPrec ifsciErriErr iPrec SCIUINT8 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr16 iPrec ifsciErriErr iPrec SCIINT16 Integer reading Scilab gateway 3259 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru16 iPrec ifsciErriErr iPrec SCIUINT16 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr32 iPrec ifsciErriErr iPrec SCIINT32 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru32 iPrec ifsciErriErr iPrec SCIUINT32 printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger8pvApiCtx piAddr8 iRows8 iCols8 pcData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddru8 iRowsu8 iColsu8 pucData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger16pvApiCtx piAddr16 iRows16 iCols16 psData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddru16 iRowsu16 iColsu16 pusData ifsciErriErr printErrorsciErr 0 Integer reading Scilab gateway 3260 return 0 retrieve dimensions and data sciErr getMatrixOfInteger32pvApiCtx piAddr32 iRows32 iCols32 piData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddru32 iRowsu32 iColsu32 puiData ifsciErriErr printErrorsciErr 0 return 0 alloc and fill new variable pcDataOut charcreateoutput2 1 iRows8 iCols8 voidpcData pucDataOut unsigned charcreateoutput4 1 iRowsu8 iColsu8 voidpucData psDataOut shortcreateoutput8 2 iRows16 iCols16 voidpsData pusDataOut unsigned shortcreateoutput16 2 iRowsu16 iColsu16 voidpusData piDataOut intcreateoutput32 4 iRows32 iCols32 voidpiData puiDataOut unsigned intcreateoutput64 4 iRowsu32 iColsu32 voidpuiData create new variable sciErr createMatrixOfInteger8pvApiCtx Rhs 1 iRows8 iCols8 pcDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger8pvApiCtx Rhs 2 iRowsu8 iColsu8 pucDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfInteger16pvApiCtx Rhs 3 iRows16 iCols16 psDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger16pvApiCtx Rhs 4 iRowsu16 iColsu16 pusDataOut ifsciErriErr printErrorsciErr 0 return 0 Integer reading Scilab gateway 3261 create new variable sciErr createMatrixOfInteger32pvApiCtx Rhs 5 iRows32 iCols32 piDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger32pvApiCtx Rhs 6 iRowsu32 iColsu32 puiDataOut ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 Rhs 1 LhsVar2 Rhs 2 LhsVar3 Rhs 3 LhsVar4 Rhs 4 LhsVar5 Rhs 5 LhsVar6 Rhs 6 return 0 void createoutputint iCoeff int iSize int iRows int iCols void pvDataIn int i 0 void pvDataOut voidmallociSize iRows iCols fori 0 i iRows iCols i int iVal 0 memcpyiVal charpvDataIn i iSize iSize iVal iCoeff memcpycharpvDataOut i iSize iVal iSize return pvDataOut Scilab test script a8 int8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au8 uint8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a16 int16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Integer reading Scilab gateway 3262 au16 uint16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a32 int32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au32 uint32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 c8 cu8 c16 cu16 c32 cu32 readintegera8 au8 a16 au16 a32 au32 if orc8 a8 2 then errorfailed end if orcu8 au8 4 then errorfailed end if orc16 a16 8 then errorfailed end if orcu16 au16 16 then errorfailed end if orc32 a32 32 then errorfailed end if orcu32 au32 64 then errorfailed end 3263 Name Integer writing Scilab gateway How to write matrices of integers in a gateway Create from existing data Input argument profile Signed integer SciErr createMatrixOfInteger8void pvCtx int iVar int iRows int iCols char pcData8 SciErr createMatrixOfInteger16void pvCtx int iVar int iRows int iCols short psData16 SciErr createMatrixOfInteger32void pvCtx int iVar int iRows int iCols int piData32 Unsigned integer SciErr createMatrixOfUnsignedInteger8void pvCtx int iVar int iRows int iCols unsigned char pucData8 SciErr createMatrixOfUnsignedInteger16void pvCtx int iVar int iRows int iCols unsigned short pusData16 SciErr createMatrixOfUnsignedInteger32void pvCtx int iVar int iRows int iCols unsigned int puiData32 Named variable profile Signed integer SciErr createNamedMatrixOfInteger8void pvCtx char pstName int iRows int iCols char pcData8 SciErr createNamedMatrixOfInteger16void pvCtx char pstName int iRows int iCols short psData16 SciErr createNamedMatrixOfInteger32void pvCtx char pstName int iRows int iCols int piData32 Unsigned integer SciErr createNamedMatrixOfUnsignedInteger8void pvCtx char pstName int iRows int iCols unsigned char pucData8 SciErr createNamedMatrixOfUnsignedInteger16void pvCtx char pstName int iRows int iCols unsigned short pusData16 SciErr createNamedMatrixOfUnsignedInteger32void pvCtx char pstName int iRows int iCols unsigned int puiData32 Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Numbers of columns of the new variable pcData8 psData16 piData32 pucData8 pusData16 puiData32 Address of data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Integer writing Scilab gateway 3264 Input argument profile Signed integer SciErr allocMatrixOfInteger8void pvCtx int iVar int iRows int iCols char pcData8 SciErr allocMatrixOfInteger16void pvCtx int iVar int iRows int iCols short psData16 SciErr allocMatrixOfInteger32void pvCtx int iVar int iRows int iCols int piData32 Unsigned integer SciErr allocMatrixOfUnsignedInteger8void pvCtx int iVar int iRows int iCols unsigned char pucData8 SciErr allocMatrixOfUnsignedInteger16void pvCtx int iVar int iRows int iCols unsigned short pusData16 SciErr allocMatrixOfUnsignedInteger32void pvCtx int iVar int iRows int iCols unsigned int puiData32 Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable iRows Number of rows of the new variable iCols Numbers of columns of the new variable pcData8 psData16 piData32 pucData8 pusData16 puiData32 Returns address of data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of integers can be handled through the Scilab API Two types of functions can be used to write in the memory of Scilab Gateway Source void createoutputint iCoeff int iSize int iRows int iCols void pvDataIn int readintegerchar fnameunsigned long fnamelen SciErr sciErr output variable info int iRows8 0 int iCols8 0 int iRows16 0 int iCols16 0 int iRows32 0 int iCols32 0 int iRowsu8 0 int iColsu8 0 Integer writing Scilab gateway 3265 int iRowsu16 0 int iColsu16 0 int iRowsu32 0 int iColsu32 0 int iPrec 0 int piAddr8 NULL int piAddr16 NULL int piAddr32 NULL int piAddru8 NULL int piAddru16 NULL int piAddru32 NULL char pcData NULL short psData NULL int piData NULL unsigned char pucData NULL unsigned short pusData NULL unsigned int puiData NULL char pcDataOut NULL short psDataOut NULL int piDataOut NULL unsigned char pucDataOut NULL unsigned short pusDataOut NULL unsigned int puiDataOut NULL check inputouput arguments count CheckRhs66 CheckLhs66 get varialbe address sciErr getVarAddressFromPositionpvApiCtx 1 piAddr8 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 2 piAddru8 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 3 piAddr16 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 4 piAddru16 ifsciErriErr printErrorsciErr 0 return 0 Integer writing Scilab gateway 3266 sciErr getVarAddressFromPositionpvApiCtx 5 piAddr32 ifsciErriErr printErrorsciErr 0 return 0 sciErr getVarAddressFromPositionpvApiCtx 6 piAddru32 ifsciErriErr printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr8 iPrec ifsciErriErr iPrec SCIINT8 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru8 iPrec ifsciErriErr iPrec SCIUINT8 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr16 iPrec ifsciErriErr iPrec SCIINT16 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru16 iPrec ifsciErriErr iPrec SCIUINT16 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddr32 iPrec ifsciErriErr iPrec SCIINT32 printErrorsciErr 0 return 0 check variable precision sciErr getMatrixOfIntegerPrecisionpvApiCtx piAddru32 iPrec Integer writing Scilab gateway 3267 ifsciErriErr iPrec SCIUINT32 printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger8pvApiCtx piAddr8 iRows8 iCols8 pcData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger8pvApiCtx piAddru8 iRowsu8 iColsu8 pucData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger16pvApiCtx piAddr16 iRows16 iCols16 psData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger16pvApiCtx piAddru16 iRowsu16 iColsu16 pusData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfInteger32pvApiCtx piAddr32 iRows32 iCols32 piData ifsciErriErr printErrorsciErr 0 return 0 retrieve dimensions and data sciErr getMatrixOfUnsignedInteger32pvApiCtx piAddru32 iRowsu32 iColsu32 puiData ifsciErriErr printErrorsciErr 0 return 0 alloc and fill new variable pcDataOut charcreateoutput2 1 iRows8 iCols8 voidpcData pucDataOut unsigned charcreateoutput4 1 iRowsu8 iColsu8 voidpucData psDataOut shortcreateoutput8 2 iRows16 iCols16 voidpsData Integer writing Scilab gateway 3268 pusDataOut unsigned shortcreateoutput16 2 iRowsu16 iColsu16 voidpusData piDataOut intcreateoutput32 4 iRows32 iCols32 voidpiData puiDataOut unsigned intcreateoutput64 4 iRowsu32 iColsu32 voidpuiData create new variable sciErr createMatrixOfInteger8pvApiCtx Rhs 1 iRows8 iCols8 pcDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger8pvApiCtx Rhs 2 iRowsu8 iColsu8 pucDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfInteger16pvApiCtx Rhs 3 iRows16 iCols16 psDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger16pvApiCtx Rhs 4 iRowsu16 iColsu16 pusDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfInteger32pvApiCtx Rhs 5 iRows32 iCols32 piDataOut ifsciErriErr printErrorsciErr 0 return 0 create new variable sciErr createMatrixOfUnsignedInteger32pvApiCtx Rhs 6 iRowsu32 iColsu32 puiDataOut ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 Rhs 1 LhsVar2 Rhs 2 LhsVar3 Rhs 3 LhsVar4 Rhs 4 LhsVar5 Rhs 5 Integer writing Scilab gateway 3269 LhsVar6 Rhs 6 return 0 void createoutputint iCoeff int iSize int iRows int iCols void pvDataIn int i 0 void pvDataOut voidmallociSize iRows iCols fori 0 i iRows iCols i int iVal 0 memcpyiVal charpvDataIn i iSize iSize iVal iCoeff memcpycharpvDataOut i iSize iVal iSize return pvDataOut Scilab test script a8 int8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au8 uint8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a16 int16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au16 uint16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a32 int32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 au32 uint32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 c8 cu8 c16 cu16 c32 cu32 readintegera8 au8 a16 au16 a32 au32 if orc8 a8 2 then errorfailed end if orcu8 au8 4 then errorfailed end if orc16 a16 8 then errorfailed end if orcu16 au16 16 then errorfailed end if orc32 a32 32 then errorfailed end if orcu32 au32 64 then errorfailed end 3270 Name Pointer reading Scilab gateway How to read pointer in a gateway Input argument profile SciErr createNamedPointervoid pvCtx char pstName void pvPtr Named variable profile SciErr readNamedPointervoid pvCtx char pstName void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pvPtr Return address of pointer SciErr Error structure where is stored errors messages history and first error number Description This help describes how pointer can be handled through the Scilab API Gateway Source int readpointerchar fnameunsigned long fnamelen SciErr sciErr CheckRhs01 CheckLhs11 ifRhs 0 create mode double pdblData doublemallocsizeofdouble 2 2 pdblData0 1 pdblData1 3 pdblData2 2 pdblData3 4 sciErr createPointerpvApiCtx Rhs 1 voidpdblData else ifRhs 1 read mode int iType 0 int piAddr NULL void pvPtr NULL double pdblData NULL sciErr getVarAddressFromPositionpvApiCtx 1 piAddr Pointer reading Scilab gateway 3271 ifsciErriErr printErrorsciErr 0 return 0 sciErr getPointerpvApiCtx piAddr pvPtr ifsciErriErr printErrorsciErr 0 return 0 pdblData doublepvPtr sciErr createMatrixOfDoublepvApiCtx Rhs 1 2 2 pdblData else return 0 ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script bref 1234 a readpointer b readpointera if orb bref then errorfailed end 3272 Name Pointer writing Scilab gateway How to write pointer in a gateway Create from existing data Input argument profile SciErr getPointervoid pvCtx int piAddress void pvPtr Named variable profile SciErr createNamedPointervoid pvCtx char pstName void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pvPtr Address of pointer SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory SciErr allocPointervoid pvCtx int iVar void pvPtr Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pvPtr Return address of pointer SciErr Error structure where is stored errors messages history and first error number Description This help describes how pointer can be handled through the Scilab API Two types of functions can be used to write in the memory of Scilab Gateway Source int readpointerchar fnameunsigned long fnamelen SciErr sciErr Pointer writing Scilab gateway 3273 CheckRhs01 CheckLhs11 ifRhs 0 create mode double pdblData doublemallocsizeofdouble 2 2 pdblData0 1 pdblData1 3 pdblData2 2 pdblData3 4 sciErr createPointerpvApiCtx Rhs 1 voidpdblData else ifRhs 1 read mode int iType 0 int piAddr NULL void pvPtr NULL double pdblData NULL sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 sciErr getPointerpvApiCtx piAddr pvPtr ifsciErriErr printErrorsciErr 0 return 0 pdblData doublepvPtr sciErr createMatrixOfDoublepvApiCtx Rhs 1 2 2 pdblData else return 0 ifsciErriErr printErrorsciErr 0 return 0 LhsVar1 Rhs 1 return 0 Scilab test script Pointer writing Scilab gateway 3274 bref 1234 a readpointer b readpointera if orb bref then errorfailed end 3275 Name Polynomial Symbolic Variable Scilab gateway How to get the symbolic variable name Input argument profile SciErr getPolyVariableNamevoid pvCtx int piAddress char pstVarName int piVarNameLen Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the variable pstVarName Return the symbolic varaible name piVarNameLen Return the length of pstVarName SciErr Error structure where is stored errors messages history and first error number Description This help describes how to get the symbolic variable name Gateway Source int readpolychar fnameunsigned long fnamelen SciErr sciErr int ij variable info int iRows 0 int iCols 0 int iVarLen 0 int piAddr NULL int piNbCoef NULL double pdblReal NULL double pdblImg NULL char pstVarname NULL check input and output arguments CheckRhs11 CheckLhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 ifisVarComplexpvApiCtx piAddr FALSE Polynomial Symbolic Vari able Scilab gateway 3276 Error return 0 get variable name length sciErr getPolyVariableNamepvApiCtx piAddr NULL iVarLen ifsciErriErr printErrorsciErr 0 return 0 alloc buff to receive variable name pstVarname charmallocsizeofchar iVarLen 11 for null termination get variable name sciErr getPolyVariableNamepvApiCtx piAddr pstVarname iVarLen ifsciErriErr printErrorsciErr 0 return 0 First call retrieve dimmension sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL NULL ifsciErriErr printErrorsciErr 0 return 0 alloc array of coefficient piNbCoef intmallocsizeofint iRows iCols Second call retrieve coefficient sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piNbCoef NULL NULL ifsciErriErr printErrorsciErr 0 return 0 alloc arrays of data pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piNbCoefi pdblImgi doublemallocsizeofdouble piNbCoefi Third call retrieve data sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piNbCoef pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 Polynomial Symbolic Vari able Scilab gateway 3277 Do something with Data Invert polynomials in the matrix and invert coefficients fori 0 i iRows iCols 2 i int iPos1 iRows iCols 1 i double pdblSave NULL int iNbCoefSave 0 switch array of coefficient pdblSave pdblReali pdblReali pdblRealiPos1 pdblRealiPos1 pdblSave pdblSave pdblImgi pdblImgi pdblImgiPos1 pdblImgiPos1 pdblSave switch number of coefficient iNbCoefSave piNbCoefi piNbCoefi piNbCoefiPos1 piNbCoefiPos1 iNbCoefSave switch coefficient fori 0 i iRows iCols i forj 0 j piNbCoefi 2 j int iPos2 piNbCoefi 1 j double dblVal pdblRealij pdblRealij pdblRealiiPos2 pdblRealiiPos2 dblVal dblVal pdblImgij pdblImgij pdblImgiiPos2 pdblImgiiPos2 dblVal sciErr createComplexMatrixOfPolypvApiCtx Rhs 1 pstVarname iRows iCols piNbCoef pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 free OS memory freepstVarname freepiNbCoef fori 0 i iRows iCols i freepdblReali freepdblImgi Polynomial Symbolic Vari able Scilab gateway 3278 freepdblReal freepdblImg assign allocated variables to Lhs position LhsVar1 Rhs 1 return 0 Scilab test script coeff1 29i22i16i11i7i30231712831i24i18i13i9i322519141033i26i20i15i034272100028i0003635i0000 4i2ii221653023i17i6i00241800025i19i000262000027i21i00028000000 11742112i8i5i3i013960014i10i000150000000000000000000 x poly0 x p1 1 p2 2 x 3 i p3 4 x2 5 i x 6 p4 7 x3 8 i x2 9 x 10 i p5 11 x4 12 i x3 13 x2 14 i x 15 p6 16 x5 17 i x4 18 x3 19 i x2 20 x 21 i p7 22 x6 23 i x5 24 x4 25 i x3 26 x2 27 i x 28 p8 i p9 2 i x 3 p10 4 i x2 5 x 6 i p11 7 i x3 8 x2 9 i x 10 p12 11 i x4 12 x3 13 i x2 14 x 15 i p13 16 i x5 17 x4 18 i x3 19 x2 20 i x 21 p14 22 i x6 23 x5 24 i x4 25 x3 26 i x2 27 x 28 i p15 29 i x7 30 x6 31 i x5 32 x4 33 i x3 34 x2 35 i 36 p p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p1 readpolyp coeff2 coeffp1 if orcoeff2 coeff1 then errorfailed end 3279 Name Polynomial reading Scilab gateway How to read matrices of polynomials in a gateway Input argument profile SciErr getMatrixOfPolyvoid pvCtx int piAddress int piRows int piCols int piNbCoef double pdblReal SciErr getComplexMatrixOfPolyvoid pvCtx int piAddress int piRows int piCols int piNbCoef double pdblReal double pdblImg Named variable profile SciErr readNamedMatrixOfPolyvoid pvCtx char pstName int piRows int piCols int piNbCoef double pdblReal SciErr readNamedComplexMatrixOfPolyvoid pvCtx char pstName int piRows int piCols int piNbCoef double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns piNbCoef Return number of coefficient for each polynomial must be allocated pdblReal Address of array of double with imaginary part of coefficient size iCols iRows must be allocated pdblImg Address of array of double with imaginary part of coefficient size iCols iRows must be allocated SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of polynomials can be handled through the Scilab API Gateway Source int readpolychar fnameunsigned long fnamelen SciErr sciErr int ij variable info int iRows 0 int iCols 0 Polynomial reading Scilab gateway 3280 int iVarLen 0 int piAddr NULL int piNbCoef NULL double pdblReal NULL double pdblImg NULL char pstVarname NULL check input and output arguments CheckRhs11 CheckLhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 ifisVarComplexpvApiCtx piAddr FALSE Error return 0 get variable name length sciErr getPolyVariableNamepvApiCtx piAddr NULL iVarLen ifsciErriErr printErrorsciErr 0 return 0 alloc buff to receive variable name pstVarname charmallocsizeofchar iVarLen 11 for null termination get variable name sciErr getPolyVariableNamepvApiCtx piAddr pstVarname iVarLen ifsciErriErr printErrorsciErr 0 return 0 First call retrieve dimmension sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols NULL NULL NULL ifsciErriErr printErrorsciErr 0 return 0 alloc array of coefficient piNbCoef intmallocsizeofint iRows iCols Second call retrieve coefficient sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piNbCoef NULL NULL ifsciErriErr printErrorsciErr 0 return 0 Polynomial reading Scilab gateway 3281 alloc arrays of data pdblReal doublemallocsizeofdouble iRows iCols pdblImg doublemallocsizeofdouble iRows iCols fori 0 i iRows iCols i pdblReali doublemallocsizeofdouble piNbCoefi pdblImgi doublemallocsizeofdouble piNbCoefi Third call retrieve data sciErr getComplexMatrixOfPolypvApiCtx piAddr iRows iCols piNbCoef pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 Do something with Data Invert polynomials in the matrix and invert coefficients fori 0 i iRows iCols 2 i int iPos1 iRows iCols 1 i double pdblSave NULL int iNbCoefSave 0 switch array of coefficient pdblSave pdblReali pdblReali pdblRealiPos1 pdblRealiPos1 pdblSave pdblSave pdblImgi pdblImgi pdblImgiPos1 pdblImgiPos1 pdblSave switch number of coefficient iNbCoefSave piNbCoefi piNbCoefi piNbCoefiPos1 piNbCoefiPos1 iNbCoefSave switch coefficient fori 0 i iRows iCols i forj 0 j piNbCoefi 2 j int iPos2 piNbCoefi 1 j double dblVal pdblRealij pdblRealij pdblRealiiPos2 pdblRealiiPos2 dblVal dblVal pdblImgij pdblImgij pdblImgiiPos2 pdblImgiiPos2 dblVal Polynomial reading Scilab gateway 3282 sciErr createComplexMatrixOfPolypvApiCtx Rhs 1 pstVarname iRows iCols piNbCoef pdblReal pdblImg ifsciErriErr printErrorsciErr 0 return 0 free OS memory freepstVarname freepiNbCoef fori 0 i iRows iCols i freepdblReali freepdblImgi freepdblReal freepdblImg assign allocated variables to Lhs position LhsVar1 Rhs 1 return 0 Scilab test script coeff1 29i22i16i11i7i30231712831i24i18i13i9i322519141033i26i20i15i034272100028i0003635i0000 4i2ii221653023i17i6i00241800025i19i000262000027i21i00028000000 11742112i8i5i3i013960014i10i000150000000000000000000 x poly0 x p1 1 p2 2 x 3 i p3 4 x2 5 i x 6 p4 7 x3 8 i x2 9 x 10 i p5 11 x4 12 i x3 13 x2 14 i x 15 p6 16 x5 17 i x4 18 x3 19 i x2 20 x 21 i p7 22 x6 23 i x5 24 x4 25 i x3 26 x2 27 i x 28 p8 i p9 2 i x 3 p10 4 i x2 5 x 6 i p11 7 i x3 8 x2 9 i x 10 p12 11 i x4 12 x3 13 i x2 14 x 15 i p13 16 i x5 17 x4 18 i x3 19 x2 20 i x 21 p14 22 i x6 23 x5 24 i x4 25 x3 26 i x2 27 x 28 i p15 29 i x7 30 x6 31 i x5 32 x4 33 i x3 34 x2 35 i 36 p p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p1 readpolyp coeff2 coeffp1 if orcoeff2 coeff1 then errorfailed end Polynomial reading Scilab gateway 3283 3284 Name Polynomial writing Scilab gateway How to write matrices of polynomials in a gateway Input argument profile SciErr createMatrixOfPolyvoid pvCtx int iVar char pstVarName int iRows int iCols int piNbCoef double pdblReal SciErr createMatrixOfPolyvoid pvCtx int iVar char pstVarName int iRows int iCols int piNbCoef double pdblReal Named variable profile SciErr createNamedMatrixOfPolyvoid pvCtx char pstName char pstVarName int iRows int iCols int piNbCoef double pdblReal SciErr createNamedComplexMatrixOfPolyvoid pvCtx char pstName char pstVarName int iRows int iCols int piNbCoef double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions pstVarName Variable name in polynomials Scilab5 4 characters max iRows Number of rows of the new variable iCols Numbers of columns of the new variable piNbCoef Number of coefficient for each polynomial pdblReal Address of array of double with real part of coefficient size iCols iRows pdblImg Address of array of double with imaginary part of coefficient size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of polynomials can be handled through the Scilab API Gateway Source int writepolychar fnameunsigned long fnamelen SciErr sciErr Polynomial writing Scilab gateway 3285 output variable info polinomial matrix 2 x 4 x 2 x2 4x 5 4x3 14x2 18 2x3 12x2 64 1 8x5 32x3 int iRows 2 int iCols 3 varname x char pstVarName2 x coeficient array int piNbCoef6 243146 data array double pdblReal6 0 double pdblPoly02 21 double pdblPoly14 640122 double pdblPoly23 541 double pdblPoly31 1 double pdblPoly44 180144 double pdblPoly56 0003208 pdblReal0 pdblPoly0 pdblReal1 pdblPoly1 pdblReal2 pdblPoly2 pdblReal3 pdblPoly3 pdblReal4 pdblPoly4 pdblReal5 pdblPoly5 sciErr createMatrixOfPolypvApiCtx Rhs 1 pstVarName iRows iCols piNbCoef pdblReal ifsciErriErr printErrorsciErr 0 return 0 assign allocated variables to Lhs position LhsVar1 Rhs 1 return 0 Scilab test script pref 2 5 18 1 4 0 0 1 14 0 0 4 0 0 0 0 0 064 1 0 0 0 0 12 0 0 2 0 32 0 0 0 0 0 8 l list a writepoly p coeffa if orp pref then errorfailed end 3286 Name Sparse matrix reading Scilab gateway How to read sparse matric in a gateway Input argument profile SciErr getSparseMatrixvoid pvCtx int piAddress int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal SciErr getComplexSparseMatrixvoid pvCtx int piAddress int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Named variable profile SciErr readNamedSparseMatrixvoid pvCtx char pstName int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal SciErr readNamedComplexSparseMatrixvoid pvCtx char pstName int piRows int piCols int piNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns piNbItem Return number of non zero value piNbItemRow Return number of item in each rows size iRows piColPos Return column position for each item size iNbItem pdblReal Return address of real data array size iCols iRows pdblImg Return address of imaginary data array size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how sparse matrix can be handled through the Scilab API Gateway Source int readsparsechar fnameunsigned long fnamelen SciErr sciErr Sparse matrix read ing Scilab gateway 3287 int ijk int piAddr NULL int iRows 0 int iCols 0 int iNbItem 0 int piNbItemRow NULL int piColPos NULL double pdblReal NULL double pdblImg NULL CheckRhs11 sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 ifisVarComplexpvApiCtx piAddr sciErr getComplexSparseMatrixpvApiCtx piAddr iRows iCols iNbItem piNbItemRow piColPos pdblReal pdblImg else sciErr getSparseMatrixpvApiCtx piAddr iRows iCols iNbItem piNbItemRow piColPos pdblReal ifsciErriErr printErrorsciErr 0 return 0 sciprintSparse d items iNbItem k 0 fori 0 i iRows i forj 0 j piNbItemRowi j sciprintdd f i1 piColPosk pdblRealk ifisVarComplexpvApiCtx piAddr sciprint fi pdblImgk sciprint k assign allocated variables to Lhs position LhsVar1 0 return 0 Sparse matrix read ing Scilab gateway 3288 Scilab test script spsparse12453101 2i2 3i3 4i readsparsesp 3289 Name Sparse writing Scilab gateway How to write sparse matrix in a gateway Create from existing data Input argument profile SciErr createSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr createComplexSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Named variable profile SciErr createNamedSparseMatrixvoid pvCtx char pstName int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr createNamedComplexSparseMatrixvoid pvCtx char pstName int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Number of item in each rows size iRows piColPos Column position for each item size iNbItem pdblReal Address of real data array size iNbItem pdblImg Address of imaginary data array size iNbItem This argument does not exist with createSparseMatrix and createNamedSparseMatrix SciErr Error structure where is stored errors messages history and first error number Write directly in Scilab memory Input argument profile SciErr allocSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal SciErr allocComplexSparseMatrixvoid pvCtx int iVar int iRows int iCols int iNbItem int piNbItemRow int piColPos double pdblReal double pdblImg Sparse writing Scilab gateway 3290 Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable iRows Number of rows of the new variable iCols Number of columns of the new variable iNbItem Number of non zero itmes in the sparse piNbItemRow Return address of number of item in each rows size iRows piColPos Return address of column position for each item size iNbItem pdblReal Address of real data array size iNbItem pdblImg Address of imaginary data array size iNbItem This argument does not exist with allocSparseMatrix SciErr Error structure where is stored errors messages history and first error number Description This help describes how to add sparse matrix Two types of functions can be used to write in the memory of Scilab Gateway Source int writesparsechar fnameunsigned long fnamelen SciErr sciErr int piNbItemRow 121 int piColPos 8472 double pdblSReal 1234 double pdblSImg 4321 int iNbItem 4 sciErr createComplexSparseMatrixpvApiCtx Rhs 1 3 10 iNbItem piNbItemRow piColPos pdblSReal pdblSImg ifsciErriErr printErrorsciErr 0 return 0 Sparse writing Scilab gateway 3291 LhsVar1 1 return 0 Scilab test script spref sparse1824273214i23i32i4i 310 sp writesparse if orsp spref then errorfailed end 3292 Name String reading Scilab gateway How to read matrices of strings in a gateway Input argument profile SciErr getMatrixOfStringvoid pvCtx int piAddress int piRows int piCols int piLength char pstStrings SciErr getMatrixOfWideStringvoid pvCtx int piAddress int piRows int piCols int piLength wchart pwstStrings Named variable profile SciErr createNamedMatrixOfStringvoid pvCtx char pstName int iRows int iCols char pstStrings SciErr createNamedMatrixOfWideStringvoid pvCtx char pstName int iRows int iCols wchart pwstStrings Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh piAddress Address of the Scilab variable pstName Name of the variable for named functions piRows Return number of rows piCols Return number of columns piLength Address of array of strings length must be allocated size piRows piCols pstStrings Address of array of char must be allocated size piRows piCols pwstStrings Address of array of wchart must be allocated size piRows piCols SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of strings can be handled through the Scilab API Gateway Source int readstringchar fnameunsigned long fnamelen SciErr sciErr int ij int iLen 0 variable info int iRows 0 int iCols 0 int piAddr NULL String reading Scilab gateway 3293 int piLen NULL char pstData NULL output variable int iRowsOut 1 int iColsOut 1 char pstOut NULL check input and output arguments CheckRhs11 CheckLhs11 get variable address sciErr getVarAddressFromPositionpvApiCtx 1 piAddr ifsciErriErr printErrorsciErr 0 return 0 fisrt call to retrieve dimensions sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols NULL NULL ifsciErriErr printErrorsciErr 0 return 0 piLen intmallocsizeofint iRows iCols second call to retrieve length of each string sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen NULL ifsciErriErr printErrorsciErr 0 return 0 pstData charmallocsizeofchar iRows iCols fori 0 i iRows iCols i pstDatai charmallocsizeofchar piLeni 1 1 for null termination third call to retrieve data sciErr getMatrixOfStringpvApiCtx piAddr iRows iCols piLen pstData ifsciErriErr printErrorsciErr 0 return 0 computer length of all strings fori 0 i iRows iCols i iLen piLeni alloc output variable pstOut charmallocsizeofchar iLen iRows iCols String reading Scilab gateway 3294 initialize string to 0x00 memsetpstOut 0x00 sizeofchar iLen iRows iCols concat input strings in output string fori 0 i iRows i forj 0 j iCols j int iCurLen strlenpstOut ifiCurLen strcatpstOut strcpypstOut strlenpstOut pstDataj iRows i create new variable sciErr createMatrixOfStringpvApiCtx Rhs 1 iRowsOut iColsOut pstOut ifsciErriErr printErrorsciErr 0 return 0 free memory freepiLen fori 0 i iRows iCols i freepstDatai freepstData freepstOut LhsVar1 Rhs 1 return 0 Scilab test script aref may the puffin be with you a may the puffin bewithyou b readstringa if aref b then errorfailed end 3295 Name String writing Scilab gateway How to write matrices of string in a gateway Input argument profile SciErr createMatrixOfStringvoid pvCtx int iVar int iRows int iCols char pstStrings SciErr createMatrixOfWideStringvoid pvCtx int iVar int iRows int iCols wchart pwstStrings Named variable profile SciErr createNamedMatrixOfStringvoid pvCtx char pstName int iRows int iCols char pstStrings SciErr createNamedMatrixOfWideStringvoid pvCtx char pstName int iRows int iCols wchart pwstStrings Parameters pvCtx Scilab environment pointer pass in pvApiCtx provided by apiscilabh iVar Position in the Scilab memory where you want to put the variable pstName Name of the variable for named functions iRows Number of rows of the new variable iCols Numbers of columns of the new variable pstStrings Address of array of char size iCols iRows SciErr Error structure where is stored errors messages history and first error number Description This help describes how matrix of strings can be handled through the Scilab API Gateway Source int writestringchar fnameunsigned long fnamelen SciErr sciErr variable info matrix of string 2 x 3 int iRows 2 int iCols 3 char pstData NULL data to put in the new variable char string11 may char string21 be String writing Scilab gateway 3296 char string12 the char string22 with char string13 puffin char string23 you alloc new array pstData charmallocsizeofchar iRows iCols copy data address to the main array pstData0 string11 pstData1 string21 pstData2 string12 pstData3 string22 pstData4 string13 pstData5 string23 create the variable sciErr createMatrixOfStringpvApiCtx Rhs 1 iRows iCols pstData ifsciErriErr printErrorsciErr 0 return 0 free container freepstData assign allocated variables to Lhs position LhsVar1 Rhs 1 return 0 Scilab test script aref may the puffin be with you b a writestring for i1sizear for j1sizeac b b aij b b end end if b aref then errorfailed end Parte LVIII Gerenciamento de ajuda online 3298 Name addhelpchapter adiciona uma entrada na lista de ajudas addhelpchaptertitlepathmode Parâmetros title string o título da ajuda path string o endereço do diretório contendo os arquivos de ajuda mode booleano T se o diretório pertence à lista de módulos do Scilab F em caso contrário tool boxes O valor padrão é F Descrição Esta função adiciona uma nova entrada na lista de ajudas Os arquivos do capítulo de ajuda devem estar localizados em um único diretório Se o dado título title já existir na lista de ajudas associado com o mesmo endereço nada é feito A função verifica se o diretório existe Ver Também help adddemo Autor Serge Steer INRIA 3299 Name apropos procura por palavraschave na ajuda do Scilab aproposkey aproposregexp Parâmetros key string Fornece a seqüência de caracteres a ser encontrada regexp string Fornece a expressão regular a ser encontrada apenas com Scilab Browser Descrição aproposkey procura por arquivos de ajuda Scilab contendo a palavrachave key na seção de descrições breves aproposregexp procura por arquivos de ajuda Scilab contendo a expressão regular regexp na seção de descrições breves Exemplos aproposode apropos ode apropos list of apropos sinhyperbolic apropos ab procura por ajuda começando com os dois caracteres ab apropos quadraticsolver Ver Também help man 3300 Name foo descrição breve de foo y foox Parâmetros x o que puder ser x y o que puder ser y Descrição Um primeiro parárgrafo que explica o que a função foo computa Se quiser enfatizar um parâmetro então você utiliza o seguinte tag x se quiser enfatizar parte do texto encerreo nestes tags e então utilize estes para obter uma fonte em negrito e finalmente para um estilo em máquina de escrever Um segundo parágrafo Aqui está um exemplo de um link para outra página man first parágrafo simples second toto é o foo francês Exemplos deffyfooxyx define a função foo como a função identidade foototo Ver Também man apropos Autor B P 3301 Name help comando de ajuda online helpkey help Parâmetros key string Fornece a página de ajuda a ser encontrada Descrição help sem argumentos fornece a página de hipertextos dos capítulos de ajuda helpkey exibe o arquivo de ajuda Scilab associado ao dado key Se nenhum arquivo for encon trado helpkey chama automaticamente aproposkey Ver man para mais explicações sobre como escrever novas páginas Ver Também apropos man 3302 Name helpfromsci Geração de arquivos de ajuda e de arquivos de demonstração a partir da seção de comentários de cabeçalho de um arquivofonte sci helpfromsci gera um modelo de função vazio helpfromscifunnamehelpdir gera helpdirfunnamexml a partir de funnamesci helpfromscidirnamehelpdir processa dirnamesci e cria helpdirxml helpfromscidirnamehelpdirhelpdir como acima mas também cria o arquivo de demonstração helpdirdemsce helptxtdemotxthelpfromscifunname retorna funnamexml e funnamedemsce como duas matrizes de texto Parâmetros funname o nome de um único arquivo sci a ser processado dirname nome do diretório onde todos os arquivos sci serão processados helpdir endereço opcional onde o arquivo de ajuda xml será criado demodir endereço opcional onde os arquivos de demonstração demsce serão criados baseados nos códigos da seção Examples helptxt retorna o código da ajuda XML se helpdir for vazio ou o endereço para o novo arquivo xml demotxt retorna o código de demonstração se demodir for vazio ou o endereço para o novo arquivo demsc Descrição helpfromsci é uma versão revisada da função helpskeleton Seu objetivo é gerar arquivos de aju da xml baseados na seção de comentários de cabeçalho dos arquivosfontes sci Opcionalmente os arquivos de demonstração demsce podem ser gerados baseados nos códigos da seção Examples na seção de cometários de cabeçalho dos arquivos sci Para que helpfromsci formate o arquivo xml propriamente os a seção de comentários de cabeçalho deve concordar com algumas regras simples de formatação A primeira linha de comentário seguinte à definição de função deve conter uma descrição breve da função Os comentários restantes são formatados de acordo com os seguintes cabeçalhos opcionais Call ing Sequence Parameters Description Examples See also Used functions Authors e Bibliography As seguintes diretrizes devem ser seguidas ao se escrever os comentários de código fonte Calling Sequence um exemplo por linha Parameters separe o nome do parâmetro e a descrição por um Mantenha a descrição de cada parâmetro na mesma linha Description a formatação do texto pode ser feita utilizando comandos XML Adicionar uma linha de comentário vazia na seção Description é interpretado como começo de um novo parágrafo helpfromsci 3303 See also liste um nome de função por linha Authors escreva um autor em cada linha após o cabeçalho Authors Use para separar os autores de qualquer informação adicional Bibliography escreva uma referência por linha seguindo o cabeçalho References Exemplos helpfromsci abrindo um modelo de códigofonte vazio no editor salve este modelo como testfunsci no diretório corrente antes de executar os próximos comandos do exemplo helpfromscitestfun retornando o esqueleto xml como um string de texto helpfromscitestfun criando o arquivo de ajuda xml no diretório corrente criando ambos os arquivos de ajuda e demonstração no diretório corrente helpfromscitestfun de um diretório raiz de um toolbox uma seqüência de chamamento típica seria helpfromscimacroshelpptBRdemos este comando processaria todos os arquivos sci no diretório de macros e utilizaria a seção de comentários de cabeçalho para atualizar as ajudas xml no diretório helpenUS e reconstruiria os arquivos demsce no diretório demos Ver Também help helpskeleton xmltohtml Autor T Pettersen torbjornpettersenbroadparkno 3304 Name helpskeleton constrói o esqueleto do arquivo de ajuda xml associado à função Scilab txt helpskeletonfunname path language Parâmetros funname string o nome da função path string o endereço onde se criará o arquivo se for requerido Se este argumento não for fornecido o esqueleto é retornado como um string language string com valor possível frFR ou enUS o padrão é enUS txt o código xml ou o endereço do arquivo xml completo Descrição txt helpskeletonfunname gera um vetor de strings contendo o esqueleto do código XML descrevendo a ajuda da função funname fullpath helpskeletonfunnamedirpath gera o código XML descrevendo a aju da da função funname em um arquivo nomeado funnamexml no diretório especificado pelo endereço dirpath Neste caso a função retorna o endereço do arquivo Exemplos function yzfooabyabz1endfunction phelpskeletonfooTMPDIR if isdefeditor funptreditor0 then editorp end Ver Também help Autor Serge Steer INRIA 3305 Name makeindex cria um novo arquivo de índice para ajuda online makeindex Descrição A ajuda online lê primeiro o arquivo indexhtml que contém a lista dos capítulos Este arquivo vem com o Scilab e está no diretório SCIDIRmanlanguage ver man É possível modificar este arquivo de índice enquanto se adiciona interativamente novos arquivos Para isto modifique a variável helps e então utilize a função makeindex Ver Também helps man 3306 Name man Descrição do formato do arquivo de ajuda XML Descrição Os arquivosfontes da ajuda Scilab são escritos em formato XML Arquivosfontes com extensão xml podem ser encontrados nos diretórios SCIDIRman language O nome do arquivo é geralmente associado à palavrachave correspondente a um nome de função na maioria dos casos que descreve Breves palavras sobre XML Um arquivo XML lembra um arquivo HTML mas possui uma sintaxe tanto mais rígida quanto mais livre Livre porque você pode construir os seus próprios tags marcação o conjunto de tags junto com suas regras deve ser descrito em algum lugar geralmente em outro arquivo SCIDIRman manrevdtd para o Scilab e rígida porque uma vez que os tags e regras são definidas as quais são chamadas Definição de Tipo de Documento Document Type Definition DTD você deve re speitálas em particular para todos os tags MYTAG abertos deve corresponder um tag fechado MYTAG O DTD manrevdtd é escrito em SGML e precisa a exata sintaxe requerida por uma página de ajuda XML do Scilab Então se você conhece esta linguagem você pode ler este arquivo O seguinte exemplo anotado veja a próxima seção mostra algumas possibilidades oferecidas por este DTD e pode ser suficiente para escrever páginas de ajuda simples Uma vez que a página XML é escrita e está em conformidade com o DTD ela pode ser transformada em um HTML para ser lida por algum navegador de internet ou pelo navegador tcltk do Scilab ver a seção escolha do navegador nesta página A tradução XML HTML é controlada por um conjunto de regras escritas no arquivo XML SCIDIRmanlanguagehtmlxsl Estas regras estão correntemente mais ou menos restritas para se adequarem aos recursos do navegador tcltk do Scilab que pode exibir corretamente apenas HTML básico Se você utilizar um navegador de HTML e quiser melhorar a aparência terá que modificar este arquivo Como escrever uma página de ajuda XML do Scilab simples a maneira lazzy Caso se deseje escrever um arquivo XML associado a uma nova função Scilab podese utilizar a função helpskeleton para produzir o esqueleto do arquivo XML Na maior parte dos casos o usuário não precisará saber a sintaxe XML Como escrever uma página de ajuda XML do Scilab simples um exemplo Aqui está um exemplo simples de uma página de ajuda XML que descreve uma função do Scilab hipotética chamada foo No seguinte o arquivo XML é exibido em uma fonte de máquina deescrever e recortado em várias partes cada parte precedida por algumas explicações as sociadas O arquivo XML inteiro fooxml está no diretório SCIDIRmanengutili ty e o resultado pode ser exibido clicandose em foo você pode encontrar outros exemplos no diretório SCIDIRexamplesmanexamplesxml Finalmente note que alguns pares de tags TAG TAG foram renomeados aqui ATAG ATAG Isto porque alguns scripts do Scilab que realizam trabalhos sobre ou a partir dos arquivos XML não verificam se um tag está dentro de uma entrada VERBATIM As primeiras três linhas do arquivo são mandatórias a segunda precisa o endereço para o arquivo DTD e a terceira formada pelo tag MAN inicia a descrição hierárquica o arquivo deve terminar man 3307 com o tag MAN As quatro entradas seguintes LANGUAGE TITLE TYPE e DATE também são mandatórias nesta ordem o texto correspondente a TYPE sendo geralmente função do Scilab na maior parte dos casos mas pode ser simplesmente palavrachave do Scilab ou tipo de dados do Scilab dependendo do que explica a página de ajuda DOCTYPE MAN SYSTEM SCIDIRmanmanrevdtd MAN LANGUAGEengLANGUAGE TITLEfooTITLE TYPEfunção do ScilabTYPE DATELastChangedDateDATE A primeira destas duas entradas seguintes SHORTDESCRIPTION é mandatória e importante des de que as palavras do texto da descrição curta short description são utilizadas pelo comando apro pos para buscar páginas de ajuda a partir de uma palavrachave a descrição curta é utilizada para construir o arquivo whatishtml correspondente ao seu toolbox e o comando apropos key word faz uma pesquisa em todos os arquivos whatis e propõe os links para cada página onde a palavra keyword se encontra em sua descrição curta na verdade os tags reais associados são SHORTDESCRIPTION e SHORTDESCRIPTION e não ASHORTDESCRIPTION e ASHORTDESCRIPTION A próxima entrada CALLINGSEQUENCE deve ser utilizada ao se descrever uma função mas não é estritamente mandatória Se a sua função possui várias seqüências de chamamento utilize várias entradas CALLINGSEQUENCEITEM ASHORTDESCRIPTION namefoodescrição curta de fooASHORTDESCRIPTION CALLINGSEQUENCE CALLINGSEQUENCEITEMy fooxCALLINGSEQUENCEITEM CALLINGSEQUENCE A entrada seguinte PARAM não é estritamente mandatória mas é a boa para descrever cada parâmetro de entrada e saída no caso de uma função PARAM PARAMINDENT PARAMITEM PARAMNAMExPARAMNAME PARAMDESCRIPTION SP o que pode ser xSP PARAMDESCRIPTION PARAMITEM PARAMITEM PARAMNAMEyPARAMNAME PARAMDESCRIPTION SP o que pode ser ySP PARAMDESCRIPTION PARAMITEM PARAMINDENT PARAM A entrada DESCRIPTION é talvez a mais significativa mas não é estritamente mandatória e pode ser mais sofisticada que neste exemplo por exemplo você pode ter subentradas DESCRIPTIONITEM Aqui você vê como escrever vários parágrafos cada um encerrado pelos tags P e P como enfatizar uma variável ou um nome de função encerrandoos por tags VERB e VERB como enfatizar uma parte o texto EM ou BD e TT para colocar em man 3308 fonte de máquina de escrever e finalmente como colocar um link para outra página de ajuda na verdade os tags associados são LINK e LINK e não ALINK e ALINK DESCRIPTION P Um primeiro parágrafo explica o que a função foo computa Se você deseja enfatizar um nome de parâmetro você pode utilizar o segunte tag VERBxVERB se você desejar enfatizar parte do texto EMencerrea nestes tagsEM e use estes BDpara uma fonte em negritoBD e finalmente TTpara um estilo em máquina de escreverTT P P Um segundo parágrafo Aqui vai um exemplo de um link para outra página ALINKmanALINK P DESCRIPTION Aqui está como escrever a sua própria entrada por exemplo para escrever observações eou notas sobre a sua maravilhosa função SECTION labelNotes P Aqui está uma lista de notas P ITEM labelfirstSPblablablaSPITEM ITEM labelsecondSPtoto é o francês de fooSPITEM SECTION Uma entrada importante é EXAMPLE que é reservada para mostrar usos no Scilab da sua função comece com exemplos simples Note que você deve fechar esta entrada com EXAMPLE e não como aqui com EXAMPLE mais uma vez este é um truque ruim para evitar problemas de interpretação EXAMPLECDATA deffyfooxyx definindo a função foo como a função identidade foototo EXAMPLE Esta última parte explica como colocar links para outras páginas de ajuda relacionadas como já foi dito antes os bons tags são LINK e LINK e não ALINK e ALINK e finalmente como revelar o seu nome se você quiser utilize uma entrada AUTHORITEM por autor Talvez seja uma boa idéia colocar um endereço de email se você procura por relatos de bugs SEEALSO SEEALSOITEM ALINKmanALINK SEEALSOITEM SEEALSOITEM ALINKaproposALINK SEEALSOITEM SEEALSO AUTHOR AUTHORITEMB PAUTHORITEM AUTHOR MAN man 3309 Como criar um capítulo de ajuda Crie um diretório e escreva um conjunto de arquivos XML construídos como descrito acima Então inicie o Scilab e execute xmltohtmldir onde é um dir string fornecendo o endereço do diretório ver xmltohtml para mais detalhes Como fazer o Scilab reconhecer um novo capítulo de ajuda Isto pode ser feito através da função addhelpchapter Exemplos function yfooabcya2bcendfunction pathhelpskeletonfooTMPDIR if isdefeditor funptreditor0 then editorpath end Ver Também apropos help helpskeleton 3310 Name manedit editando item do manual maneditmanitem Parâmetros manitem string geralmente o nome de uma função Descrição editmanitem abre o arquivo xml associado a manitem no editor Se não há arquivo xml associado a manitem e manitem é o nome de uma função Scilab o xpad abre com o esqueleto do arquivo xml produzido por helpskeleton Este arquivo está localizado em TMPDIR Exemplos maneditmanedit function xyzfoo123ab xabyabzab endfunction manedit foo123 Ver Também help helpskeleton 3311 Name helps variável definindo o endereço dos diretórios de ajuda Descrição A variável global helps é uma matriz N x 2 de strings A késima linha de helps helpsk representa o késimo capítulo do manual e é feita de dois strings helpsk1 é o nome de endereço absoluto de um diretório helpsk2 é um título para este diretório Por exemplo para k2 nós temos o capítulo de gráficos helps2 A variável helps é definida no arquivo de inicialização do Scilab SCIscilabstart Para adicionar um novo diretório de ajuda o usuário deve adicionar uma linha a helps Uma linha para cada diretório Por exemplo helpshelps PathOfMyHelpDirMyTitle habilita o navegador de ajuda do Scilab a procurar por itens do manual de ajuda no diretório com endereço PathOfMyHelpDir MyTitle é então o título do novo capítulo de ajuda Um diretório válido deve conter 1 Um conjunto de arquivoshtml ex item1html item2html etc Os arquivos html são geralmente construídos de arquivos XML 2 Um arquivo whatishtml que deve conter um formato especial Cada linha de whatis deve ser como segue BRA HREFitemhtmlitemA rápida descrição item é o item da ajuda ie o comando help item exibe o conteúdo do arquivo itemhtml O comando apropos keyword retorna as linhas de todos os arquivos whatishtml nos quais a palavrachave keyword aparece Em plataformas Linux o Scilab provê um Makefile para transformar páginas xml pages em páginas html ver SCIDIRexamplesmanexamples Ver Também apropos help man 3312 Name xmltohtml converte arquivos de ajuda xml do Scilab para formato HTML xmltohtmldirs titles dirlanguage defaultlanguage Parâmetros dirs vetor de strings um conjunto de endereços de diretórios para os quais os manuais html devem ser gerados ou titles vetor de strings títulos associados a endereços de diretórios ou dirlanguage vetor de strings idiomas associados a endereços de diretórios ou defaultlanguage vetor de strings idiomas padrões associados aos endereços de diretórios ou Se um arquivo XML estiver faltando em dirlanguage ele é copiado de defaultlanguage Descrição Converte arquivos de ajuda Scilab contidos em um conjunto de diretórios para formato HTML Exemplos example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Construindo a ajuda em francês myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR myfrenchhtmldir xmltohtmlmyfrenchhelpdirmyfrenchhelptitlefrFR Construindo a ajuda em inglês myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 enUS myenglishhtmldir xmltohtmlmyenglishhelpdirmyenglishhelptitleenUS xmltohtml 3313 Construindo a ajuda em chinês mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW mychinesehtmldir xmltohtmlmychinesehelpdirmychinesehelptitlezhTW Ver Também help addhelpchapter 3314 Name xmltojar converte arquivos de ajuda xml do Scilab para formato javaHelp xmltojardirs titles dirlanguage defaultlanguage Parâmetros dirs vetor de strings um conjunto de endereços de diretórios para os quais os manuais html devem ser gerados ou titles vetor de strings títulos associados a endereços de diretórios ou dirlanguage vetor de strings idiomas associados a endereços de diretórios ou defaultlanguage vetor de strings idiomas padrões associados aos endereços de diretórios ou Se um arquivo XML estiver faltando em dirlanguage ele é copiado de defaultlanguage Descrição Converte arquivos de ajuda Scilab contidos em um conjunto de diretórios para formato jar Exemplos example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Construindo a ajuda em francês myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR xmltojarmyfrenchhelpdirmyfrenchhelptitlefrFR Construindo a ajuda em inglês myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 enUS xmltojarmyenglishhelpdirmyenglishhelptitleenUS xmltojar 3315 Construindo a ajuda em chinês mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW xmltojarmychinesehelpdirmychinesehelptitlezhTW Adicionando capítulos de ajuda em francês inglês e chinês if getlanguage frFR then addhelpchaptermyfrenchhelptitlemymodulepathjar elseif getlanguage zhTW then addhelpchaptermychinesehelptitlemymodulepathjar else addhelpchaptermyenglishhelptitlemymodulepathjar end Ver o resultado no navegador de ajuda help Deletando capítulos de ajuda em francês e inglês if getlanguage frFR then delhelpchaptermyfrenchhelptitle else delhelpchaptermyenglishhelptitle end Ver Também help addhelpchapter 3316 Name xmltopdf converte arquivos de ajuda xml do Scilab para formato PDF xmltopdfdirs titles dirlanguage defaultlanguage Parâmetros dirs vetor de strings um conjunto de endereços de diretórios para os quais os manuais pdf devem ser gerados ou titles vetor de strings títulos associados a endereços de diretórios ou dirlanguage vetor de strings idiomas associados a endereços de diretórios ou defaultlanguage vetor de strings idiomas padrões associados aos endereços de diretórios ou Se um arquivo XML estiver faltando em dirlanguage ele é copiado de defaultlanguage Descrição Converte arquivos de ajuda Scilab contidos em um conjunto de diretórios para formato PDF Exemplos example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Construindo a ajuda em francês myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR myfrenchpdf xmltopdfmyfrenchhelpdirmyfrenchhelptitlefrFR Construindo a ajuda em inglês myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 enUS myenglishpdf xmltopdfmyenglishhelpdirmyenglishhelptitleenUS xmltopdf 3317 Construindo a ajuda em chinês mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW mychinesepdf xmltopdfmychinesehelpdirmychinesehelptitlezhTW Ver Também help addhelpchapter 3318 Name xmltops converte arquivos de ajuda xml do Scilab para formato Postscript xmltopsdirs titles dirlanguage defaultlanguage Parâmetros dirs vetor de strings um conjunto de endereços de diretórios para os quais os manuais postscript devem ser gerados ou titles vetor de strings títulos associados a endereços de diretórios ou dirlanguage vetor de strings idiomas associados a endereços de diretórios ou defaultlanguage vetor de strings idiomas padrões associados aos endereços de diretórios ou Se um arquivo XML estiver faltando em dirlanguage ele é copiado de defaultlanguage Descrição Converte arquivos de ajuda Scilab contidos em um conjunto de diretórios para formato PS Exemplos example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Construindo a ajuda em francês myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR myfrenchps xmltopsmyfrenchhelpdirmyfrenchhelptitlefrFR Construindo a ajuda em inglês myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 ENUS myenglishps xmltopsmyenglishhelpdirmyenglishhelptitleenUS xmltops 3319 Construindo a ajuda em chinês mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW mychineseps xmltopsmychinesehelpdirmychinesehelptitlezhTW Ver Também help addhelpchapter 3320 Name delhelpchapter Delete an entry in the helps list delhelpchaptertitlemode Parameters title String array Help chapters title mode A boolean if TRUE the chapter is considered as belongs to a internal modules otherwise the chapter is added as external module Its an optional input argument and its default value is F Description This function deletes an entry in the helps list See Also help addhelpchapter 3321 Name xmltochm converts xml Scilab help files to Microsoft Compressed HTML format Windows xmltochmdirs titles dirlanguage defaultlanguage Parameters dirs vector of strings a set of directory paths for which html manuals are to be generated or titles vector of strings titles associated to directory paths or dirlanguage vector of strings languages associated to directory paths or defaultlanguage vector of strings default languages associated to directory paths or If an XML file is missing in the dirlanguage its copied from the defaultlanguage Description converts xml Scilab help files contained in a set of directories into chm files Microsoft HTML Help Downloads Windows httpmsdnmicrosoftcomenusli braryms669985VS85aspx Examples example1 help enUS example1function1xml example1function2xml example1function3xml frFR example1function1xml example1function2xml example1function3xml zhTW example1function1xml example1function2xml example1function3xml mymodulepath pathconvertSCImoduleshelptoolsexamplesexample1ff Build the french help myfrenchhelpdir mymodulepathhelpfrFR myfrenchhelptitle Example 1 frFR res xmltochmmyfrenchhelpdirmyfrenchhelptitlefrFR if MSDOS then dosstart res end xmltochm 3322 Build the english help myenglishhelpdir mymodulepathhelpenUS myenglishhelptitle Example 1 enUS res xmltochmmyenglishhelpdirmyenglishhelptitleenUS if MSDOS then dosstart res end Build the chinese help mychinesehelpdir mymodulepathhelpzhTW mychinesehelptitle Example 1 zhTW res xmltochmmychinesehelpdirmychinesehelptitlezhTW if MSDOS then dosstart res end See Also help addhelpchapter