27-08-2011
Introduction to MATLAB
Dr. Suhas P. Deshmukh
Professor, Sinhagad Academy of Engineering, Kondhawa, Pune
Outline
Introduction Basic Operations using MATLAB
8/27/2011
MATLAB : Introduction
27-08-2011
MATLAB Introduction
MatLab : Matrix Laboratory Numerical Computations with matrices Why Matlab?
User Friendly (GUI) Easy to work with Powerful tools for complex mathematics Every number can be represented as matrix
8/27/2011
MATLAB : Introduction
MATLAB System
Desktop Tools and Development Environment
This part of MATLAB is the set of tools and facilities that help you use and become more productive with MATLAB functions and les. Many of these tools are graphical user interfaces. It includes:
8/27/2011
the MATLAB desktop and Command Window, an editor and debugger, a code analyzer, browsers for viewing help, the workspace, and les, and other tools.
MATLAB : Introduction 4
27-08-2011
MATLAB System
Mathematical Function Library
This library is a vast 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, fast Fourier transforms and many more
8/27/2011
MATLAB : Introduction
MATLAB System
The Language
The MATLAB language is a high-level matrix/array language with control ow statements, functions, data structures, input/output, and object-oriented programming features. It allows both programming in the small to rapidly create quick programs you do not intend to reuse. You can also do programming in the large to create complex application programs intended for reuse.
8/27/2011 MATLAB : Introduction 6
27-08-2011
MATLAB System
Graphics
MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. It includes high-level functions for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level functions that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications.
8/27/2011 MATLAB : Introduction 7
MATLAB System
External Interfaces
The external interfaces library allows you to write C and Fortran programs that interact with MATLAB.
It includes facilities for calling routines from MATLAB (dynamic linking), for calling MATLAB as a computational engine, and for reading and writing MAT-les.
External DAQ System can be interfaced for digital/analog Input Output
8/27/2011 MATLAB : Introduction 8
27-08-2011
Menus
MATLAB Window
View or change current directory
Files in work Directory
Workspace Window Command Window Move or resize window Command History
8/27/2011
MATLAB : Introduction
Essential Requirements
for successful Programming You need to learn the exact rules for writing MATLAB statements. You need to develop a logical plan of attack for solving particular problems Garbage in, garbage out.
If you give MATLAB a garbage instruction, you will get a garbage result. With experience, you will see that with MATLAB you can design, develop and implement computational and graphical tools to do relatively complex science and engineering problems.
8/27/2011
MATLAB : Introduction
10
27-08-2011
Arithmetic Operations
Since we have experience doing arithmetic, we want to examine if MATLAB does this correctly. When applying computer tools this is a required step to gain condence in the tool and in our ability to use the tool. Carry out simple arithmetic operations at command line as below >> 3+5 >> 5*10/2 >> 3^2+5^3+10/5 The line with the >> prompt is called the command line. Use of Backspace , Left-arrow , Right-arrow and Del keys. Use of Up-arrow and Down-arrow
MATLAB : Introduction 11
8/27/2011
Arithmetic Operations
Assign values to variable to do arithmetic operations
>> a=5 >> b=10 >> c=(a+b)/a etc
MATLAB has all of the usual mathematical functions that are on a scientic-electronic calculator, like sin, cos, log
Carry out simple trigonometric operations and verify
MATLAB has numerous general functions such as date, calendar, clc, clear, who, whos etc
8/27/2011
MATLAB : Introduction
12
27-08-2011
Simple Command Prompt Operations
Arithmetic
25 2 1 5 1 3 ( 5 1) 2
5
Operations 2 ^ 5 / ( 2 ^ 5 - 1) 3 * (sqrt(5) -1) / (sqrt(5) +1) ^ 2 1.0323 -0.6459
Exponential and Logarithmic
log10 (e3 )
Trigonometric 2 2
sin 6 cos 6
log10(exp(3))
3.0000
(sin( pi / 6))^2 + (cos( pi / 6))^2
1.0000
Complex Number
1 3i 1 3i
(1 + 3i) / ( 1 3i) exp( i * pi / 4)
MATLAB : Introduction
-0.800 + 0.600 i 0.7071 + 0.7071 i
13
e
8/27/2011
Precedence of Arithmetic Operations
Precedence 1 2 3 Operator Parentheses (round brackets) Power, left to right Multiplication and division , left to right
Addition and Subtraction, left to right
8/27/2011
MATLAB : Introduction
14
27-08-2011
Infinity and Not-A-Number
MATLAB is sensible about anticipating some errors; it warns you in case you didnt realize you were dividing by zero, but still gives the answer Inf. If you insist on using in a calculation, which you may legitimately wish to do, type the symbol Inf (short for innity), e.g. try 13+Inf and 29/Inf. Another special value that you may meet is NaN, which stands for Not-a-Number. It is the answer to calculations like 0/0.
8/27/2011
MATLAB : Introduction
15
Variables and the Workspace
Variables are fundamental to programming. In a sense, the art of programming is
getting the right values in the right variables at the right time.
A variable name must comply with following rules:
It may consist only of the letters az, the digits 09 and the underscore ( _ ). It must start with a letter. MATLAB is case sensitive, Give name to variable which is easily distinguishable
8/27/2011
MATLAB : Introduction
16
27-08-2011
General Commands
Online help
help topic lookfor string demo who whos size clear WP) clc list topics on which help is available lists help topics containing string runs the demo program lists variable currently in workspace lists variable currently in workspace with their clears workspace (deletes all variables from clears command window returns a current date and time vector creates a directory lists contents of current directory
MATLAB : Introduction 17
Workspace Information
General Information
clock mkdir ls
8/27/2011
Arrays: Vectors and Matrices
A vector is a special type of matrix, having only one row, or one column. Vectors are also called lists or arrays in other programming languages. A matrix is a rectangular object (e.g. a table) consisting of rows and columns.
8/27/2011
MATLAB : Introduction
18
27-08-2011
Entering Matrices Direct entry
4 ways of entering matrices in MATLAB:
Enter an explicit list of elements Load matrices from external data files Generate matrices using built-in functions Create matrices with your own functions in M-files
Rules of entering matrices:
Separate the elements of a row with blanks or commas Use a semicolon ; to indicate the end of each row Surround the entire list of elements with square brackets, [ ]
To enter matrix, simply type: A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
8/27/2011
MATLAB : Introduction
19
Defining a Array
Explicit list of elements Array Variables
Variable x can be defined as a row vector by specifying its elements as below X=[0 , 0.1 , 0.2 , 0.3 , 0.4 , 0.5] ;
Variable x Elements Separation either by blank space or comma Simicolon decides output, remove semicolon output will appear on screen
Elements of variable
8/27/2011
MATLAB : Introduction
20
10
27-08-2011
Defining Array
Initializing vectors: the colon operator
Starting Number
>> x = 1 :
Variable Name
10
End Number
1 as default increment
Colon operator for increment
>> x = 1
Increment of +0.5
0.5 :
Positive increment
>> x =
Increment of -1
8/27/2011
10 :
-1
Negative increment
MATLAB : Introduction
21
Defining Array
Initializing vectors: linspace, rand etc. functions
linspace Function : Linearly spaced vector
>> x = linspace( start_no, end_no, no_of_divisions) >> x = linspace(0, pi/2, 10)
rand function: Uniformly distributed pseudorandom numbers >> x = rand( row_nos, col_nos) >> x = rand(1,7)
8/27/2011
MATLAB : Introduction
22
11
27-08-2011
Defining a Matrix
Explicit list of elements
Matrix Variables
Matrix X can be defined as a row vector by specifying its elements as below Variable X X =[1 2 3 ; 1 2 3 ; 1 2 3] ;
Second Row First Row Next Row by ;
8/27/2011
MATLAB : Introduction
23
Defining MATRIX
Inbuilt Functions
eye Function : Identity matrix >> x = eye(row_nos, col_nos) >> x = eye(5, 5) zero Function : Zeros array (M-by-N matrix of zeros) >> x = zero(row_nos, col_nos) >> x = zero(5, 5) ones Function : Ones array (M-by-N matrix of ones) >> x = ones(row_nos, col_nos) >> x = ones(5, 5)
8/27/2011
MATLAB : Introduction
24
12
27-08-2011
>> help elmat Functions
Elementary Matrices zeros ones
Elementary matrices and matrix manipulation
Zeros Array / Matrices Ones array / matrices
eye
linspace repmat logspace freqspace meshgrid
Indentity Matrix
Linearly spaced vector Replicate and tile array Logarithmically spaced vector Frequency spacing for frequency response X & Y arrays for 3D plots
8/27/2011
MATLAB : Introduction
25
>> help elmat Functions
Basic array information
Elementary matrices and matrix manipulation
size
length ndims numel disp isempty isequal isequalwithequalnans
Size of array
Length of vector Number of dimensions Number of elements Display matrix or text True for empty array True if arrays are numerically equal True if arrays are numerically equal.
8/27/2011
MATLAB : Introduction
26
13
27-08-2011
>> help elmat Functions
Matrix manipulation cat reshape
Elementary matrices and matrix manipulation
Concatenate arrays Reshape array
diag
blkdiag tril flipplr rot90 end
Diagonal matrices and diagonals of matrix
Block diagonal concatenation Extract lower triangular part Flip matrix in left / right direction Rotate matrix 90 degrees Last index
8/27/2011
MATLAB : Introduction
27
>> help elmat Functions
Special Variables and constants
Elementary matrices and matrix manipulation
ndgrid
permute ipermute Shiftdim circshift Squeeze isscalar isvector
8/27/2011
Generate arrays of N-D function
Permute array dimensions Inverse permute array dimensions Shift dimensions Shaft array circularly Remove singleton dimensions True for scalar True for vector
MATLAB : Introduction 28
Array Utility Functions
14
27-08-2011
>> help elmat Functions
Multi-dimensional array functions eps Floating point relative accuracy realmax Largest positive floating point realmin intmax inmin pi
8/27/2011
Elementary matrices and matrix manipulation inf nan isnan isinf isfinit e i&j Infinity Not a number True for not a number True for infinite elements True for finite elements Imaginary unit
29
Smallest positive floating point Largest positive integer value Smallest integer value 3.1415926535897....
MATLAB : Introduction
>> help elfun (Functions)
Trignometric Functions
sin, cos, tan, sinh, cosh, tanh, etc
Exponential Functions
exp, log, log10, log2, realpow, reallog, sqrt, nthroot etc
Complex Functions
abs, angle, complex, conj, imag, real, etc
Rounding and reminder Functions
fix, floor, ceil, round, rem, mod, sign etc
8/27/2011
MATLAB : Introduction
30
15
27-08-2011
>> help specfun
Specialized math functions. Specialized math functions Math Functions airy besselj, bessely, besselh beta etc gamma etc legendre etc cross dot
8/27/2011
Number theoretic functions factor isprime, primes gcd (),lcm rat factorial
Coordinate transforms cart2sph cart2pol pol2cart sph2cart hsv2rgb rgb2hsv
MATLAB : Introduction
31
Matrix Manipulations
Transpose of Matrix >> A = rand(3,3) >> A = rand(3,3) >> B = A >> B = det(A) Dash Operator Dash Operator Determinant of Matrix
Multiplication of Matrix >> C = A * B Eigen Values and Eigen Vectors Dash * Operator
>> A = [0 1;0 -1]; >> [V,L] = eig(A)
Inverse of Matrix
eig function inv function
32
>> A = [0 1;0 -1]; >> B= inv(A)
8/27/2011 MATLAB : Introduction
16
27-08-2011
Matrix Manipulations
The colon operator >> A=magic(3,3) >> A (2:3, 1:2) Deleting rows & columns >> a ( :, 2) = [] >> a ( 1, 2) = [] Sum of elements of matrix >> A=fix(10*rand(3,3)) >> sum (A) Colon : Operator Deletes 2nd column of a Deletes single element of a Colon : Operator
8/27/2011
MATLAB : Introduction
33
Thank You
Tutorials (20 Problems for 60 min ) Plz solve problems from tutorials
8/27/2011
MATLAB : Introduction
34
17