You are on page 1of 59

MATLAB and other software tools

By Dr. V. Madhusudanan Pillai Associate Professor MED

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

Content of MATLAB system


Development Environment MATLAB Mathematical Function Library MATLAB Language Graphics MATLAB Application Program Interface (API)

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 Mathematical Function Library


Large collection of computational algorithms ranging from
elementary functions, like sum, sine, cosine, and complex arithmetic to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms

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

MATLAB Application Program Interface (API)


This is a library that allows you to write C and Fortran programs that interact with MATLAB It includes facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files

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)

General Features of MATLAB


The operations are designed to be as natural as possible Basic data element is an array that does not require dimensioning Consists a family of add-on application-specific solutions called toolboxes Toolboxes are comprehensive collections of MATLAB functions (M-files)
to learn and apply specialized technology like signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many others.

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,

exp, abs, round,

Precedence rules in expressions


Left-to-right within a precedence group Precedence groups are (highest first)
Highest precedence is parenthesis, then Power (^) Multiplication and division (*, /) Addition and subtraction (+, -)

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

A single equal sign (=) is the assignment operator,


LHS = RHS

Read this as
evaluate expression on the right-hand side, and then

assign the result to the variable named on the left-hand-side

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.

Examples of Variables and Assignment


Legal
>> A = sqrt(13) >> B = exp(2); >> A = 2*B >> A = A + 1 >> C = tan(pi/4)

Illegal (all for different reasons)


>> D = sqrt(E) + 1; # if E is defined before then valid >> 3 = E >> 3*A = 14 >> F = 2 3

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

Creation of Vectors and Operations


Generation of n equally spaced values. x = linspace(s,f,n)
The increment or decrement is calculated by MATLAB Increment or decrement, d = (f-s)/(n-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

Column and Row deletion of matrix


If a is 10 x 12 matrix and the 9th column is not required this can be obtained by a(:,9)=[]; If 9 to last columns are not required which can be obtained as follows A(:,9:end)=[];

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

Saving the workspace


When you quit MATLAB, the variables in the workspace are erased from memory. If you need them for later use, you must save them. You can save all variables (or just some of them) to a file using the command save >> save # saves all of the variables in the workspace into a file called matlab.mat (it is saved in the current directory) .mat file is in binary format >> save Andy saves all of the variables in the workspace into a file called Andy.mat >> save Important A B C D* saves the variables A, B, C and any variable beginning with D in the workspace into a file called Important.mat

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)

Structure of Function files


[output_arguments]= function_name(input_arguments) % Comment lines <function body> factfun.m
function [z]=factfun(n) % FACTFUN Compute factorial z = prod(1:n);

Execution of function file >> y = factfun(10);

Script or function: when use what?


Functions
Take inputs, generate outputs, have internal variables Solve general problem for arbitrary parameters

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

Flow control - selection


The if-elseif-else-end construction
if <logical expression>

<commands>
elseif <logical expression> <commands> else <commands> end if height>170 disp(tall) elseif height<150

disp(small)
else disp(average) end

Flow control - repetition


Repeats a code segment a fixed number of times
for index = <vector>
<statements> end The <statements> are executed repeatedly. At each iteration, the variable index is assigned a new value from <vector>.
for k=1:12 kfac=prod(1:k); disp(['Factorial of ',num2str(k),' is end

',num2str(kfac)]);

Flow control conditional repetition

while-loops
while <logical expression> <statements> end <statements> are executed repeatedly as long as the <logical expression> evaluates to true

A typical programme showing input and output methods


clear all fclose('all'); input(['\n Enter the data FILE NAME. It should be a scipt M file.\n\n']); fname1 = input([' \n Enter the NAME of a txt. file where results to be stored: '],'s'); delete(fname1) C = A*B; f2 = fopen(fname1,'w'); fprintf(f2,'%s\n\n',fname1); s1 = Product of two matrices; fprintf(f2,'%s\n\n',s1); write(f2,3,0,C); fclose(all);

Input requirement for the above programme


The above programme can be saved as script M file Open the MATLAB editor window and open a new file Copy the above program to this file and save as test Create another data script file with the following content
% Input data for Matrix mutiplication A = [10 8 6; 5 7 8]; B = [2 4; 3 5; 6 2];

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

Content of function file write


function write(fid,w,p,x) % WRITE(fid,w,p,x) write the matrix x in a file associated with file % identifier fid. The format includes the conversion character f. % The format field width w and precision p are argument to the % function. The data can be printed in integer format if p is % assigned zero. The field width w may be atleast one unit greater % than the largest size data element in matrix x. n = size(x); for i = 1:n(1) for j = 1:n(2) c = fprintf(fid,'%*.*f\t',w,p,x(i,j)); end fprintf(fid,'\n'); end fprintf(fid,'\n');

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 There is another prompt in the window as


Enter the NAME of a txt. file where results to be stored:

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

r-random number; a,b- constants


% generate a random number % if random number is between 1 and 25 % display lt = 1 % if random number is between 26 and 50 % display lt = 2 % if random number between 51 and 80 % display lt = 3 % else lt = 4

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

A script M file to get solution of program 2


d= [0 1 2 3 4 5 6 7]; df=[2 4 14 16 8 1 1 4]; rand_dem =randdem(d,df) lt = [1 2 3 4]; ltf = [60 30 9 1]; rand_lt = randdem(lt,ltf) Save the above as data1.m file and execute this file, the answer will be displayed in the command window. Remember that Program 2 and this data1 should be available in the same directory.

Scilab: The Free Platform for Numerical Computation

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

Since 1990: Matlab is the standard and a monopoly


Around 1980: Blaise then Basile built upon Matlab 1990: creation of Scilab at INRIA

1994: Scilab freely distributed on the net


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

Scilab

More than 1,700 functions

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

Graphics, GUI, GUI builder


2-D and 3-D graphics, animation Ui controls, interface with TCL/TK

Contributors

User interface
Language, interpreter Editor On line help

Scilab Consortium

Interface Services

Other Scientific Software

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/

Use the help provided on Scilab web site


http://www.scilab.org/product/man

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

You might also like