Vous êtes sur la page 1sur 48

Training Program on MATLAB

by
Dr. A.P. Ruhil Computer Centre

Contents
Introduction to MATLAB MATLAB Basics MATLAB Programming Graphics & Animation Applications Statistical data analysis

Introduction to MATLAB
MATLAB (Matrix Laboratory) A special purpose computer program to perform optimized engineering and scientific calculations. Genesis: In 1960-70 a large number of subroutines developed for specific computational purpose in FORTRAN were organized into public domain packages for free distribution.

MATLAB was originally created as a front end for LINPACK A group of routines for working with matrices and linear algebra. Primary developer Prof. Cleve Moler (Univ. of New Maxico) founded Mathwork Inc. to further develop and market the product (MATLAB) commercially Most widely used tools for high performance numerical computations in engineering and scientific departments.

Provide interactive working environment with hundred of built-in functions for technical computation, graphics and animation. Built-in functions and Tool box: Linear algebra, Statistical Data Analysis, Signal Processing, Optimization, Partial Differential Equations, Artificial Neural Network, Fuzzy Logic, GA, Financial, Communication, Symbolic Math, Data Acquisition, Database, Image processing, Compiler, External Interface etc.

Why MATLAB ?
Vector/matrix manipulation is intuitive Plotting is easy and flexible Toolboxes for specialized functionality Full programming language suitable for quick prototyping

Advantages
Ease of use similar to Basic language State of the art algorithms Platform Independence Predefined and user defined functions Device Independent Plotting Graphic User Interface for application development Interface with C/ C++/ FORTRAN Languages Matlab Compiler

Advantages of MATLAB
1-Ease of Use
MATLAB is similar to BASIC language. Can be used as scratch pad to evaluate expressions typed at the command line, or it can be used to execute large prewritten programs. Programs may be easily modified with the builtin integrated development environment and debugged with the MATLAB debugger. As it is so easy to use, it is ideal for the rapid prototyping of the programs.

2-Platform Independence
MATLAB is supported on many different Computer systems, providing a large measure of platform independence. Programs written on any platform will run on all the other platforms.

3-Predefined Functions
MATLAB comes complete with an extensive library of functions that provide tested and pre-packaged solutions to many basic technical tasks. In addition to the large library of functions built into the basic MATLAB language, many special-purpose toolboxes are available to help complex problems in specific areas.

4-Device-Independent Plotting
MATLAB has many plotting and imaging commands. The plots and images can be displayed on any graphical output device supported by the computer on which MATLAB is running. This capability makes MATLAB an outstanding tool for visualizing technical data.

5-Graphical User Interface


MATLAB includes tools that allow users to interactively construct a graphical user interface (GUI) for his or her program. With this capability, the users can design sophisticated data analysis programs that can be operated by relatively inexperienced users.

6-MATLAB Compiler
MATLABs flexibility and platform independence is achieved by compiling MATLAB programs into a deviceindependent p-code and then interpreting the p-code instructions at runtime.

7-Interface with C/ FORTRAN Languages

C++/

Disadvantage
Slow in Interpreter mode High Cost

MATLAB Environment
Fundamental data type is Array. Scalar is also treated as array with one row and one column Three most Important windows are: Command, Figure, Edit/Debug Examples in Command window (run MATLAB Environment)

MATLAB Desktop
Current Directory

Launch Pad

Command Window

History

Workspace is collection of all created variables and arrays (who, whos, clear) Getting Help:
? from menu or typing helpdesk Type help followed by function name Type lookfor followed by function/key word

Important Commands (clc, clear)

MATLAB Search Path

Variables
A variable is a holding place for a value which can be given a name. Variable Name Rules:
Must begin with a letter followed by any combination of letters, numbers, and the underscore. Only first 31 characters are significant. Name must be unique. Names are case sensitive

Numeric Variables
Double precision occupies 8 bytes or 64 bits in size Can hold integer, real, imaginary, or complex values Range: 10 ^ -308 to 10 ^ 308 15-16 significant decimal digits Automatically created by assigning a numeric value to a variable V = 1 + I; (creates a complex number)

Character Variables
Consists of scalars or arrays of 16 bit values each representing a single character Automatically created by assigning a single character or a character string to a variable

Comment = This is a Character String; (creates a 1x26 character array)

Now show workspace window

Variables can be created at any time


Type of data assigned to variable determines the type of variable

Initializing Variables
Assign data to the variables in an assignment statement
(var = expression)

Input data into the variable from Keyboard


var = input(Enter an input value: );

Read data from file

Useful Commands
who - shows the environment (name of variables in workspace) clear - removes all variables from memory clear v1 ez - removes variables v1 & ez from memory clf - clears the current figure or graph clc - clears the command window Dir - lists current directory delete fname - deletes file named fname

Special Values/ Variables


pi (3.14159) inf infinity NaN not a number clock current date and time date current date eps epsilon ans answer

Reserved Words
MATLAB has some special (reserved) words that may not be used.
for end if while function return elsif case otherwise switch continue else try catch global persistent break

Displaying Output data


Integer values are displayed as such Real number up to four decimals Very small or large number in scientific notation with exponent Default format can be changed to:
format short 4 digits after decimal (default) format long 14 digits after decimal format short e, format short g format long e, format long g

Save/ Load Data


MATLAB saves data in MAT file in a special compact format. (default mode) Use -ascii option to save data to exchange data file other than MATLAB (use extension as .dat)

Save filename var1 var2. Load filename (to retrieve data from file)

MATLAB Basics
The fundamental unit of data (variable) in any MATLAB program is the array. An array is a collection of data values organized into rows and columns and known by a single name.

Arrays can be classified as either vector or matrices. The term vector is usually used to describe an array with only one dimension, while the term matrix is usually used to describe an array with two or more dimension.

MATLAB Matrices
MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, it is stored that way.

Vectors are special forms of matrices and contain only one row OR one column. Scalars are matrices with only one row AND one column.

Multidimensional Array
2D 3D or more Arrays are stored in memory in column major order eg. For A(2x2) array elements are stored as (1,1), (2,1), (1,2), (2,2) Can be accessed as single array subscription. Eg. A(3) will be A(1,2) Subarray

MATLAB as Scratchpad
MATLAB can do everything a calculator does >> (1+4)*3 >> ans= 15

MATLAB Matrices (Scalar)


A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows: a_value=23 a_value = 23 >>area = pi*2.5^4; >>x= 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6;

Scalar Operations
Arithmetic Operations between tow Scalars:
Addition: Subtraction: Multiplication: Division: Exponentiation: a+b ab a*b a/b a^b

Hierarchy: Parenthesis, ^, /, *, +, - from L to R

MATLAB Matrices (Row Vector)


A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas): rowvec= [12 14 63] rowvec= 12 14 63

MATLAB Matrices (Col. Vector)


A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons): colvec= [13; 45; 2] colvec= 13 45 2

MATLAB Matrices
A matrix can be created in MATLAB as follows (note the gaps AND semicolons): matrix = [1 2 3; 4 5 6; 7 8 9] matrix = 1 2 3 4 5 6 7 8 9

Extracting a Sub-Matrix
A portion of a matrix can be extracted and stored
in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is: sub_matrix= matrix ( r1 : r2 , c1 : c2 );
where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix.

Array Operation
Performed between arrays on an elementby-element basis
Array Addition: a + b Array Subtraction: a b Array Multiplication: a .* b Array Right Division: a ./ b Array left Division: a .\ b Array Exponentiation: a .^ b

Matrix Operation
Follows the normal rules of linear algebra such as matrix multiplication
Matrix Multiplication: a * b Matrix Right Division: a / b Matrix left Division: a \ b

%( a * inv(b) ) %( inv(a) * b)

MATLAB Symbols
. . . continue statement on next line , separate statements and data % start comment which ends at end of line ; (1)suppress output
(2)used as a row separator in a matrix

Specify range

Numeric Functions
sqrt(x) Calculates the square root of x mod(x, y) remainder or modulo function exp(x) e raise to power x log(x) natural logarithm base e ceil(x) rounds x to nearest integer towards +ve infinity fix(x) - rounds x to nearest integer towards Zero floor(x) - rounds x to nearest integer towards ve infinity round(x) Rounds x to the nearest integer Many more

Matrix Manipulation Function


Diag(x) Extract diagonal elements Rot90(x) Rotate matrix 90 degree tril(x) Extract lower triangular part triu(x) Extract upper triangular part det(x) Determinant of matrix rank(x) - No. of linearly independent rows or columns trace(x) sum of diagonal elements eig(x) Eigenvalues and eigenvectors Many more

Complex Variables
Complex number: c = a +bi Complex variable is created by assigning a complex value Operators:
+ * / \ : for addition : for subtraction : for multiplication : for right division : for left division

Functions for Complex Numbers


isreal(a) - returns 0 if a is complex number abs(a) - returns magnitude of complex value conj(a) - computes the complex conjugate real(a) - returns the real portion imag(a) - returns the imaginary portion Angle(a)- returns the angle of complex number

Solution of Simultaneous Equations


Scientific problems always seem to involve the solution of simultaneous linear equations. For a few equations (two or three at most) this may be done by hand. For more than three equations it is advisable to use a computer. MATLAB can solve such equations easily. For example: Solve for x1, x2, and x3 satisfying:

For example: solve linear equations for x1, x2, and x3


5x + 8y + 2z = 3 4x + 6y + 7z = 5 2x + 8y + 2z = 11

Solution:
a = [5 8 2; 4 6 7; 2 8 2]; b = [3; 5; 11]; X = [x; y; z]; X1 = a \ b;

MATLAB Graphics
MATLAB also provides a powerful set of graphics commands to create and manipulate graphics. Many commands can be entered from the Figure window. Advanced commands must be entered from the Command window or a script.

Simple Plots
plot(x,y) For example: x= 0:1:10; y=x.^210.*x+15; plot(x,y); title (Plot of y=x.^2-10.*x+15) xlabel(x) ylabel(y) grid on

Multiple Graphs
It is possible to plot multiple functions on the same graph. For Example:
x=0:0.1:6; y1 = sin(x); y2 = cos(x) plot(x,y1,'r--', x, y2, 'bo');