Professional Documents
Culture Documents
Content
MATLAB as a programming language
Introduction to Scilab
What Is MATLAB?
The name MATLAB is an abbreviation for MATrix LABoratory MATLAB is a high-performance language for technical computing Used mainly for algorithm development and data visualization Algorithms can be implemented and tested more quickly and easily than with traditional programming languages Provide quickly numerical and graphic answers to matrix and vector related math problems
Development Environment
Set of tools and facilities that help you use MATLAB functions and files includes
MATLAB desktop
Command Window command history, an editor and debugger browsers for viewing help, the workspace, files, and the search path
MATLAB Language
High-level matrix/array language with control flow statements, functions, data structures, input/output, and objectoriented programming features Allows to rapidly create small to large and complex application programs
Graphics
Extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs Include high-level functions for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics Allow to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications
Common Uses
Developing Algorithms Data Analysis Data Visualization Numeric Computation
Developing Algorithms
The use of MATLABs own high-level language and developmental tools allow you to develop and analyze algorithms faster and easier. Using MATLABs tools lets you write and test algorithms using much fewer lines of code than C or C++. MATLAB allows you to use traditional programming features, such as arithmetic operations, flow control, data structures.
Data Analysis
MATLAB provides interactive tools and commandline functions for data analysis operations including: Correlation, Fourier analysis Basic statistics and curve fitting Matrix analysis MATLAB provides functions to input data easily from various sources like. Excel spreadsheets Text files
Data Visualization
With MATLAB you can graph/draw complicated structures easily. Several powerful tools exist for: 2-D and 3-D plotting
Numeric Computation
MATLAB has built in functions to handle the following types of math problems: Matrix manipulation and linear algebra Data analysis and statistics Optimization and numerical integration Ordinary differential equations (odes) Partial differential equations (PDEs)
MATLAB Basics
Starting MATLAB
double-click the MATLAB icon, or in a terminal window, type matlab, and return
In the Command Window the MATLAB prompt is >> The Desktop menu
undocking command window tiling other windows (command history, workspace, current directory)
MATLAB Basics
MATLAB as a calculator
Type expressions at the >>, and press return Result is computed, and displayed as ans Use numbers, +, *, /, -, (), sin, cos,
Examples of expressions
Legal expressions >> 4 >> 5 + pi >> 6*sqrt(2)^4-12 >> 6 * sqrt( 2.0) ^ 4 - 12 >> sin(pi/3)^2 + cos(pi/3)^2 >> 1.0/0.0 # a number divided by zero is infinity (inf) >> -4/inf # This is equal to zero >> 0/0 # This is equal to infinity Illegal expressions >> 2 4 >> (2,4)
Variables
Use names to assign result of an expression to a variable
Variables do not need to be declared before assignment
Read this as
evaluate expression on the right-hand side, and then
Therefore
The right-hand-side needs to be a legal Matlab expression The left-hand-side needs to be a single variable name
A semicolon at the end of the RHS expression suppresses the display, but the assignment still takes place.
Creation of Vectors
Colon notation to create a vector x = s:d:f or x = (s:d:f) or x = [s:d:f] where
s = starting value, d = increment or decrement f = end or final value
when d is omitted MatLab assumes d = 1. length(x) gives the number of terms in the vector. e.g. x = 0.2:0.1:1
e.g. x = linspace(-2,10,7) Vector can also be created with x = [-2,1,3,5,7,9,10]; or x = [-2,1:2:9,10]; z = x-1 results in z = -3 0 2 4 6 8 9 z(3) = z(3)/2 results in z = -3 0 1 4 6 8 9 z(3:5) = z(3:5)*3-1 results in z = -3 0 2 11 17 8 9 y = z(3:5) results in y = 2 11 17
Array Operations
y = [-3 0 2 11 17 8 9 ]; [ynew,indx] = sort(y) results in ynew = -3 0 2 8 9 11 17 indx = 1 2 3 6 7 4 5 Indxx = find(y<=9) and s = y(indxx) results in Indxx=1 2 3 6 7 and s= -3 0 2 8 9 [ymax,indxmax]=max(y) [ymin,indxmin]=min(y)
Creation of Matrices
A = [2 3 4;5 4 7; 7 6 9; 2 6 8]; or A = [2 3 4 547 769 2 6 8]; [m,n] = size(A) results in m = 4 and n = 3 S = length(A) results in S = 4
Special matrices
x = ones(r,c) # creates ones matrix where, r and c are dimensions of matrix L = zeros(r,c) # creates the zeros matrix diag(a) # creates the (n x n) diagonal matrix whose elements are given by vector a of length n
Manipulation of Matrices
A=[3 5 7 9 11 2 4 6 8 13 1 1 3 4 16]; A(3,4)=4 A(:,2) # Means all the rows of column 2 A(2,:) # Means all the columns of rows 2 A(1:3,3:5) results in [7 9 11;6 8 13;3 4 16]; x=A # Creates the transpose of A.
Manipulation of Matrices
Addition/Substraction C = A+B and C = A-B # A & B have same dimensions Column augmentation C = [A,B] # A & B have same number of rows Row augmentation C = [A;B] # A & B have same number of columns Removing the row or column C(3,: ) = [] # 3rd row of C is removed Multiplication C=A*B # for multiplication matrix dimensions should match. i.e (m x k) (k x n) (m x n)
Manipulation of Matrices
Dot operations are used to do mathematical operations on element by element. A = [2 3 5; 6 8 5; 7 10 9]; B = [5 2 9; 6 4 9; 3 20 7]; C=A.*B C=A./B =A divided by B element by element C=A.\B =B divided by A element by element C=A.^B Also if x=1:8 and y=2.^x results in y=2 4 8 16 32 64 128 256
Functions
Provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin Also provides many more advanced mathematical functions, including Bessel and gamma functions Most of these functions accept complex arguments For a list of the elementary mathematical functions, type help elfun For a list of more advanced mathematical and matrix functions, type help specfun help elmat
The workspace
It consists of the set of variables built up during a MATLAB session and stored in memory All variables that you create are accessible from the prompt >> Variables are accessed using their name as a reference
Builtin Matlab commands >> who #list current variable >> whos #more information about current variable are used to see what is in the workspace.
You can clear (ie, erase) variables with the clear command >> clear A # clears the variable A from the workspace
Loading from a .mat file load is the opposite of save. It reads a .mat file, putting all variables contained in the .mat file into the workspace >> load # loads all of the variables from the file matlab.mat >> load Andy
loads all of the variables from the file
andy.mat
Programming in Matlab
Script files
A MATLAB script file (Called an M-file) is a text file that contains one or more MATLAB commands and, optionally, comments. The file is saved with the extension ".m". When the filename (without the extension) is issued as a command in MATLAB, the file is opened, read, and the commands are executed as if input from the keyboard. The result is similar to running a program in C.
Script files
factscript.m
% FACTSCRIPT Compute n-factorial, n!=1*2*...*n y = prod(1:n);
Executed by typing its name >> factscript Operates on variables in global workspace Variable n must exist in workspace Variable y is created (or over-written) Use comment lines (starting with %) to document file
Function files
Functions describe subprograms Take inputs, generate outputs Have local variables (invisible in global workspace)
Scripts
Operate on global workspace Document work, design experiment or test Solve a very specific problem once
Logical expressions
Relational operators (compare arrays of same sizes) == (equal to) ~= (not equal) < (less than) <= (less than or equal to) > (greater than) >= (greater than or equal to) Logical operators (combinations of relational operators) & (and) if (x>=0) & (x<=10) | (or) disp(x is in range [0,10]) ~ (not)
else disp(x is out of range) end Logical functions xor # Logical EXCLUSIVE OR isempty # True for empty array any # True if any element of a vector is nonzero all # True if all elements of a vector are nonzero
<commands>
elseif <logical expression> <commands> else <commands> end if height>170 disp(tall) elseif height<150
disp(small)
else disp(average) end
',num2str(kfac)]);
while-loops
while <logical expression> <statements> end <statements> are executed repeatedly as long as the <logical expression> evaluates to true
Save this file and this data file is going to be given as input to the above programme For this programme to work, a function M file write should be available in the present working directory. The content of this file is given in the next slide. You can create this function write by copying the content to the MATLAB editor window and by saving the file
Now three files such as test.m, data.m and write.m are available in the current working directory Execute the script file test.m by typing test in the command window Now you can see the prompt
Enter the data FILE NAME. It should be a scipt M file.
Enter data_result.txt
Now you will see the following in the command window: Warning: File 'data_result.txt' not found. > In test at 5 This is because there is no 'data_result.txt' file was available in the current working directory before the execution of the script file test. In the program there was a command to delete 'data_result.txt' file This is the reason for the warning You can now open 'data_result.txt' file in the MATLAB editor window
Click the existing file open icon in the tool bar; a small window will be opened select file type as all Now you can see 'data_result.txt file and open this file to see the content
Programming Exercise
Develop a program to sample a random value based on the given empirical distribution. For example, if the distribution is as follows Event Frequency 1 25 2 25 3 30 4 20 When we sample, the event can be 1 or 2 or 3 or 4. The program has to give randomly one value. We want a generalised program so that for any empirical distribution it will give a random value. This value has to be used subsequently in some other program.
Two programs to this question is given in the next two slides Which is the program you prefer?
Program 1
Function leadtimeee(); % lt-lead time in weeks; a=1; b=100; r=round((b-a)*rand+a); if (1<r)&(r<=25) disp('lt=1'); elseif (26<r)&(r<=50) disp('lt=2'); elseif (51<r)&(r<=80) disp('lt=3'); else disp('lt=4'); end
Program 2
function [rd]=randdem(d,df) % RANDEM(d,df) identify randomly a sample value from the distribution defined by % d and df. The possible values of the variable are given in d and % frequencey of these values are given in df. ld = length(df); rf = (df./sum(df))*100; a=0; for i = 1:ld a=a+rf(i); cf(i)=a; end rn=rand*100; for j=1:ld if j==1 if rn<=cf(j) rd = d(j); break end elseif rn>=cf(j-1) & rn<=cf(j) rd = d(j); break end end
What is Scilab?
Scilab is an open source scientific software package which can be used as a programming language. It can be used for numerical computations; providing a powerful open computing environment for engineering and scientific applications. It is a collection of collection of numerical algorithms covering many aspects of scientific computing problems. Since 1994 it has been distributed freely along with the source code via the Internet. It is currently used in educational and industrial environments around the world.
History
Scilab was created in 1990 by researchers from INRIA (French National Institute for Research in Computer Science and Control) and cole nationale des ponts et chausses (ENPC) Scilab Consortium was formed in May 2003 to broaden contributions and promote Scilab as worldwide reference software in academia and industry In July 2008, the Scilab Consortium joined the Digiteo Foundation
History Contd..
1980: Matlab written in Fortran and public domain 1984: creation of The MathWorks company
Scilab
Toolboxes
SIVP: image and video processing MIXMOD: cluster and discriminant Analysis OpenFEM: finite elements Wavelab: wavelet analysis OPC: data acquisition Grocer: econometric Modnum: communication systems in Scicos RTAI: real time Scicos CGAL: computational geometry GRID with ProActive GREENSCILAB: plant growth simulation
Computation library
Matrix computation, sparse matrices Polynomials and rational functions Interpolation, approximation Simulation: systems of differential equations Classic and robust control, LMI optimization Differentiable and non-differentiable optimization Signal processing Statistics Graphs and networks Scicos: block diagram simulator for dynamical systems
Contributors
User interface
Language, interpreter Editor On line help
Scilab Consortium
Interface Services
Courtesy: Claude Gomez (Scilab Consortium / Digiteo Director )and Bruno Jofret (Scilab Consortium / Digiteo Project Engineer), A ppt presentation on Scilab: The Platform for Numerical Computation
Websites
Scilab binaries can be downloaded directly from the Scilab homepage for the platforms (Windows, Linux or Mac)
http://www.scilab.org/
A list of commercial books, free books, online tutorials and articles is presented on the Scilab homepage
http://www.scilab.org/publications
Scilab in India
A project on Scilab is currently going on in IITB
www.scilab.in
This project is funded by MHRD as part of the National Mission on Education through ICT. Mumbai and Pune universities have scilab as part of their syllabus
References
For Matlab 1. Rudra Pratap, Getting Started with MATLAB 7, First indian edition 2006, Oxford University Press Inc 2. E.B.Magrab, S.Azarm, B.Balachandran, J.H.Duncan, K.E.Herold and G.C.Walsh. An Engineers Guide to MATLAB, second edition 2005, Pearson Prentice Hall. 3. www.mathworks.com For Scilab http://www.scilab.org/support/documentation/tutorials
Thank You