Download presentation
Presentation is loading. Please wait.
Published byJessie Patterson Modified over 9 years ago
1
Part 1 Introductory to Scilab Course
2
Outline Views 1.0Introduction to Scilab 2.0Scilab Environment 3.0Working with Variables and Array 4.0Scilab Programming Language 5.0Plotting and Visualization
3
Introduction - What is Scilab?? Scientific software package for numerical computations -> a powerful open computing environment for engineering and scientific applications An open source software Currently used in educational and industrial around the world Under Scilab Consortium – launched in May 2003 Includes hundreds of mathematical functions with the possibility to add interactively programs from various languages (C,C++,Fontran and etc) Has sophisticated data structures (including lists, polynomials, rational functions, linear systems & etc), an interpreter and a high level programming
4
Introduction - What is Scilab?? Cntd.. What people like: Can port a Matlab toolboxes to Scilab Have impressive number of built-in functions as well as number of built-in toolboxes Contain Scicos, a visual system modelling tool, letting the user visually build systems that can then be dynamically simulated. Scicos is free counterpart to The MathWork’s Simulink product, which must be purchased separately from Matlab. Use without worrying about legality issues or (ethics!) It is FREEE!!! (erm... not interested BECAUSE we can get FREE pirated copy software!!!)
5
Introduction - What is Scilab?? Cntd.. Primary issues/challenges: Lack of a nice IDE (Integrated Development Environment). It is not-really-free-licence. The statement from the developers (from Scilab website) mention that the coming version 5 will be released under recognised open source licence.
6
What does it mean for Government, School or an Institution (GSI)? Lower IT costs Examples: Cost estimated to buy Matlab licence in UniMAP = 7 labs x 70 PCs x RM4000 = RM1,960,000.00 Spend more than a million just to install Matlab!! Matlab is superb, but it may put you in the poor house! If we don’t buy Matlab licence, the money can be used to buy other equipments which are more important for student usage.
7
Features of Scilab A number of toolboxes are available with the system: 2-D and 3-D graphics, animation Linear algebra, sparse matrices Polynomials and rational functions Interpolation, approximation Simulation: ODE solver and DAE solver Scicos: a hybrid dynamic systems modeler and simulator Classic and robust control, LMI optimization Differentiable and non-differentiable optimization
8
Features of Scilab Signal processing Metanet: graphs and networks Parallel Scilab Statistics Interface with Computer Algebra: Maple package for Scilab code generation Interface with Fortran, Tcl/Tk, C, C++, Java, LabVIEW And a large number of contributions for various domains.
9
Features of Scilab Scilab has been built using a number of external libraries Scilab works on most Unix systems (including GNU/Linux) and Windows (9X/2000/XP/Vista) It comes with source code, on-line help and English user manuals
10
What’s next for Scilab in UniMAP?? Why use Scilab? Its capabilities to perform similar functions as Matlab such as: Design filter Plot graphs and spectrums Perform fast fourier transform (FFT) Perform signal analysis Simulate communication system design& etc First implementation will be done for Signal and System lab module where Scilab with Linux platform will be used to replace Matlab software.
11
How to Install Scilab? The simplest way to install and use Scilab is : Go to http://www.scilab.org/ht p://www.scilab.org/ Download Scilab 5.5.2 (latest version) Run and follow its steps To start Scilab : Double click the Scilab icon on the PC desktop or Go to Start / All Programs / Scilab / scilab (do not select Scilab Console)
12
Scilab Environment Command Window is used to enter variables and run functionsand sci-files. The Command window is where you can interact with Scilab directly. Command Window
13
Scilab Help Window Help Window consists of commands and functions which can be performed in Scilab session. How to open Help window? -> Click ? button in the Scilab toolbar Help Window
14
Scilab Editor Access to commands SciPad Launch Icon
15
Workings with Variables and Array The Scilab environment is command oriented like UNIX. A prompt appears on the screen and a MATLAB statement can be entered. When the key is pressed, the statement is executed, and another prompt appears. If a statement is terminated with a semicolon ( ; ), no results will be displayed (similar to MATLAB). Variable names ARE case sensitive. Variable names must start with a letter followed by letters, digits, and underscores. Variable names and their types do not have to be declared. Any variable can take real, complex, and integer values. The name of variable is not accepted if it is reserved word.
16
Scilab Variables Special variables: – ans: default variable name for the result. – %pi: π = 3.1415926 => % is used in front of defined keyword ---- %i : i is an imaginary number %inf : infinity (∞) Commands involving variables: -who: lists the names of the defined variables -whos: lists entire contents of the workspace, including functions, libraries, constants -clear: clears all variables -clc: clears the command window clf: clears all plots in the active graphic window
17
Scilab Arithmetics Operators OperatorDescription + Addition - Subtraction.* Multiplication (element wise)./ Right division (element wise).\ Left division (element wise) = Assignment operator,e.g. a = b, (assign b to a) : Colon operator (Specify Range ).^ Power (element wise) ' Transpose * Matrix multiplication / Matrix right division \ Matrix left division ; Row separator in a Matrix ^ Matrix power
18
Calculations at Command Lines » -5/(4.8+5.32)^2 ans = -0.0488213 >>(3+4*%i)*(3- 4*%i) ans = 25. » cos(%pi/2) ans = 6.123D-017 » exp(acos(0.3)) ans = 3.5470053 » »»»» a = 2; b = 5; a^b ans = 32. » x = 5/2*%pi; » y = sin(x) y = 1. » z = asin(y) z = 1.5707963 Results assigned to “ans” if name not specified ( ) parentheses for function inputs Semicolon suppresses screen output Scilab as a calculatorAssigning Variables
19
Vectors and Matrices in Scilab 425425 1 5 23230 1 2 Rows (m)3 4 5 (n) 12345 16111621 410162 8 2 1.2 7 9 1212172 7.2 3 57 81313 18 11 23 4 00.5 9 4 1414 19 56 24 5 83 10 13 1520 10 25 A =A = A (17) Rectangular Matrix: Vector:m-by-1 array Matrix: 1-by-n array m-by-n array Matrix elements can be EITHER numbers OR characters Columns How do you specify this 5 x 5 matrix ‘A’ in Scilab ? 4101>>A=[ A (2,4) 62 81.29 425 7.257111 00.5 4556 Sca 2 la 3 r: 8 1 3 -b 1 y- 3 1 0 arra 1 y 0 ]; >>A=[410162; 81.29425; 7.257111; 00.5 4556; 238313 010 ];
20
More on VectorsMore on Vectors x = start:endCreates row vector x starting with start, counting by 1, ending at end x = initial value : increment : finalCreates row vector x starting with start, counting by increment, ending at or before end x = v li a n l s u p e ace(start,end,number) Creates linearly spaced row vector x starting with start, ending at end, having number elements x = logspace(start,end,number)Creates logarithmically spaced row vector x starting with start, ending with end, having number elements length(x)Returns the length of vector x y = x’Transpose of vector x
21
More on Matrices zeros(n,n)Returns a n x n matrix of zeros zeros(m,n)Returns a m x n matrix of zeros rand(m,n)Returns a m x n matrix of random numbers eye(m,n)Returns a m x n Identity matrix ones(n,n)Returns a n x n matrix of ones ones(m,n)Returns a m x n matrix of ones size(A) For a m x n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix
22
Examples
23
Entering numeric array » a=[1 2;3 4] a = 1 3 2424 » cat_a=[a,2*a;3*a,4*a;5*a,6*a] Use [ ] to combine existing arrays as matrix “elements” Row separator: Use square brackets [ ] The resulting matrix must be rectangular. 4*a semicolon (;) cat_a = 1. 2. 4. 3.4.6.8. Column separator: 3.6.4.8. space / comma (,) 9.12. 16. 5.10.6.12. 15.20.18.24.
24
Sub Matrices 1 2 3 4 5 12345 A =A = A(3,1) A(3) A(1:5,5) A(:,5) A(21:25) A(4:5,2:3) A([9 14;10 15]) Use () parentheses to specify index colon operator (:) specifies range / ALL [ ] to create matrix of index subscripts ‘end’ specifies maximum index value A(1:end,end) A(:,end) A(21:end) 1 4 6 10 111111 16 6 21 2 2 8 7 1.27 1.2 129129 17 4 22 2522 25 37.237.2 8585 137137 18 1 23 1123 11 4 0 9 0.59 0.5 144144 19 5 24 5624 56 5 235 23 10831083 15 13 20 0 25 1025 10
25
Examples Hints: The $ symbol stands for the last row or last column index of a matrix or vector. The colon symbol (:) stands for “all rows” or “all columns”
26
Examples of Matrix Operations a = [ 1 2 3; 4 5 6; 7 8 9];Define a 3x3 matrix b = a’Transpose a and store a in b c = a + bAdd a and b and store the result in c. a and b must be in the same size d = a – bSubtract a and b and store the result in d. e = a * bMultiply a and b and store the result in e. a and b must be compatible for matrix multiplication f = [3 1 2; 1 5 3; 2 3 6];Define a 3x3 matrix g = inv(f)Invert f and store it in g. f must be square and positive definite f * gThe answer must be an identity matrix det(f)Determinant of f log(a)Matrix of log of each element of a a.*bElement by element multiplication a^2Same as a * a a.^2Element by element square
27
Scilab Programming - Function The syntax for a function definition line is as follows…… function[output variables] = function_name (input variables); The function_name must be the same as the filename (without the.sce extension) in which the function is written. For example if the name of the function is euler then it must be written and saved in a file with the name euler.sce Examples: Function Definition Line function [rho, H, F] = motion (x, y, t); File name motion.sce function theta = THETA (x, y, z);THETA.sce function [] = circle (r); function circle (r)circle.sce function [theta] = angleTH (x, y);angleTH.sce CAUTION: The first word in the functiondefinition line, function, must be typed in lower case. A common mistake is to type it as Function A function definition line may look slightly different depending on weather there is no output, single output, or multiple outputs.
28
Scilab Programming - Function function[xout, yout] = function_name (input variables); // add 1 line description of the function here //write online help comments here // include your name and date x = blah;. y = more_blah; Function definition line Output list Function name Input list H1 lineH1 line Comment line used by online help Body of the function Comments in the H1 line can be accessed by the lookfor command
29
Scilab Programming - Function Programming: Open SCIPAD to write your program Hints: When save file, remember write filename + extension (*.sce, *.sci ) .sce files are executed .sci files are loaded to be used when we need them Write function as ‘myfunc’ Load function into Scilab Execute function in command window
30
Programming - Loop Similar to other programming languages Repeats loop a set number of times (based on index) The for loop… N=10; for i = 1:N disp(i) end
31
Programming – Conditional Statement if, elseif and else statements….. x=10; if x < 0 disp(‘Negative’) elseif x ==0 disp(‘Zero’) else disp(‘Positive’) end Works on Conditional statements Short-circuited in Scilab - once a condition is true, the sequence terminates.
32
Plotting and Visualization in Scilab Specify x-data and/or y-data Specify color, line style and marker symbol Syntax: 2-D Plotting – Plotting single line: – Plotting multiple lines: plot2d(x1, y1, 'clm1', x2, y2, 'clm2',...) plot2d(xdata, ydata, 'color_linestyle_marker')
33
2D Plotting Create a Blue (default color) Sine Wave »t= 0:.1:10; »y= sin(2*t); » scf(1);//figure »plot2d(x,y);
34
2D Plotting Adding a Grid and Label plot »t= 0:.1:10; »y= sin(2*t); » scf(1);//figure »plot2d(t,y); » ax1=gca(); » ax1.grid =[0,0]; //Adds grid. (gca=get current axes) //[0,0] iscolour code for x and y grid, resp. [0,0] is black. » title('Experiment 1') » xlabel('t [s]') » ylabel('y [V]')
35
Multiple 2D Plotting »t= 0:.1:10; » u=-1+0.2*t; //u is a column vector »y= sin(2*t); » scf(1); »plot2d(t,y,t,u); Plot 2 curves in one plot
36
Subplots » scf(1); clf; //Opens and clears figure 1 » subplot(211) //Plot number 1 in a 2x1 "table" ofplots » plot(t,u) » subplot(212) //Plot number 2 in the 2x1 "table" of plots » plot(t,y) SUBPLOT- display multiple axes in the same figure window
37
Application – Digital Signal Processing //Generation of a Unit Sample Sequence //Generate a vector from -10 to 20 n = -10:20; //Generate the unit sample sequence u = [zeros(1,10) 1 zeros(1,20)]; //Plot the unit sample sequence scf(1); plot2d3(n,u); xlabel('Time index n'); ylabel('Amplitude'); title('Unit Sample Sequence'); Signal Generation – Unit Impulse
38
Signal Generation c = -(1/12)+(%pi/6)*%i; K = 2; n = 0:40; x = K*exp(c*n); subplot(2,1,1); plot2d3(n,real(x)); xlabel('Time index n');ylabel('Amplitude' ); title('Real part'); subplot(2,1,2); plot2d3(n,imag(x)); xlabel('Time index n');ylabel('Amplitude' ); title('Imaginary part'); Complex Exponential
39
Convolution Sum Function of convolution
40
Fast Fourier Transform (FFT) //Simple use of fft x=0:63; y=cos(2*%pi*x/16); scf(1); subplot(2,1,1) plot(y); title('Cosine Signal'); yf=fft(y,-1); subplot(2,1,2); plot(x,real(yf)'); title('DFT of Cosine Signal');
41
Frequency Response in Z-Transform Example: Given the difference equation as the following: y[n] 0.2 y[n 1] 0.5 y[n 2] x[n] x[n 2] (i)Find zeroes and poles for the given H(z) and plot them (ii)Plot the magnitude and phase response of H(z)
42
Pole Zero Plot Command z=poly(0,'z'); scf(0); num = z^2+1; den = z^2-0.2*z-0.5; zero = roots(num)//gives the values of zeros pole = roots(den)//gives the values of poles h = num/den; plzr(h);
43
Pole Zero Plot
44
Frequency Response in Z-Transform z=poly(0,'z'); //Defines z to be a polynomial variable sys=syslin('d', (z^2+1), (z^2-0.2*z-0.5)); // Creates sys as a discrete-time ('d') syslin model. fmin=0.001; //Min freq in Hz fmax=1; //Max freq in Hz scf(1);clf; bode(sys,fmin,fmax); / /Plots frequency response in Bode diagram title('Frequency Response of H(z)');
45
Frequency Response in Z-Transform bode( ) plots frequency response in a Bode plot The frequency axis shows normalized frequencies. The red vertical line in the Bode plots represents the normalized Nyquist frequency, which is 0.5, corresponding to the normalized sampling frequency being 1 samples/sec. If the actual sampling frequency is fs [samples/sec], the actual (non-normalized) frequency is found by multiplying the normalized frequency by fs.
46
FIR Filter Design To fully design and implement a filter, five steps are required: (1)Filter specification (2)Coefficient calculation (3)Structure selection (4)Simulation (optional) - MATLAB (5)Hardware Implementation (using FPGA or DSP board)
47
Low Pass Filter Specification
48
Using Scilab’s wfir( ) function Instead of doing the design start from the ideal reponse, we shall use Scilab's wfir () function We will design a FIR filter with the following specification sampling frequency = 8000 passband edge frequency = 1200 stopband edge frequency = 1800 minimum stopband attenuation = 40 dB By using the Hamming window, the stopband attenuation specification is met
49
Using Scilab’s wfir( ) function fsamp = 8000; fp= 1200; fs= 1800; fc= (fp+fs)/2; N = round(3.3*fsamp/(fs-fp));//Compute the order offilter wc=2*fc/fsamp; //Compute the cut-off frequency [valcoeff,filtamp,filtfreq]=wfir('lp',N,[wc 0],'hm',[0 0]); plot2d(filtfreq,log(filtamp)); xlabel('Frequency inrad/sec'); ylabel('Amplitude'); wfir( ) computes linear phase FIR Command: [wft,wfm,fr] = wfir(‘lp’,order offilter,cut-off frequency, ‘type ofwindow’,window parameter)
50
Magnitude Response of LPF
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.