Scilab教程

合集下载

科学计算自由软件SCILAB基础教程(可编辑)

科学计算自由软件SCILAB基础教程(可编辑)

科学计算自由软件SCILAB基础教程(可编辑)科学计算自由软件SCILAB基础教程第 1 章SCILAB 简介1.1 引言1.2 SCILAB 软件的构成1.3 安装 SCILAB 的系统需求1. 4 SCILAB 主窗口介绍图1.1 SCILAB 3.0 的主窗口图1.2 SCILAB 3.0 的文件菜单项图1.3 SCILAB 3.0 的编辑菜单项图1.4 SCILAB 的选择菜单项图1.5 SCILAB 的控制菜单项图1.6 SCILAB 的编辑器窗口图1.7 SCILAB 的应用窗口图1.8 SCILAB 的帮助窗口1.5 SCILAB 中的基本操作与预定对象SCILAB 中的文件操作1(5(2 界面层次的控制操作SCILAB 主窗口中的快捷键操作SCILAB 中预先定义的对象图1.9 who 指令后的SCILAB 主窗口图1.10 whos 指令后的SCILAB 主窗口1. 6 谈谈如何学习 SCILAB图1.11 SCILAB 的演示窗口图1.12 SCILAB 的选择图形演示窗口图1.13 SCILAB 的选择图形演示窗口图1.14 SCILAB 的一个图形信息窗口图1.15 SCILAB 的一个图形演示窗口第 2 章数据类型2.1 引言2.2 特定符号与常数特定符号特定常数2. 3 标量的数值计算2.4 数值型向量与矩阵的定义及基本运算数值型向量与矩阵的定义数值型向量与矩阵的运算2.5 与数值型矩阵有关的若干常用函数常用矩阵的生成函数size 函数和 matrix 函数从已知矩阵提取部分元素来构成同阶新矩阵的若干函数与方阵的行列式求值、求逆、线性代数方程组的求解、求矩阵特征值与特征向量等有关的函数与矩阵(数组)或向量有关的数据统计函数2(6 向量与矩阵(数组)元素的引用2(7 整型数组2. 8 布尔型向量与矩阵的定义及基本运算2.9 字符串型数据的定义与运算字符串的定义字符串的运算与处理字符串有关的一些常用函数2.10 多项式类型多项式的定义多项式运算有关多项式的几个常用函数2.11 表类型表类型的定义表类型数据的引用,域的插入与删除tlist 和 mlist 类型第 3 章 SCILAB 中的程序设计、脚本文件与函数3.1 引言3.2 顺序结构程序设计赋值语句输入输出语句3.3 选择结构程序设计if 语句图3.1 不完整if 语句的框图图3.2 完整if 语句的框图select_case 语句图3.3 select 语句框图(else 缺省情形)3.4 循环结构程序设计for 语句图3.4 for 语句的框图while 语句图3.5 while 型循环框图循环语句的嵌套(多重循环语句)continue 语句和 break 语句图3.6 循环体内含有continue 语句的框图图3.7 循环体内含有break 语句的框图3.5 脚本文件与函数脚本文件函数局部变量与全局变量、函数的嵌套定义与递归调用图3.8 用递归调用求 n!示意图(n 4 )有关程序调试的几个常用指令3.6 函数的应用函数名作形式参数――二分法求非线性方程的根图3.9 用二分法求方程p (x ) 0 的根的框图函数的递归调用――求两正整数的最大公因子图3.10 用递归调用求n!示意图多重循环的应用――线性方程组的顺序消元法图3.11 顺序消元法的框图第 4 章计算结果可视化4.1 引言图4.1 图形窗口图4.2 图形窗口的文件菜单图4.3 图形窗口的工具菜单图4.4 图形窗口的编辑菜单4.2 二维图形的绘制plot 指令图4.5 利用指令plot (y,'X', 'Y', 'y f(x )' )画图图4.6 利用指令plot 在同一窗口画两条曲线图4.7 利用指令plot (x,y )画图图4.8 利用指令plot (z,y )在同一窗口画两条曲线plot2d 指令图4.9 利用指令plot2d (x,y )画y sinx 的图形图4.10 利用指令plot2d (x,y )在同一窗口画两条曲线图4.11 利用指令plot2d (x,y, 画曲线y sinx图4.12 利用指令plot2d (x,y, opt+args )在同一窗口画三条曲线图4.13 利用指令plot2d2 (x,y )画曲线y sin2x图4.14 利用指令plot2d3 (x,y )画曲线y sin2x图4.15 利用指令plot2d4 (x,y )画曲线y sin2x4.3 三维图形的绘制函数plot3d( )――三维曲面的绘制图4.16 利用指令plot3d (x,y …)画曲面z sinxcosy图4.17 利用指令plot3d (x,y …)画曲面z x2+y2图4.18 利用指令plot3d (x,y …)画曲面z xy图4.19 利用指令plot3d (x,y …)画曲面z sinxcosy 图4.20 利用指令plot3d 在同一坐标系中画两张曲面函数param3d――三维空间曲线的绘制图4.21 利用指令param3d 画螺旋线图图4.22 利用指令param3d 在同一坐。

Scilab程序设计教程_v0.02

Scilab程序设计教程_v0.02

Scilab程序设计教程内容摘要本书是为适应教学的需要而编写。

全书以Scilab4.1版为基础,介绍Scilab程序设计的方法与应用,主要内容包括:Scilab操作基础、Scilab矩阵及其运算、Scilab程序设计、Scilab 文件操作、Scilab绘图、Scilab数据分析与多项式计算、Scicos图形化仿真环境以及Scilab 常用工具箱。

本书符合教学规律和特点,内容丰富、取材新颖、注重实用、便于教学。

本书可作为高校理工科各专业大学生、研究生学习的教材,也可供广大科技工作者阅读使用。

编者列表:序前言目录1. Scilab基础 (4)1.1. Scilab概述 (4)1.2. Scilab的运行环境与安装 (4)1.3. Scilab集成环境 (6)1.4. Scilab帮助系统 (8)2. Scilab矩阵及其运算 (8)2.1.变量和数据操作 (8)2.2. Scilab矩阵 (11)2.3. Scilab运算 (15)2.4.字符串 (16)2.5.稀疏矩阵 (20)3. Scilab程序设计 (17)3.1. SCI文件 (17)3.2.程序控制结构 (17)3.3.函数文件 (18)3.4.程序举例 (18)3.5.程序调试 (18)4. Scilab文件操作 (19)4.1.文件的打开与关闭 (19)4.2.文件的读写操作 (19)4.3.数据文件定位 (19)5. Scilab绘图 (19)5.1.二维数据曲线图 (19)5.2.其他二维图形 (19)5.3.三维图形 (19)5.4.图形修饰处理 (19)5.5.图像处理及动画制作 (19)6. Scilab数据分析与多项式计算 (20)6.1.数据统计处理 (20)6.2.数据插值 (20)6.3.曲线拟合 (20)6.4.离散傅立叶变换 (20)6.5.多项式计算 (20)7. Scilab解方程与函数极值............................................................................. 错误!未定义书签。

Scilab基本实际操作

Scilab基本实际操作
>> format(12)表示设置数据格式为12位.
Scilab 预定义的一些常数:
i: 基本虚数单位
pi: 圆周率(π=3.1415926...)
e: 欧拉常数(е=2.7182818...)
inf: 表示无限大, 例如1/0
nan或NaN: 表示非数值(Not a number), 例如0/0
>> Scilab将所有数值均保存为double形式,故不需要变量声明,Scilab会自动进行变量的创建和 回收。
>> Scilab的基本运算符:加(+)、 减(-)、 乘(*)、 除(/)、指数(^); 上述运算符不仅运用于通常实数之间计算,也可运用于矩阵的运算。
>> 变量赋值语句一般格式:
变量名 = 数值 或变量组成表达式 或字符串
x= 0 0.2 0.4 0.6 0.8 1.
-->x=0:0.2:1; -->y=x.*x
// 生成当x=0,0.2,0.4,0.6,0.8,1时, y=x2函数值序列
y= 0 0.04 0.16 0.36 0.64 1.
>> 表达式 y=x.*x中的“.*”表示对应元素相乘; 另外(./)表示对应元素相除,(.^)表示对应元素求幂.
-0.0044772
Scilab变量命名规则 1.变量名必须是英文字母,区分大小写 2.字母间不可留空格
>> Scilab显示当前数据格式是10位(含数值符号),如下图:
>> 函数指令format( )的作用是返回当前数据格式的位数. ans=1. 10. (计算结果ans返回的是行列的矩阵形式) 表示当前数据格式是10位(含数值符号“+,-”,正数的符号“+”一般不显示).

SCILAB_Chap4(学习资料)

SCILAB_Chap4(学习资料)

撰文者:1.中央大氣科學系 楊善文2.(如對本文有貢獻者,記得在此留名。

)程式命令腳本視窗(scipad)的使用:這在第零章已大略說過。

從這章開始到之後的章節,你所需要下的指令行數將會越來越多,主視窗將會逐漸不敷使用。

故筆者建議可以開始去習慣改用scipad來工作了。

在scipad上可以輸入大量行數的語句,存檔後選擇執行鈕後,可以一次執行完。

當寫入的語句如果是系統內定的函式,則自動會以不同顏色顯示,方便使用者閱讀與判斷自己是否有下錯指令語法。

Conférencier : Prénom Nom Date : Transparent 3Scipad語系界面選擇:在[選單]的地方有[語言]可選擇,例如筆者之前的Scipad圖即是法文界面。

執行前一定要存檔。

可從Fichier(檔案)的地方選擇Enregistrer(儲存),如果想要另存新檔,可以選擇Enregistrer sous。

或者也可以直接選擇執行,如果之前沒存,它也會進入存檔界面。

執行程式或是命令腳本:在Exécuter(執行)的地方選擇Charger dans Scilab(讀取進Scilab)。

在edition的地方,有Couper(剪下)、Copier(複製)、Sélectionner tout(全選)、Annuler(取消)等功能。

在Fenêtres(窗戶)的地方,可以切換分頁。

開新分頁在Fichier的地方選擇Nouveau。

在使用Scipad寫程式或命令腳本時,最好在首行加入clear指令,它的功用是清除之前所做的變數宣告。

主要原因是避免之前的宣告影響到腳本中的程式碼,也可以清空記憶體中多餘的變數所佔用的空間。

如果只是想清除之前某個特定的變數,可以在clear後接該變數名即可。

例如:clear x y;如想在行與行之間插入注解語句,可以在該行頭加入:''//'',與C++語法相同。

scilab使用辅导

scilab使用辅导
信息技术教研组 袁中果
Hale Waihona Puke 国人民大学附属中学练习P22
信息技术教研组 袁中果
中国人民大学附属中学
复杂判断结构
If 表达式 1 语句序列1 elseif表达式 1 语句序列2 else 语句序列3 …… end
信息技术教研组 袁中果
中国人民大学附属中学
练习
给出一个百分制成绩,要求输出成 绩等级‘A’、 ‘B’、 ‘C’、 ‘D’、 ‘E’。90分以上为‘A’ ,80~89分为 ‘B’,70~79分为‘C’,60~69分为 ‘D’,60分以下为‘E’。
信息技术教研组 袁中果
中国人民大学附属中学
三种基本结构
循环结构
While型 Until型
A
A
P1 Y 成立 N成立
P2
不成立
图2.7
信息技术教研组 袁中果
中国人民大学附属中学
选择结构
If 表达式 语句序列1 else
语句序列2
If 表达式 语句序列1 end
end
信息技术教研组 袁中果
中国人民大学附属中学
信息技术教研组 袁中果
中国人民大学附属中学
P7练习A 4
3x-2y+z=-4 5x+2y-3z=12 x+3y+5z=-1 x+y+z=12 3x=3y-z=16 x-y-z=-2
信息技术教研组 袁中果
中国人民大学附属中学
程序设计
变量 在scilab中变量的定义是很自由的,几乎大部 分的字串都可以做变量。例如x=3;a2=14; 但是 变量开头不可以是数字。同時也不可以將Scilab 內定常量更改它的数值。 常量 Scilab的內定常常多半以‘%’開頭,例如圓周 率π,它以‘%pi’來表示。自然常數e:%e。虛 數i:%i。如對這些常量重新定义會出現錯誤信 息。

第1章 SCILAB基础

第1章 SCILAB基础

第一章SCILAB基础本章内容是后续所有内容的基础,读者可以通过本章的学习,了解计算科学软件SCILAB\SCICOS的基本功能和基本操作方法,特别是对SCICOS模块库或工具箱的概念和作用有所了解。

本章需解决的关键问题:SCILAB是什么?可以做什么?如何操作?SCICOS是什么?如何操作?SCICOS和SCILAB之间是什么关系?什么是工具箱?如何安装和加载?本章主要内容:SCILAB基本知识和基本操作;SCICOS基本知识和基本操作;SCICOS工具箱的概念和工具箱的加载方法;本章阅读建议:本章的内容不同于理论知识的学习,建议读者在阅读本章全文的过程中,结合书中讲解,动手在平台上进行操作演练,有助于加深理解和消化本章内容。

本章主要是为初学者提供帮助,已经具备SCILAB\SCICOS基本知识、熟悉其基本操作的读者,可不用学习本章内容。

1.1SCILAB介绍1.1.1 关于SCILAB通用科学软件目前有两大类:进行符号运算的计算机代数系统(Computer Algebra Systems);进行数值计算和专门科学应用设计的通用数值系统(General Purpose Numerical Systems)。

第一类中较为出名的有Maple、Mathematical、Maxima、Axiom和Mupad等,第二类则以MATLAB为代表。

自由开源软件SCILAB就属于第二类。

SCILAB最初是由INRIA 和ENPC 开发,现在由SCILAB 协会维护的开放源代码的科学计算软件。

具有矩阵运算、数值运算、信号处理、程序设计等功能,目前已被广泛应用于教育、科研和工业。

1.1.2 SCILAB基本知识本书内容基于SCILAB 4.1.2版本平台而编写。

此版本软件可以从SCILAB官方主页的链接()下载。

SCILAB中指令和程序的运行可以分为三种情况:命令窗口下的逐句执行、脚本文件的执行、以及SCI函数形式的调用。

第一讲 Scilab基本操作

第一讲  Scilab基本操作

-->x=0:0.2:1; -->y=x.*x
// 生成当x=0,0.2,0.4,0.6,0.8,1时, 0.16 0.36 0.64
y=x2函数值序列
y =
0 0.04 1.
>> 表达式 y=x.*x中的“.*”表示对应元素相乘; 另外(./)表示对应元素相除,(.^)表示对应元素求幂.
-->x=0:0.2:1; -->y=x.^2 y =
>> 在Command窗口下进行数学运算,只需将表达式直接输入提示号(--> )之后,并按【Enter】 键即可。Scilab会将计算结果直接存入变量ans,代表Scilab运算后的答案 (Answer),并在 Command窗口下显示其数值。 >> Scilab将所有数值均保存为double形式,故不需要变量声明,Scilab会自动进行变量的创建和 回收。 >> Scilab的基本运算符:加(+)、 减(-)、 乘(*)、 除(/)、指数(^); 上述运算符不仅运用于通常实数之间计算,也可运用于矩阵的运算。
Scilab 预定义的一些常数: i: 基本虚数单位 pi: 圆周率(π=3.1415926...) e: 欧拉常数(е=2.7182818...) inf: 表示无限大, 例如1/0 nan或NaN: 表示非数值(Not a number), 例如0/0
注: 在使用预定义常数之前加%,如下图。
【例2-2】简单矩阵的输入和运算。
0
0.04
0.16
0.36
0.64
1.
Scilab常用的基本数学函数
abs(x): 纯量的绝对值或向量的模 sqrt(x):开平方 fix(x): 求实数x的整数部分 modulo(x,y):求x除以y余数 round(x):四舍五入至最近整数 floor(x):不超过x的最大整数 sign(x): 符号函数 当x<0时,sign(x)=-1; 当x=0时,sign(x)=0; 当x>0时,sign(x)=1。 exp(x):自然指数 log(x):以e为底的对数,即自然对数 log2(x):以2为底的对数 log10(x):以10为底的对数 sin(x): 正弦函数 cos(x):余弦函数 tan(x):正切函数 asin(x):反正弦函数 acos(x):反余弦函数 atan(x):反正切函数

scilab中文帮助手册

scilab中文帮助手册

(1)程序设计programming:abort: 中断计算说明:abort命令中断当前计算并给出Scilab的提示符(“-->”)。

如果用户使用pause命令进入高层界面,可使用abort命令回到初始层界面,出现Scilab的提示符(“-->”)。

Ans: 计算结果说明:如果表达式的值没有被赋与任何变量,那么Scilab自动产生一个变量Ans,用来存储当前表达式的值。

backslash (\):矩阵左除调用格式:如x=A\b说明:backslash (\)代表矩阵左除,x=A\b是方程A*x=b的解。

如果A是一个方阵或者可逆矩阵(nonsingular或者invertible),那么x=A\b是方程A*x=b 的唯一确定的解,且等于x=inv(A)*b.(通俗的说,就是方程数目等于未知数个数,所以解唯一。

如A=[1 2 1;3 2 2;2 3 1],b=[8;13;11])如果A不是一个方阵,那么x是最小二乘解,此时,该解x使norm(A*x-b)最小。

(通俗的说,就是方程数目不等于未知数个数。

如果方程数目大于未知数个数,本来是没有准确解的,但可以根据最小二乘法原理拟合出最佳解。

如A=rand(3,2);b=[1;1;1]。

此时,由于A不是一个方阵,无法使用inv(A)命令,因此x=A\b等效于x=pinv(A)*b.如果方程数目小于未知数个数,应该有无穷个解,用x=A\b命令得出的解只是其中的一个解,而用pinv(A)*b命令得出的解则比较粗糙,没有用x=A\b命令得出的解精确。

)如果A是一个列满秩矩阵(矩阵的秩等于列数),那么此最小二乘解x=A\b是唯一能使norm(A*x-b)最小的解。

如果A不是一个列满秩矩阵,那么此最小二乘解x=A\b不能使norm(A*x-b)最小,使norm(A*x-b)最小的解应该是x=pinv(A)*b)。

inv(A)要求A是方阵,pinv(A)则不要求A是方阵bool2s :将布尔矩阵转化为0、1矩阵调用格式:bool2s(x)参数:x是一个布尔向量或者布尔矩阵或者常数矩阵。

scilab 使用教程

scilab 使用教程

2.11 表类型 2.11.1 表类型的定义 可用list,tlist和mlist三个函数创建表变量。 表中的元素可以是任何类型的,例如 s=list(‘shanghai’,13, %f,[1,5]); definedfields()返回表中已定义元素的标号; 2.11.2 表类型数据的引用,域的插入与删除 使用 x(0) 在表x的表头插入数据; 使用 x(i) 删除表x中的第i个元素; 使用getfield()可以抽取表中的元素; 使用setfield()可以在表中插入元素; 2.11.3 tlist和mlist类型 tlist和mlist采用域来定义表;例如: mlist类型表中的元素不可以索引来访问存储的对象。 ((2)得到name的第二个元素b)
3.5.3 局部变量与全局变量、函数的嵌套定义与递归调用 使用global 定义全局变量。 在scilab中,可以嵌套定义函数,例如:
在scilab中函数还可以递归调用,例如
3.5.4 有关程序调试的几个常用指令 pause, resume, abort
第4章 计算结果可视化
4.1 引言 4.2 二维图形的绘制 4.2.1 plot指令 1、plot指令可以用來绘制一般的曲线图。 例如(对sin函数绘图): t=linspace(0,2*%pi); //取0到2π的范围 y=sin(t); plot(y); 2、多重曲线绘图,例子: x=-2:0.01:2; y1=sin(x); y2=exp(x); y3=sin(x)+cos(x); X=[x;x;x]; Y=[y1,y2,y3]; plot(X',Y');
2.10 多项式类型 2.10.1 多项式的定义 1、直接定义 s=poly(1(q中的s用s-1代入),’ x(变量名字)’) ;q=1+3*s^4; 2、用根定义 p=poly([1,3],’x’); 3、用系数定义 p1=poly([1,2,4],’x’,’c’); 2.10.2 多项式运算 有加(+)、减(-)、乘(*)、除(/)运算。 2.10.3 有关多项式的几个常用函数 coeff 取多项式系数 pdiv 求多项式的商和余式 denom 取多项式的分母 numer 取多项式的分子 roots 求多项式的根 horner(p,str) 用str代替多项式p中的变量 derivat 求多项式的导数

《讲Scilab基本操作》课件

《讲Scilab基本操作》课件
《讲Scilab基本操作》PPT 课件
通过这个PPT课件,我们将学习Scilab的基本操作,让你在科学计算方面快速 上手。准备好探索Scilab的世界吧!
一、Scilab的介绍
Scilab的概述
了解Scilab是一个开源的数 值计算和数据分析软件, 适用于工程学、科学研究 和教育领域。
Scilab的特点
探讨Scilab在不同领域的应用 前景,如工程学、科学研究 和数据分析。
Scilab的学习建议和 总结
提供学习Scilab的建议和总结, 帮助大家更好地掌握Scilab的 基本操作。
Scilab的数据分析与拟 合
掌握如何使用Scilab进行数 据分析和曲线拟合,以从 数据中获得有用信息。
Scilab与其他编程语言 的集成
了解如何将Scilab与其他编 程语言集成,从ቤተ መጻሕፍቲ ባይዱ扩展其 功能和应用领域。
五、Scilab常见问题解答
1 Scilab的常见错误及解决方法
指导解决常见的Scilab错误,如语法问题、函数调用和脚本调试。
2 Scilab的优化与调试技巧
分享Scilab的性能优化和调试技巧,确保代码的正确性和效率。
3 Scilab的相关资源推荐
为学习Scilab提供相关资源推荐,如文档、教程和论坛。
结束语
Scilab的未来发展
展望Scilab的未来发展方向, 包括新功能、性能改进和社 区贡献。
Scilab的应用前景
掌握Scilab的特性,如多维 数组、函数库、图形显示 和内置编辑器等。
Scilab的优势
了解为什么Scilab是一种强 大的工具,可以用于解决 复杂的数学和工程问题。
二、Scilab的安装与环境配置

Scilab 教学

Scilab 教学

• for i=初值:终值 • While 表达式
切记:循环条件可以与循环体写 在一行,但需在中间加逗号。
总结+技巧
• 循环体结尾必有“end” • 代码的可读性很重要(主要是因为有些句子后并没有;使得代码 在不分层情况下很恶心)
• 最好一行一行写,不要贪图省行数 • 同一层的代码缩进同样的格数
1.2.3 实际运用
eg1
• 小明很喜欢算数。有一天,小亮告诉他了一个数N(N>100且为 整数),小明将从1~n中的所有数加和,并满足:若n是2的倍数 便直接加,若除以2余1则先乘以(n-1)/2再相加,; • 求最后的和。 • 画框图,写代码
n=input("input n-->"); s=0; for i=1:1:n if i/2==0 s=s+i; else s=i*(i-1)/2; end end print(%io(2),s);
1.2 基本算法语句
----Scilab的使用
Scilab?
• 一个数学计算软件 • Scilab==science + lab
认识scilab
• 优越性:
• 专门进行数学计算 • 开源 免费
1.2.1 三种基本语句
赋值语句
• = 一个等号 • 复制的顺序:右边覆盖左边,无论右边是否包含自己
• 关于赋值:一步步来,不行在纸上写写试试
1.2.2 条件&循环
条件语句if
• if a<0 • else
• print(%io(2),a); • print(%io(2),-a);
• end
循环语句
• for i=初值:步长:终值
• 循环体; • end • 循环体; • end • 循环体; • end

附录2 Scilab特殊矩阵赋值和字符串操作

附录2  Scilab特殊矩阵赋值和字符串操作

特殊矩阵赋值和字符串操作一.行、列向量赋值(1) 矩阵转置-->a=[1,2;3,4];-->a'ans =1. 3.2. 4.(2) 矩阵合并-->x1=[1,2;3,4];-->x2=[9,8;7,6];-->x=[x1,x2]x =1. 2. 9. 8.3. 4. 7. 6.-->y=[x1;x2]y =1. 2.3. 4.9. 8.7. 6.(3)-->a=[1,2;3,4]a =1. 2.3. 4.-->b=a(1,:) //得到矩阵a的第一行b =1. 2.-->b=a(:,2) //得到矩阵a的第二列b =2.4.(4)-->a=[1,2;3,4];-->b=[5,6;7,8]b =5. 6.7. 8.-->a(1,:)=b(1,:)//将矩阵a的第一行替换为矩阵b的第一行a =5. 6.3. 4.-->a(:,2)=b(:,2)//将矩阵a的第2列替换为矩阵b的第2列a =5. 6.3. 8.(5)-->a=[1,2,3;4,5,6;7,8,9]a =1. 2. 3.4. 5. 6.7. 8. 9.-->b=a(2:3,:)//得到矩阵a的第2行和第3行b =4. 5. 6.7. 8. 9.二.字符串操作(1) 字符串连接-->s ="aaa"+"bbb" //Scilab中的字符串可以直接运算 s =aaabbb-->strcat(['aaa','bbb'])ans =aaabbb-->strcat(string(1:10),',')ans =1,2,3,4,5,6,7,8,9,10(2) 字符串查找 i=strindex(str1,str2)-->i=strindex("abcdef","bc")i =2.(3)大小写转换-->s = convstr("abc",'u') //小写变大写s =ABC-->s = convstr("ABC",'l') //大写变小写s =abc(4)字符串替换-->strsubst('abcdef','bc','00')ans =a00def(5)字符串长度 length-->n=length('abcdefg')n =7.(6)字符串转换 string-->a=string(12) //此时a是字符串变量a =12-->a+'23'ans =1223-->str="今年是"+string(2008)+"年"str =今年是2008年(7) 将SCILAB数码转换为字符串 code2str -->code2str(12)ans =c(8) 将字符串转换为SCILAB数码 str2code -->str2code("12yn89")ans =1.2.34.23.8.9。

scilab 画函数

scilab 画函数

在Scilab中绘制函数图像的步骤如下:
以下是一个基本的例子,我们将绘制函数y = x^2 的图像:
1. 首先,打开Scilab并创建一个新的脚本文件。

2. 在脚本文件中,首先定义你要绘制的函数。

例如,我们定义函数y = x^2:
scilab代码:
3. 接下来,定义x的取值范围,并计算对应的y值。

例如,我们将x从-10到10,每隔0.1取一个点:
scilab代码:
4. 使用plot2d函数绘制图像:
scilab代码:
5. 如果你想改变线的颜色、样式或者添加网格线,可以使用以下选项:
scilab代码:
6. 运行脚本(可以通过点击菜单栏的“执行”按钮或者直接在命令窗口输入脚本名后按回车键),你将在图形窗口看到所绘制的函数图像。

注意:以上代码适用于Scilab的较新版本。

在不同版本的Scilab中,绘图函数的参数可能会有所不同。

如果你遇到问题,建议查阅Scilab的官方文档或在线帮助。

scilab-使用教程

scilab-使用教程

与MATLAB的互操作性
01
SCILAB可以与MATLAB进行互 操作,允许用户在SCILAB中调 用MATLAB函数或编辑器中的 脚本。
02
互操作性可以通过MATLAB Engine API for Scilab实现, 该API提供了与MATLAB的接 口,以便在SCILAB中执行 MATLAB代码。
图像处理
SCILAB提供了图像处理和分析的功能,可以用 于图像处理和计算机视觉等领域。
ABCD
工程仿真
SCILAB可以用于工程设计和仿真的数值计算和 分析,如流体动力学、结构力学等。
系统控制
SCILAB可以用于控制系统设计和分析,如控制 系统仿真和优化等。
02 SCILAB基础操作
启动与退出SCILAB
易用性
SCILAB的用户界面友好,易于学 习和使用,支持多种编程语言接 口,方便用户进行编程和开发。
开放性
SCILAB是开源软件,用户可以自 由获取和使用源代码,并根据自 己的需求进行定制和开发。
SCILAB的应用领域
科学计算
SCILAB广阵元素
使用单引号或双引号将元素索引括起来,例如 `A(1,1)`或`A"[1,1]"`。
矩阵运算
支持常见的矩阵运算,如加法、减法、乘法 等。
03 SCILAB编程基础
控制流语句
顺序执行
SCILAB中的代码按照从上到下的顺序 执行,无需使用特定的控制流语句。
循环语句
使用`for`循环重复执行特定代码块, 例如`for i=1:10, statements, endfor`。
初值条件
求解常微分方程时需要指定初值条件,可以使用"="指定初值。例如, y(t0)=y0将指定在t0时刻的初值。

scilab中文手册

scilab中文手册

. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
2 Scilab 簡易教學 2.1 啟動 . . . . . . . . . . . . . . . . . . . . 2.2 編輯 . . . . . . . . . . . . . . . . . . . . 2.3 變數宣告、分行、多行連結及註解 . . 2.4 計算環境、系統變數、常數及特殊變數 2.5 矩陣數內容的設定及讀取 . . . . . . . . 2.6 函數呼叫 . . . . . . . . . . . . . . . . . 2.7 使用多項式 . . . . . . . . . . . . . . . . 2.8 多項式矩陣及行列式之符號運算 . . . . 2.9 分式多項式矩陣及其分子及分母多項式 2.10 計算環境之層次 . . . . . . . . . . . . . 2.11 頻率響應及繪圖 . . . . . . . . . . . . . 2.12 合成函數 . . . . . . . . . . . . . . . . . 2.13 動態系統、狀態空間及轉換函數 . . . . 2.14 狀態空間資料的詳細內容 . . . . . . . . 2.15 動態子系統之並聯 . . . . . . . . . . . . 2.16 設計 Scilab 函數 . . . . . . . . . . . . . 2.17 補償器設計範例 . . . . . . . . . . . . . 2.18 執行系統指令 . . . . . . . . . . . . . . 2.19 以 Fortran 或 C 語言提供動態程式庫 . . 2.20 常微分方程組應用範例 . . . . . . . . . 2.21 運算子設計 . . . . . . . . . . . . . . . . 2.22 函數參數的傳遞 . . . . . . . . . . . . . 3 操作環境 3.1 輸入輸出及環境 . . . . . 3.1.1 環境 . . . . . . . 3.1.2 Scilab 之啟動指令 3.1.3 輸入及輸出 . . .

必修3scilab程序

必修3scilab程序

第二个:自然常数 e 的计算(输入一个正整数,输出自然常数 e 的运算值)
n=input('please input a number'); i=1; s=1; t=1; while i<n|i==n s=s+1/t; i=i+1; t=t*i; End disp('s'); disp(s);
第三个:把 k 进制化成十进制
第七个:更相减损术
a=input('please input number a='); b=input('please input number b='); t=1;m=1; if a<b then t=a; a=b; b=t; End while m~=0 m=a-b; a=m; if a<b then t=a; a=b; b=t; End end disp('the highest common factor is'); disp(a);
第十个:秦九Biblioteka 算法n=input('the biggest power number is'); i=1; x=input('x=:'); a=input('first number is :'); b=input('second number is'); u=a*x+b while i<n v=input('next is '); u=u*x+v; i=i+1; End disp(u);
第九个:十进制化 k 进制
n=input('please input a usual number:'); k=input('please input the key number:');

scilab code generation 教程

scilab code generation 教程

Scicos Code GenerationScicos teamDecember11,2009Contents1Introduction21.1Background (2)1.2Scicos Overview (3)1.3Functional approach (4)1.4Code generation implementation (4)2Use of code generation72.1Inside the editor (7)2.1.1Default properties definition (7)2.1.2Use of the main GUI (8)2.2Use and definition of external libraries and additional compilerflag(s) (9)2.3List of the main generatedfiles (10)2.4Code generation from the ScicosLab prompt (10)2.5Use of the ScicosLab interfacing function for the standalone (11)2.6Use the loader script to reload the generated codes inside Scicos/ScicosLab (12)2.7Standalone executable (12)2.7.1Compilation (12)2.7.2Sensors/Actuators (13)2.7.3Standalone options (14)2.7.4The calling sequence of the standalone simulation function (15)2.7.5The calling sequence of the generic interfaces for actuator/sensor (16)2.7.6The structure of the parametersfile (17)List of Figures1A Scicos block diagram (3)2Flowchart Scicos implementation (4)3Flowchart:Functional approach (5)4Flowchart:code generation implementation (6)5The diagram GUI of the code generation (7)6The main GUI of the code generation (8)7GUI asking to the user to change the name of the generated codes (8)8GUI asking to the user to rewritte the Actuator/sensor routines (9)9The structure of the parametersfile (17)List of Tables1List of the main generatedfiles (10)1Introduction1.1BackgroundScicos is a modeler/simulator of hybrid dynamical systems.It can simulate a wide variety of systems,including in a same process of simulation,discrete and continuous time dynamics.Scicos can solve non-linear differential equations described by Ordinary Differential Equations(ODE),Differen-tial Algebraic Equations(DAE)and Discrete Difference Equations.With Scicos one can model hybrid dynamical systems by using block diagram schematics and/or by using the modelling language Modelica.In both cases the user can generate C code from the model description.An hybrid dynamical system can be described by separating the continuous time from the discrete time dynamics. For a system using ODEs,we can write the continuous time part as:y(t)=f(t,x(t),z(t k),u(t),p)(1)˙x(t)=h(t,x(t),z(t k),u(t),p)(2)where t is the continuous time,y(t)is a vector of outputs,u(t)is a vector of inputs,x(t)is a vector of states,˙x(t)is the vector of the derivative states,z(t k)is a vector of discrete states and p a vector of constant parameters.f and h are functions that define non-linear relation between variables.For a system using DAEs,we can write the continuous time part as:0=f(t,y(t),x(t),z(t k),u(t),p)(3)˙x(t)=h(t,x(t),z(t k),u(t),p)(4)where(3)defines algebraic relations.For the discrete time part,one can write:y(t k)=f(t k,x(t k),z(t k),u(t k),p)(5)x t+ =g c(t k,x(t k),z(t k),u(t k),p)(6)z(t k+1)=g d(t k,x(t k),z(t k),u(t k),p)(7)where t k is the discrete time,g c and g d are respectively functions for the states vector and the discrete states vector. Note that here have written x(t+)instead of x(t k+1)for(6)because we assume that a discrete jump occurs during the continuous time integration of the state vector.In a Scicos simulation,the delay between two discrete instants t k+1and t k is not necessary constant.Such instants are called output events date and are computed by primary sources of activation.These sources are defined by:t k+1=k(t k,x(t k),z(t k),u(t k),p)(8)and can also be defined with a continuous time equation by using zeros crossing threshold related to continuous time states or inputs:t k+1=inf{t>t k such that0=g z(t,x(t),z(t k),u(t),p)}(9)1.2Scicos OverviewIn Scicos,hybrid dynamical systems defined by the previous equations,can be modeled by a block diagram graphic editor:Figure1:A Scicos block diagramThis diagram models the Lorentz’s system defined by the following set of equations:˙x(t)=a(−x(t)+y(t))(10)˙y(t)=bx(t)−y(t)−x(t)y(t)(11)˙z(t)=−cx(t)+x(t)y(t)(12) To simulate the dynamical system,the diagram(or its Modelica description if this high level language is used)must be compiled to translate the symbolic description in a compiled structure(or tree)that can be used both by a simulator and a code generator.In the current Scicos version,the followingflowchart shows a top-down view of the main parts of the mod-eler/simulator:•The output of the editor is a structure that corresponds to the hierarchical main diagram.It contains informations related to graphical objects(e.g.blocks,links,...)appearing in thefigure.Additional informations are set in that structure such that simulation parameters,code generation properties,etc...•Afirst step of the compiling process realizes aflat diagram structure.In the hierarchical representation of the Scicos editor some blocks(called super block)are allowed to contain other diagram structure.During that step, all graphical informations not needed for simulation are removed from the output structure.•Then a second pass in the compiler realizes the scheduling of blocks in theflat diagram.The output compiled structure have all informations needed for the simulation.1.3Functional approachA more detailedflowchart of the Scicos hybrid dynamical systems toolbox is shown infigure3.•In the left part is shown how the Scicos code generation interacts with the compiler and the simulator.With the informations provided by the compiler,two codes are generated:◦one is a computational function.This code can directly be called by the simulator.That code callsthe Standard/user’s blocks computational functions and/or the computational function provided by theScicos/Modelica implementation.◦the second code is called standalone code.It is a code which includes both the calls to the Standard/user’sblocks computational functions(and/or the computational function provided by the Scicos/Modelica im-plementation)and simulator parts needed to achieve the simulation.1.4Code generation implementationFigure4displays the current Scicos code generation implementation.Computational function Interfacing function MODELICA IMPLEMENTATION SCICOS STANDARD/USER’S BLOCKSF i g u r e 3:F l o w c h a r t :F u n c t i o n a l a p p r o a c h5Figure4:Flowchart:codegenerationimplementation 62Use of code generation2.1Inside the editorIn the editor,the C code generation can be achievied through a super-block or an complete top-level diagram.The various steps of code generation are not visible by the user.Finally,the generated codes are automatically compiled and dynamically linked inside Scicos and ScicosLab.2.1.1Default properties definitionDescriptionBefore running the code generation process,the user can set some parameters that will overload the default properties of the generation.That parameters can be set with a GUI which appears in the Scicos menu’Diagram’,option’Set Code Gen Properties’or with the context menu(also called Popup Menu)when user right click on a super-block and use the menu’Super Block Properties’.Dialog boxFigure5:The diagram GUI of the code generation•Silent mode(0:no,1:yes):If set to1,this parameter means that no GUI will be displayed during the code generation processes.This is useful when running code generation in batch mode.•Use CBLOCK4(0:no,1:yes):This parameter enables the use of a generic type4C block for the generation of the Scicos interfacing function associated with the newly created block.•Target name([]means default):By default,a name is given for the generated code according to the title of the diagram or the title of the super-block.This dialog parameter overload the default name chosen by the code generation.•Target path([]means default):By default,a name is chosen for the target path of the generated code, according to the title of the diagram or the title of the super-block.This dialog parameter overload the default path chosen by the code generator.This is useful for example to set it at’TMPDIR’when doing a long sequence of tests.•External libraries([]means default):With that parameter,the user can affect external libraries for a diagram or for a super-block.This parameter doesn’t remove the external libraries set by the global Scicos variable %scicos_libs.•Standalone generation(0:no,1:yes):One can disable the standalone code generation with that parameters.•Enable debug(0:no,1:yes):That parameters is for use only by experts.If set to1,additionnal code is generated in the computational function and in the standalone code for the debugging purpose.2.1.2Use of the main GUIDescriptionIn the Scicos editor,the code generation begins by choosing the’Code Generation’item in the Scicos menu’Tools’and then by clicking in a void area(for an entire diagram generation)or by cliking on a super-block.The user canalsofirst select the super-block that must be generated and then use the popup Menu(mouse right click)and choosethe option’Code Generation’.Then a dialog box appears,asking the user to set some parameters concerning the code generation.Most of that parameters are default values or values set in the diagram GUI.Dialog boxFigure6:The main GUI of the code generation•New block’s name:That parameter is a string which defines the new name of the Scicos block that will begenerated inside the ScicosLab environment.It will serve as a main identifier concerning names given for thegenerated functions andfiles.For example,if we choose to name our block’Rdnom’:◦The Scicos interfacing function will be called’Rdnom_c’and its associatedfile’Rdnom_c.sci’,◦the type4computational function will be called’Rdnom’and its associatedfile’Rdnom.c’,◦the simulation function of the standalone code will have the name’Rdnom_sim’and itsfile’Rdnom_standalone.c’,◦the ScicosLab interfacing function of the Standalone will be called’Rdnom’and its associatedfile’intRd-nom_sci.c’,◦the Makefiles will have the names’Makefile_Rdnom(.lcc/.mak)’and’Makefile_intRdnom(.lcc/.mak)’torespectively compile the computational function/standalone code and the ScicosLab interfacing function,◦the loader script that reload generated functions in the ScicosLab environment will be called’Rdnom_loader.sce’,◦and etc...Note that some restrictions still exist concerning the name of the block:◦The name cannot contains space,the“.”character and the“-”character.If such characters are used,thenthe main GUI will substitute them by the underscore character(“_”)and a message will be displayed toask to the user to change the new name if needed.◦If a computational function with a the same name have already been dynamically linked in the ScicosLabenvironment,then the GUI displays the following message for the user:Figure7:GUI asking to the user to change the name of the generated codes∗Change block name:For thefirst choice,the GUI will automatically rename the block’name byadding a’x’character to the end of the characters string,with’x’an increasing number correspondingto the number of time taht the block have been generated or dynamically linked into ScicosLab.Theuser will have the choice to rename it if needed.∗Force unlink:that button allows to unlink the previous computational function from ScicosLab.Thenew will then replace it.•Createdfiles path:that parameter gives the target path.In that path,thefiles will be generated and compiled.If that path doesn’t exist,the code generator will created it.If it can’t,a message will be displayed to the user and the generation will stop.Note that some restrictions still exist concerning the name of the path:◦The name can’t contains space character.If a space is used,then the main GUI will substitute it by theunderscore character(“_”)and a message will be displayed to ask to the user to change the new path ifneeded.•Otherfiles to link with(if any):that parameter is a character string row vector.It is used to spectify the paths and names of additionnal external libraries.That libraries enclose compiled user’s computational functions and other functions needed to compile and link the standalone generated code.For each library,a static and a shared version are needed.The shared library is for the dynamical link into ScicosLab,and the static is to compile the standalone executable.The libraries must havefile extensions".dll"for the windows operating systems(OS),and".so"for the Linux OS.The generator will then automatically look at for static libraries withfile extensions".lib"for Windows OSs and".a"for Linux OS.If that lastestfiles are not found,the GUI send a message to the user and the generation is aborted.•Additional compilerflag(s):this parameter defines an additional option for the C compiler.This can be useful for specifying a directory to include(needed for headerfile)and/or to include libraries(like’-lstdc++’under Linux OS).When the user has informed all the GUI parameters,he accepts by click in the’Ok’button,or by pressing the key’En-ter’.But sometimes,the generation or the compilation processes will fail.In such cases error or warning messages are send to the user.The most encountered warning in the Scicos code generation is when the user generates code over an already generated block(with same name and same target path).In that case,the following dialog box appears and ask to the user if thefile for the actuators/sensors routines’Rdnom_act_sens_events.c’must be erased.Figure8:GUI asking to the user to rewritte the Actuator/sensor routines2.2Use and definition of external libraries and additional compilerflag(s)The use of thefield entries’Otherfiles to link with(if any)’and’Additional compilerflag(s)’in the main GUI of the code generation can be sometimes difficult and boring when the diagram is composed of lot of user’s blocks that need many external libraries.In Scicos,the global variable%scicos_libs can be used to inform external libraries from the ScicosLab prompt just before launching the Scicos editor.The global variable%scicos_cflags is used as a compilerflag.Typically it can be used in a’loader.sce’scriptfile that is in charge of loading user’s function like interfacing functions and computational functions.An example of use of such a script is given below:099...0100if MSDOS then0101libnam=[’mylib1.dll’,’mylib2.dll’]0102else0103libnam=[’mylib1.so’,’mylib2.so’]0104end01050106if%scicos_libs<>[]then0107for i=1:size(libnam,2)0108if find(libnam(i)==%scicos_libs)==[]then0109%scicos_libs=[%scicos_libs,libnam(i)]0110end0111end0112else0113%scicos_libs=libnam0114end01150116if~MSDOS then%scicos_cflags=[%scicos_cflags,’-lstdc++’];end0117...When this variables are informed,the code generator of Scicos will automatically use it during the link and compile processes.The dialog parameter’Otherfiles to link with(if any)’of the main GUI will be then set with the contents of %scicos_libs and the dialog parameter’Additional compilerflag(s)’with the content of the variable%scicos_cflags. Finally,one can say that when the user generates a new block with the code generation,then the output library of the new block will be automatically added at the end of the%scicos_libs content.That behaviour is for users that use the generated block inside other blocks or diagram to be generated.2.3List of the main generatedfilesFilesScicos computational functionScicos interfacing functionStandalone codeActuators/sensors routines(shell/files)Actuators/sensors routines(generic C structure)Parameters standalonefile(“little endian binary”)ScicosLab/standalone interfacing functionMakefile for the computational function and the standalone codesMakefile for the ScicosLab/standalone interfacing functionScicosLab script to reload the generated code inside ScicosLabTable1:List of the main generatedfiles2.4Code generation from the ScicosLab promptDescriptionThe code generation of an entire diagram can be done without running the Scicos editor.This feature can be automat-ically realized with the ScicosLab macro scicos_codegeneration from the Scicoslab prompt.Before use this function the desired diagram must be loaded into ScicosLab,for example by using the’load’command for a diagram included in a’.cos’file.After the generation,the resulting diagram can be loaded in scicos with->scicos(scs_m);. Default parameters for code generation can be set with the help of the’Params’argument.Calling Sequence[ok,scs_m,%cpr]=scicos_codegeneration(scs_m,Params)Parameters•scs_m:Scicos diagram(obtained,e.g.,by’loadfile.cos’).•Params:A list of properties for scicos code generation.◦Params(1):silent_mode:if1then no message are displayed during the code generation and defaultvalues are taken for the target directory and names.◦Params(2):cblock:if set to1,the generated block is replaced by a CBLOCK4that enclosed the genericparameters and the generated computational function.◦Params(3):rdnom:sets the default name for the generated code.◦Params(4):rpat:sets the default target path for the generated code.◦Params(5):libs:sets the additional external libraries needed by code generation.◦Params(6):opt:if0,then the standalone code will not be generated-default1-.◦Params(7):enable_debug:says if additionnal code must be generated to debug generated codes.•ok:Flag to say if the code generation is successfull.•scs_m:The resulting diagram,that contains the generated block if any.•%cpr:The resulting compiled structure.2.5Use of the ScicosLab interfacing function for the standaloneThe code generation of Scicos generates both a computational function and a standalone code.In the generation process,when the user choose to generate the standalone code,it is automatically compiled and dynamically linked in the ScicosLab environment.Then the standalone code can be used by the way of a ScicosLab interfacing function which is also generated,compiled and dynamically linked in the same time than the standalone code.The ScicosLab interfacing function is a C function and is automatically added to the list of the ScicosLab functions with the help of the function addinter.For a generated code called’Rdnom’,such a function will have the following calling sequence in ScicosLab for an entire diagram generation:[out1,out2,...,outX]=Rdnom(in1,in2...,inX,[,tf][,fil])with•out1,out2,...,outX:the output signals corresponding to the X actuators.•in1,in2...,inX:the input vector or matrix corresponding to the X sensors.•tf:thefinal time of the simulation(optional).•file:the path and name of the binary datafile that contains the parameters and initial states values(optional).and the following calling sequence for a super-block code generation:[out1,out2,...,outX]=Rdnom(in1,in2...,inX,[,te][,tf][,h][,solver])with•out1,out2,...,outX:the output signals corresponding to the X actuators.•in1,in2...,inX:the input vector or matrix corresponding to the X sensors.•te:the sampling time(optional,default0.1).•tf:thefinal time of the simulation(optional,default30).•h:solver step(optional,default0.001).•solver:solver type,1:Euler,2:Heun,3:R.Kutta(optional,default3).The output signals are scilab structures composed by twofields:time and values.After have running the interfac-ing function,on can compute,e.g.,an output signal:-->out1=Discrete_KalmanFilter()out1=values:[15000x3constant]time:[15000x1constant]Thefield values contains the data stored during the simulation.If input/output signals are scalar,then the size of the valuefield will be[nx1]with n the n calls for the sensor/actuator.If the input/output signals are vector of size m,then the size for values will be[nxm].The size for time is always[nx1].For each rows,the event dates of the call are recorded.To extract or enclose data from or in signal structure one can use the scilab functions sig2data or data2sig.Note that for the time being,inputs are not considered like signals structure.The in1,in2...,inX variables can only be set with vectors(for scalar sensors)or with matrices(for vectorial sensors).The number of rows for the input correspond to the number of call of the sensor routines.If the number of calls are more that the number of rows, then the generic routine for sensor stops the reading at the last row.When the ScicosLab interfacing function of the standalone code is launched,all the simulation is running from the time0to the time tf.The value of thefinal simulation time is in fact written in the default binary datafile,but it can be overloaded by the use of the optional right hand side argument tf.For the entire diagram generation case,the default parameters datafile is normally in the path where codes have been generated.Thisfile is named,for example,’Rdnom_params.dat’and is written in binary little endian format. The lastest optional right hand side argument fil allows to specify another path and name for that parametersfile.2.6Use the loader script to reload the generated codes inside Scicos/ScicosLabThe code generation of Scicos generates a ScicosLab loader.sce script that can be used to reload the generated codes in another ScicosLab session.The script is generated in the default path where the codes have been generated and is named,for a block called’Rdnom’,Rdnom_loader.sce.This script successively:•informs the%scicos_libs variable with the library that contains the comptutational function of the generated block,•compiles and links the library that contains the computational function and the standalone code in the ScicosLab environment,•loads the Scicos interfacing function of the generated block in ScicosLab with the ScicosLab function getf,•compiles and links library that contains the ScicosLab interfacing function of the standalone code in ScicosLab.Then after running this script from the ScicosLab prompt with the exec command,with,e.g.,the command: ->exec(’Rdnom_loader.sce’);,the new generated Scicos block can be added to a diagram by the help of the item Add new block in the menu Edit of the Scicos editor,and the standalone simulation function can be run from the ScicosLab prompt with the ScicosLab interfacing function calling sequence.2.7Standalone executable2.7.1CompilationWhen generating the codes,the standalone can be compiled as an executable.This executable can be run in a shell and the compilation is possible via Makefiles generated in the target path.This Makefiles are called,for example, Makefile_Rdnom for a Linux OS and Makefile_Rdnom.mak for a Windows OS.Under Linux OS,the standalone executable can be obtained with the following command line:alan@fiboue:~/scicoslab/Rdnom$make-f Makefile_Rdnom standaloneand under Windows OS,c:\scicoslab\Rdnom>nmake/f Makefile_Rdnom standaloneNote that to run the standalone in Windows OS,the standard ScicosLab libraries(dlls in the SCI/bin directory)and the external libraries defined by the user must be avialable in the path where the standalone executable is called.The standalone executable is always called standalone(or standalone.exe for Windows).When it is called without argument,the standalone simulation is run and interacts with the shell concerning data of actua-tors/sensors.2.7.2Sensors/ActuatorsWhen sensors are called,the shell prompts the user to enter data with keyboard as follows:Require outputs of sensor number1time is:0.000000sizes of the sensor output is:1,1type of the sensor output is:10(double)Please set the sensor output valuesy(0,0):If the sensors are for vector or matrix then each element must be typed.For the actuators,the data are displayed during the simulation,as follows:Actuator:time=0.000000,u(0,0)of actuator1is-0.878222Actuator:time=0.000000,u(1,0)of actuator1is-0.702345Actuator:time=0.000000,u(2,0)of actuator1is-0.783668Actuator:time=0.001000,u(0,0)of actuator1is-0.878222Actuator:time=0.001000,u(1,0)of actuator1is-0.702345Actuator:time=0.001000,u(2,0)of actuator1is-0.783668The subroutines that correspond to the sensor/actuator are in thefile called Rdnom_act_sens_events.c.For actuators,the routine is called Rdnom_actuator and for sensors,the routine is called Rdnom_sensor.That subroutines are considered like generic routines and the user of the standalone executable can easily modify it.The calling sequence of the Rdnom_actuator is:void Rdnom_actuator(flag,nport,nevprt,t,u,nu1,nu2,ut,typout,outptr) /**To be customized for standalone execution*flag:specifies the action to be done*nport:specifies the index of the super-block*regular input(The input ports are numbered*from the top to the bottom)*nevprt:indicates if an activation had been received*0=no activation*1=activation*t:the current time value*u:the vector inputs value*nu1:the input size1*nu2:the input size2*ut:the input type*typout:learn mode(0from terminal,1from input file)*outptr:pointer to out data*typout=0,outptr not used*typout=1,outptr contains the output file name*/int*flag,*nevprt,*nport;int*nu1,*nu2,*ut;int typout;void*outptr;double*t;void*u;The calling sequence of the Rdnom_sensor is:void Rdnom_sensor(flag,nport,nevprt,t,y,ny1,ny2,yt,typin,inptr) /**To be customized for standalone execution*flag:specifies the action to be done*nport:specifies the index of the super-block*regular input(The input ports are numbered*from the top to the bottom)*nevprt:indicates if an activation had been received*0=no activation*1=activation*t:the current time value*y:the vector outputs value*ny1:the output size1*ny2:the output size2*yt:the output type*typin:learn mode(0from terminal,1from input file)*inptr:pointer to out data*typin=0,inptr not used*typin=1,inptr contains the input file name*/int*flag,*nevprt,*nport;int*ny1,*ny2,*yt;int typin;void*inptr;double*t;void*y;2.7.3Standalone optionsAll of options of the standalone executable can be viewed by using the inline help with the option-h. Options for an entire diagram generationWhen the user has chosen to generate codes for an complete diagram the following options are available: alan@fiboue:~/scicoslab/Rdnom$./standalone-hUsage:./standalone[-h][-v][-i arg][-o arg][-d arg][-t arg] Options:-h for the help-v for printing the Scicos Version-i for input file name,by default is Terminal-o for output file name,by default is Terminal-t for the final time,by default is 1.500000e+01-p for input parameters file name,by default is Rdnom_params.datOptions for a super-block generationWhen the user do a code generation from a super-block,then the following options are available:alan@fiboue:~/scicoslab/Rdnom$./standalone-hUsage:./standalone[-h][-v][-i arg][-o arg][-d arg][-t arg][-e arg][-s arg] Options:-h for the help-v for printing the Scicos Version-i for input file name,by default is Terminal-o for output file name,by default is Terminal-d for the clock period,by default is0.1-t for the final time,by default is30-e for the solvers step size,by default is0.001-s integer parameter for select the numerical solver:1for Euler’s method2for Heun’s method3(default value)for the Fourth-Order Runge-Kutta(RK4)FormulaOptions to use input/outputfiles for sensor/actuatorThe standalone executables can be used with the command line parameters-i and-o to specify input/outputfiles forthe sensors/actuators instead of using the terminal.To specify outputfile(s)for the actuator(s),one can usealan@fiboue:~/scicoslab/Rdnom$./standalone-o out.txtThe data for the actuator(s)will be then recorded infile(s)out_x.txt where x are for the actuator number.The generic routines write it in text format and the contents will be:alan@fiboue:~/scicoslab/Rdnom$cat out_1.txt|more0.000000-0.878222-0.702345-0.7836680.001000-0.878222-0.702345-0.7836680.002000-0.878222-0.702345-0.7836680.003000-0.878222-0.702345-0.7836680.004000-0.878222-0.702345-0.783668....For each row,thefirst column is for the event date when the actuator have been called and the others are for the data. When there is more than two columns,that says that the data are vector or matrix.Thefinal simulation time,that is enclosed in the parameters datafiles,can be overloaded by using the-t option,and the path and name of the parametersfile can be specified with the-p option.2.7.4The calling sequence of the standalone simulation functionIn the standalone code,a function named’Rdnom_sim’is the entry point for the simulation function.It can be calledand interfaced with external routines.In the main function of the standalonefile’Rdnom_standalone.c’and in the ScicosLab interfacing functionfile’intRdnom_sci.c’,the standalone simulation function is called like that:ierr=Rdnom_sim(params,typin,inptr,typout,outptr);Thefirst argument is a structure with the following definition:typedef struct{char*filen;double tf;}params_struct;•filen is for thefile name of the parameters datafile and tf is for thefinal simulation time.。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Writing Scilab ExtensionsMicha¨e l BaudinDecember2012AbstractIn this document,we present methods to use and create Scilab extensions.In thefirst part,we focus on the use of external modules.We describe their general organization and how to install a module from ATOMS.Thenwe describe how to build a module from the sources.In the second part,wepresent the management of a toolbox,and the purpose of each directory.Weemphasize the use of simple methods to automatically create the help pagesand to manage the unit tests.Then we present the creation of interfaces,which allows to connect Scilab to a compiled C,C++or Fortran library.We consider the example of a simple function in the C language and exploreseveral ways to make this function available to Scilab.We consider a simplemethod based on exchanging data byfile.We then present a method basedon the call function.Finally,we present the classical,but more advanced,method to create a gateway and how to use the Scilab API.The two lastsections focus on designing issues,such as managing the optional input oroutput arguments or designing examples.Contents1Introduction5 2Extending Scilab capabilities52.1Introduction (5)2.2Types of external modules (6)2.3Using ATOMS (6)2.4The toolbox skeleton (7)2.5A sample module (8)2.6The internal structure of a module (8)2.7Building an external module from the sources (9)2.8Using a module (10)2.9Loading the module automatically (10)2.10Cleaning the module(*) (11)2.11Scilab’s Forge(*) (11)3Managing a module123.1The tbx module (12)3.2The chain of builders (14)3.3The main builder (14)3.4The etc directory (15)3.5The macros directory (18)3.6Creating private functions(*) (19)3.7The help directory (20)3.8Help pages in local languages(*) (23)3.9Advanced help pages(*) (24)3.10Creating help chapters(*) (26)3.11The tests directory (27)3.12Executing the unit tests (28)3.13Advanced unit tests(*) (30)3.14Issues with unit tests (31)3.15The assert module (32)3.16Advanced assert use-cases(*) (35)3.17Generating the help from the macros (37)3.18Using pseudomacros(*) (39)3.19A check-list for the module (39)4Interfaces(*)394.1Overview (40)4.2A sample function (41)4.3With textfiles (41)4.3.1Overview (42)4.3.2Format of the exchangefiles (42)4.3.3Implementation of the C side (43)4.3.4Implementation of the Scilab side (45)4.3.5Debugging (47)4.4With the call function (47)4.4.1The C source code (47)4.4.2Debugging with ilib_for_link (48)4.4.3Using call (50)4.5With a gateway (52)4.5.1Scilab data structures (52)4.5.2The Scilab API (54)4.5.3Analysis of a gateway (54)4.5.4Debugging a gateway (60)4.6A module with gateways (61)4.6.1The src directory (61)4.6.2The src/*subdirectories (62)4.6.3The sci_gateway directory (66)4.6.4The sci_gateway/*subdirectories (67)4.6.5Solving compilation issues (70)5Designing the module725.1Thinking the API (72)5.2Providing backward compatibility (72)5.3Avoid function name conflicts (73)5.4Optional input arguments (74)5.5Provide as many input arguments as reasonable (74)5.6A correct order for optional input arguments (75)5.7A correct order for optional output arguments (76)5.8Argument checking (77)5.9Localization of messages(*) (78)5.10Output messages within functions (78)5.11Orthogonality between modules(*) (79)5.12Do not stay alone:communicate! (81)5.13A check-list for the API (81)6Designing examples826.1Any function has one(or more)example (82)6.2Examples are self-contained (82)6.3Only valid statements (82)6.4Provide scripts,not sessions (83)6.5Let the user see the results (83)6.6A good example (84)6.7A check-list for the examples (84)7Notes and references84 Bibliography85 Index85Copyright c 2012-Michael BaudinThisfile must be used under the terms of the Creative Commons Attribution-ShareAlike3.0Unported License:/licenses/by-sa/3.01IntroductionThis document is an open-source project.The L A T E Xsources are available on the Scilab Forge:/index.php/p/docsciextensions/The L A T E Xsources are provided under the terms of the Creative Commons Attri-bution-ShareAlike3.0Unported License:/licenses/by-sa/3.02Extending Scilab capabilitiesIn this section,we present Scilab external modules,a system which allows to extend considerably the capabilities of Scilab.In thefirst part,we present the basic method to install Scilab modules.In the second part,we present a sample use of the ATOMS component,a packaging system for Scilab.In this document,the sections marked with an asterisk(*)can be considered as optional and can be skipped in afirst reading.2.1IntroductionOne of the most interesting features of Scilab is that we can use and create exten-sions,which behave as built-in functions.The simplicity of creating these extensions has make so that there are hundreds of public extensions publicly available.This wealth of extensions is already a great source of information to create our own mod-ules.In this document,we present the most common methods to create new basic modules and some advanced methods to make the creation easier when a lot of functions are involved,or when a compiled source code is involved.Although the word toolbox has been used in the past,the word module is now employed in the context of Scilab,with two different meanings.•An internal module is a component which is provided by Scilab itself.•An external module is a component which is not provided by Scilab,but can be loaded by Scilab to extend its features.Fortunately,although they are technically a bit different,internal and external mod-ules have a lot in common so that understanding the latter is an excellent introduc-tion to the former.The topics that we present in this document are simple,but relatively advanced, in the sense that many users never have to extend Scilab features because they are happy with the features already provided.Nevertheless,when it comes to extending Scilab features,we have to already master the more regular features that many users already know.We suggest to read the documents[2]and[3]for topics which might be unclear when reading the current document.More precisely,we suggest to fully master the sections2.8”ATOMS,the pack-aging system of Scilab”and the section6”Functions”in[2].This should be a good basis for the section3of the current document.The section4”Management of functions”in[3]should be a consistent help for those searching how to design functions.This should be a good basis for the more advanced topics in the section5of the current document.2.2Types of external modulesA Scilab module is a set of macros,helpfiles and unit tests,which enhance Scilab with new features.Notice that some modules also contain compiled source code(e.g. in the C language),but most modules are only based on macros.External modules are meant to be developed and maintained by Scilab users,but some modules are developed or maintained by the Scilab core development team.Modules can be distinguished on the base of the origin of the features:•modules based only on macros(i.e.functions),•modules based only on compiled source code(i.e.Fortran,C or C++),•modules based both on macros and compiled source code.This difference is critical,since compiling a library requires a compiler(e.g.gcc on Gnu/Linux or Visual Studio on MS Windows).This is generally a non trivial task. In practice,when we get an external module based on compiled source code,it may be difficult to generate a binary version of this module.The ATOMS system has been designed for that purpose,in order to make the installation of external modules an easy process.The ATOMS system is reviewed in the next section.2.3Using ATOMSATOMS is the Scilab tool which allows to search,download,install and load mod-ules.The ATOMS system is available in Scilab since version5.2.The homepage for the ATOMS system is the following:The ATOMS system allows to install and use external modules without the bur-den of compiling the module,a task which is generally difficult and time consuming. Moreover,any external module which is packaged in the ATOMS system is guar-anteed to be loadable in Scilab.We cannot be sure that the functions are bugfree, but,at least,we are sure that the module can be loaded in our current version of Scilab.In this section,we consider the NISP module,which provide functions to perform sensitivity analysis in uncertainty quantification.This is a good example,since the NISP module is based on a C++library:building this module requires a compiler. Fortunately,the NISP module has been packaged in ATOMS:/toolboxes/NISPThe NISP module is available for the following platforms:•Windows32bit,64bit,•Linux32bit,64bit,•Mac OS X.The ATOMS component allows to install and use the NISP module,without having a compiler installed in the system.In the following Scilab session,we use the atomsInstall()function to download and install the binary version of the module corresponding to the current operating system.-->atomsInstall("NISP")ans=!NISP 2.1allusers D:\Programs\SC3623~1\contrib\NISP\2.1I! Then we restart Scilab.At the startup,we see the following messages in the console: Start NISP ToolboxLoad gatewaysLoad helpLoad demosshowing that the module is available.The NISP module has been automatically loaded at the start of the Scilab session.In order to remove the NISP module,we just use the atomsRemove function.More details on ATOMS are available at[11].2.4The toolbox skeletonDeveloping a new module is designed to be as easy as possible.For this purpose,a module skeleton is provided within Scilab,in the SCI/contrib/toolbox_skeleton directory,or in the Git repository:/?p=scilab.git;a=tree;f=scilab/contrib/toolbox_skeletonThis module is made of both macros and compiled source code,and presents several methods required to manage a module.One of the interests of the toolbox skeleton is that it allows to separate what are thefiles which must be edited by the developper,and what are thefiles which are automatically generated by Scilab.Notice that a toolbox skeleton for Xcos blocks is also available at:/toolboxes/xcos_toolbox_skeleton Of course,the toolbox skeleton could be used in this document to present the methods to write Scilab extensions.The difficulty with this skeleton is that it uses compiled sources codes,which is a more advanced topic and is not used by many users.The section4presents the interfaces in Scilab.Hence,we suggest to read the toolbox skeleton as a pratical exercise of this document,but after having practicing the more simple example that we now consider.The next section presents the number module,which will be used in this docu-ment.2.5A sample moduleAn external module must respect standards about its internal organization.In order to describe this organization,we will consider the practical case of the number module.The latest version of this module can be dowloaded at:/toolboxes/numberThe module is developed on the Forge at:/index.php/p/numberIt is easy to download a zipfile containing the sources of the number module at: /index.php/p/number/downloads The number module provides several algorithms which are related to number theory,for example the greatest common divisor or prime factorization.In the following sections,we assume that we have downloaded a source version of the number module,so that we have the associated number.zipfile.The reason why we consider the number module is because it is an example of a module which only uses Scilab macros.Hence,building this module is relatively simple.We now want to make a binary version of this module.Before,analysing the method to do this,we are going to review the internal structure of a module.2.6The internal structure of a moduleIn this section,we analyze the internal organization of an external module.The following list is an overview of the content of the directories.•number/demos:demonstration scripts(.scefiles),•number/etc:startup and shutdown scripts for the module,•number/help:help pages(.xmlfiles),•number/macros:macros(.scifiles),•number/tests:unit and non regression tests.These are all the directories required in the number module.But,if the module,say mytoolbox for example,contains compiled source codes,then we should have the following extra directories.•mytoolbox/sci_gateway:the sources of the gateway(.c or.cppfiles),•mytoolbox/src:the sources of the library(.f,.c or.cppfiles).At the root of the module,the followingfiles are usually located.•number/builder.sce:the script which”builds”the module,•number/changelog.txt:the changes from version to version,•number/licence.txt:the license of the module,•number/readme.txt:the purpose of the module.2.7Building an external module from the sourcesIn this section,we present the process of building a binary version of a module based on its sources.In order to get a binary version of the module,the user mustfirst build it by launching the builder.sce script.-->exec builder.sce;Building macros...--Creation of[numberlib](Macros)--genlib:Processing file:number_startup.scigenlib:Processing file:number_solvelinmod.sci[...]genlib:Processing file:number_bary.scigenlib:Regenerate names and libBuilding help...Building the master document:C:\number\help\en_USBuilding the manual file[javaHelp]in C:\number\help\en_US.(Please wait building...this can take a while)Generating loader.sce...Let us analyse the effects of the building process.•The scripts number/builder.sce and number/loader.sce have been auto-matically generated.•In the number/macros directory,the.binfiles,corresponding to the.scifiles have been created.The builder script has also created the macros/libfile and macros/namesfiles.•In the number/help directory,the builder has created subdirectories con-taining.htmlfiles.The number/help/en_US directory also contains a mas-ter_help.xmlfile,which contains a table of contents of the help pages.•The process has created a number/jar directory,containing a.jarfile.This is a Java archive used to manage the help pages.The number module contains only macros,and this is why the analysis stops here for this module.But,if the module,say mytoolbox,contains compiled source code, then the followingfiles are generated.•The mymodule/sci_gateway/loader_gateway.sce has been generated.The mymodule/sci_gateway subdirectories also contain variousfiles created by the compilation process,including the.so(on GNU/Linux)or.dll(on MS Windows)dynamic libraries.•The mymodule/src directory also contains dynamic libraries created by the compilation process.2.8Using a moduleIn this section,we present how to use a module which has been previously trans-formed into binary form.After we have built the module,the main directory now contains a number/ loader.sce.In order to load the library,we now execute the loader.sce script.-->exec C:\number\loader.sce;Start NumberLoad macrosLoad helpLoad demosType"help number_overview"for quick start.Type"demo_gui()"and search for Numberfor Demonstrations.We can now use the module,as if the functions were built in Scilab.-->number_gcd(4,6)ans=2.The statement-->help number_gcdopens the help browser and shows the help page of the number_gcd function.We can also see and execute the demonstrations of this module.In order to do this,afirst method is to open the”?>Scilab Demonstrations”menu at the right of the main menu of the console.The second method is to execute the demo_gui function,as in the following session.-->demo_gui()Both methods open the demonstration browser,where we canfind the”Number”section.When we click on the entries of the”Number”section,some scripts are executed.These scripts either print messages in the console or produce graphics. In some cases,the script containing the demonstration is opened within the editor, which let us see how the functions of the number module were used to produce these outputs.2.9Loading the module automaticallyIn this section,we present a method to automatically load a module,thanks to Scilab’s startupfile.We can easily configure Scilab so that the module is automatically loaded at startup.It suffices to add a line in the.scilabfile associated with the current Scilab system.In order to locate the directory associated with the automatic startup system,we can display the value of the SCIHOME variable.-->SCIHOMESCIHOME=C:\DOCUME~1\Root\APPLIC~1\Scilab\scilab-5.2.0-beta-1Then,we edit thefileC:\DOCUME~1\Root\APPLIC~1\Scilab\scilab-5.2.0-beta-1\.scilabor we create it if it does not exist.We may also use the editor to directly open the file,with the following statement:editor(fullfile(SCIHOME,".scilab"))In thisfile,we write the lineexec("C:\number\loader.sce");which executes the loader script associated with the module.Now,if we exit from Scilab and start it again,the module is automatically loaded.2.10Cleaning the module(*)In this section,we present the cleaner script,which can be used to delete the binary files which have been generated by the building process.The builder script has created a number/cleaner.sce script,which can delete all thefiles which have been created by the builder script.In order to use this script, we just have to execute it:-->exec("C:\number\cleaner.sce");In fact,this script is a tool dedicated to the developper of the module.It can be used,for example,after some preliminary builds,to check that the building process executes correctly when it starts from zero.2.11Scilab’s Forge(*)Scilab forge is a tool for external modules developers,which can help the develop-ment process.The main adress of the Scilab Forge is:/index.php/projects/The Scilab Forge is the place where we can share the source code of Scilab projects.It provides several components to make the development easier.More precisely,it provides•a source code revision system(SVN or GIT),•a Download system(to upload and download module releases,documents in pdf form or binaries),•documentation pages(as a wiki),•a bug tracker,and several other features as well.The Forge lets the developers work on a common source code as a team,even if the developers are not in the same location.When we use the Forge as a regular Scilab user,we can•download the releases,•report bugs,•browse the source code with a web browser.When we use the Forge as a developer,it is mandatory to be familiar with version management systems such as SVN or GIT.For example,the developer can •update the source code with SVN or GIT,•manage the bug reports,•upload the releases.The Scilab Forge is also a good place tofind sources of modules.This can be helpful,for example when we search for a new technical feature.More details on Scilab’s Forge are presented at:/Scilab%20forge3Managing a moduleIn this section,we present how to manage a module.We analyse the tbx module, which is used in all standard modules to make the building process easier.In the remaining of the section,we present the various scripts and directories of a module and analyse their contents.3.1The tbx moduleThe tbx module is a built-in module which let us develop new modules.It provides a set of functions to compile a module and to produce the binary version of the module.Thefigure1presents the main functions of the tbx module.In order to understand the tbx module,we must distinguish the various types of scripts within a module.•A builder is a script which executes statements which convert a source code (either with.sci,.c,.cpp or.ffile extension)into a binaryfile,and au-tomatically generates the scripts required to load or clean the module.The builder is written by the developper of the module.•A loader is a script which executes statements to load the binaries in Scilab.These binaries can be the.bin associated with macros,the Java archive(jar) associated with the help or the binaries associated with the source codes or gateways(.so or.dll).The loader is automatically generated by the tbx module.•A cleaner is a script which executes statements to delete thefiles automatically created by the builder.The loader is automatically generated by the tbx module.Main functionstbx_build_cleaner Generate a cleaner.sce scripttbx_build_loader Generate a loader.sce scriptMacrostbx_build_macros Compile macrostbx_builder_macros Run buildmacros.sce script if it existsHelptbx_build_help Generate helpfilestbx_build_help_loader Generate a addchapter.sce scripttbx_builder_help Run builder_help.sce script if it existstbx_builder_help_lang Run build_help.sce script if it exists Gateways(*)tbx_build_gateway Build a gatewaytbx_build_gateway_clean Generate a cleaner_gateway.sce scripttbx_build_gateway_loader Generate a loader_gateway.sce scripttbx_builder_gateway Run builder_gateway.sce script if it exists tbx_builder_gateway_lang Run builder_gateway_(language).scescript if it existsSources(*)tbx_build_src Build sourcestbx_builder_src Run builder_src.sce script if it existstbx_builder_src_lang Run builder_(language).sce script if it exists Xcos(*)tbx_build_blocks Compile blocksFigure1:The tbx module.Sections marked with(*)are optional.Thanks to the tbx module,there are very few scripts which must be edited by the developer:most other scripts are automatically generated by the tbx functions.For each type of directory(i.e.macros,help,sources,gateways and Xcos blocks), the tbx module provides two types of functions:•the tbx_builder_*functions just executes sub-builders in the corresponding sub-directories,•the tbx_build_*functions actually converts the sources into binaryfiles or automatically generates other scripts.The tbx_builder_*functions will become clearer in the next section,when we discuss the chain of builders.3.2The chain of buildersThe builders of a module are a set of scripts,with the.scefile extension.Building the module just consists in executing the main builder.sce,which performs some processing and executes,in turn,other sub-builders.For example,we may consider the following chain of builders.•number/builder.sce:main builder,•number/macros/buildmacros.sce:convers the.sci macros into binaryfiles,•number/help/builder_help.sce:builds the help pages.When we execute the number/builder.sce script,the tbx functions that we call will executefirst the number/macros/buildmacros.sce script,then the number/help/ builder_help.sce script.In fact,this is not done directly in the script,but rather implicitely by the tbx functions which know what scripts to execute,provided that we follow the standards.3.3The main builderThe main builder has the role of executing other sub-builders in appropriate sub-directories,and performing other treatments as well.For example,the main builder of the number module is the following.function buildNumberMain()trygetversion("scilab");catcherror(gettext("Scilab 5.0or more is required."));end;if~with_module("development_tools")thenerror(msprintf(..gettext("%s module not installed."),.."development_tools"));endTOOLBOX_NAME="number";TOOLBOX_TITLE="Number";toolbox_dir=get_absolute_file_path("builder.sce");tbx_builder_macros(toolbox_dir);tbx_builder_help(toolbox_dir);tbx_build_loader(TOOLBOX_NAME,toolbox_dir);tbx_build_cleaner(TOOLBOX_NAME,toolbox_dir);endfunctionbuildNumberMain();clear buildNumberMainLet us analyse the previous script in more details.The call to the tbx_builder_macros function has the effect of executing the num-ber/macros/buildmacros.sce script.Similarly,the call to the tbx_builder_help function has the effect of executing the number/help/builder_help.sce script. The tbx_build_loader function generates the number/loader.sce script,which can be used later to load the module.Finally,the tbx_build_cleaner function generates the number/cleaner.sce script,which can be used later to clean the module.The clear buildNumberMain statement prevents the function buildNumber-Main from being visible from the user.Indeed,this function would have no sense for a regular user,for whom the building process must,in general,stay invisible. The reason why the body of this builder in inside a function is because it limits the number of clear statements to be performed.The main output of the main builder is the loader.sce script,which allows to load the module.3.4The etc directoryThe etc directory contains two scripts which are executed when the module is loaded (e.g.when Scilab starts)and when Scilab quits.•number/etc/number.start:this script is executed when the module starts,•number/etc/number.quit:this script is executed when Scilab quits.When we execute the number/loader.sce script,we see the following messages in the console.-->exec L:\mypath\number\loader.sce;Start NumberLoad macrosLoad helpLoad demosType"help number_overview"for quick start.Type"demo_gui()"and search for Numberfor Demonstrations.The previous messages are printed by the number/etc/number.start script that we are going to analyse.The content of the number/etc/number.start script is presented below.function numberlib=loadnumberlib()TOOLBOX_NAME="number"TOOLBOX_TITLE="Number"mprintf("Start%s\n",TOOLBOX_TITLE);etc_tlbx=get_absolute_file_path(TOOLBOX_NAME+..".start");etc_tlbx=getshortpathname(etc_tlbx);root_tlbx=strncpy(etc_tlbx,..length(etc_tlbx)-length("\etc\"));//Load functions libraryif(%t)thenmprintf("\tLoad macros\n");pathmacros=pathconvert(root_tlbx)+.."macros"+filesep();numberlib=lib(pathmacros);end//Load gatewaysif(%f)thenmprintf("\tLoad gateways\n");ilib_verbose(0);exec(pathconvert(root_tlbx+.."/sci_gateway/loader_gateway.sce",%f));end//Load and add help chapterif or(getscilabmode()==["NW";"STD"])thenmprintf("\tLoad help\n");path_addchapter=pathconvert(root_tlbx+"/jar");if(isdir(path_addchapter)<>[])thenadd_help_chapter(TOOLBOX_TITLE,..path_addchapter,%F);endend//Add demosif or(getscilabmode()==["NW";"STD"])thenmprintf("\tLoad demos\n");demoscript=TOOLBOX_NAME+".dem.gateway.sce"pathdemos=pathconvert(fullfile(root_tlbx,.."demos",demoscript),%f,%t);add_demo(TOOLBOX_TITLE,pathdemos);end//A Welcome message.mprintf("\tType""help number_overview""for"+.."quick start.\n");mprintf("\tType""demo_gui()""and search for"+..TOOLBOX_TITLE+"for Demonstrations.\n"); endfunctionif(isdef("numberlib"))thenwarning("\tLibrary is already loaded(""ulink();"+.."clear numberlib;""to unload.)");return;end。

相关文档
最新文档