Вы находитесь на странице: 1из 8

INTRODUCTION TO MATLAB

Session-1&2

WHAT IS MATLAB?
• MATrix LABoratory
• Matrix is the basic data element
• Matrix CALCULATOR
WHY MATLAB?...
• Interactive Mathematical Calculations
• Simple programmability
• Easy to use integrated graphics (2D and 3D colour graphics)
• Numerous tool boxes covering a wide range of subjects
• Free availability of Student version

OPEN ARCHITECTURE / FEATURES


• Engine Services –MATLAB is used as computational engine in programs
developed in C or Fortran
• Dynamic linking – Runtime linking of C and Fortran Routines with MATLAB
m_files
• MATLAB C Compiler – Generates C code from MATLAB source files.
• SIMULINK – Graphical modeling, simulation and prototyping environment.
• Basic data element - Matrix
- Auto dimensioning
- Eliminates data type declarations
- Operator overloading
- Case sensitive
• Open Environment
• In- Built Functions
- Built into the Interpreter
• m-file functions
– ASCII files containing the algorithms
– Algorithms on specific topics as TOOL BOXES such as Control Systems,
Signal Processing, Neural Network, Fuzzy Logic, Communication, etc.
– USER functions (user can program using m-files)

REFERENCES

1. MATLAB users guide MathWorks, Inc.


2. Students edition of MATLAB users guide MathWorks, Inc.
3. D.M. Etter, Engineering problem solving with MATLAB, PH, 1997
home page: http://www.mathworks.com
Technical support: support@mathworks.com

1
ELEMENTARY MATRIX OPERATIONS
• Entering Arrays/Matrices with real elements
M = [first:increment:last] -----> Array with elements
M = linspace(first,last,n) -----> Array with n elements linearly spaced
M = logspace(first,last,n) -----> Array with n elements logarithmically spaced
M = [(2+4/5), sqrt(2.8), 4.2,7] -----> Array with 4 elements
M = [1 2 3; 4 5 6] OR M = [1,2,3; sqrt(2.8),5.2,5e-2] -----> 2×3 real matrices
• Entering matrices with complex elements
a = 2 + 5i ------> complex number
A = [5+3j 7+8j; 9+2j 6+5j] -----> 2×2 complex matrix
A = [1 2;3 4] + i*[5 6;7 8]
• Manipulations / Functions
- Given Matrix A (square)
A’ -----> Transpose of a matrix
inv(A) -----> inverse of a matrix
det(A) -----> determinant of a matrix
A*A -----> matrix multiplication
diag(A) -----> diagonal of a matrix
triu(A) , tril(A) , lu(A), eig(A), eigs(A), etc.

OPERATORS
• Arithmetic operators
+ Plus. - Minus.
* Matrix multiplication. .* Array multiplication
^ Matrix power .^ Array power
\ Backslash or left division / Slash or right division
./ Array division
• Relational operators
< less than <= Less than or equal to
> greater than >= Greater than or equal to
= equal ~= Not equal
• Logical operators
& AND | OR ~ NOT XOR Exclusive OR
• Array operations
Matrix operations preceded by a .(dot) indicates array operation.
• Simple math functions
sin, cos, tan, asin, acos, atan, sinh, cosh ...
log, log10, exp, sqrt …
• Range of numbers – 10-308 TO 10308

2
• Permanent variables
ANS Default result variable
EPS 2.22 x 10-16 user definable
PI π pre-calculated
INF 1/0
NAN Not A NumberEg. 0/0; inf/inf
• Special characters
() Parentheses are used to indicate precedence in arithmetic expressions and to
arguments of functions in the usual way.
[] Brackets ... Continuation
, Element separator ; Row, line delimiter
% Comments ! Exclamation point
' Transpose, quote = Assignment
: Colon
• Logical functions...
EXIST Check if variables or functions exist.
ANY True if any element of a vector is true.
ALL True if all elements of a vector are true.
FIND Find indices of the non-zero elements.
ISNAN True for Not-A-Number.
ISINF True for infinite elements.
FINITE True for finite elements.
ISEMPTY True for empty matrices.
ISREAL True for matrix of only real elements.
ISSPARSE True if matrix is sparse.
ISSTR True for text string.
ISGLOBAL True for global variables

• Flow control
1. FOR loop 2. IF statement 3. WHILE loop
for k = 1:m if condition1 while condition
…. …. ….
end else if condition2 end
….
Else
….
end
end

• Some useful commands

who whos clc clear load save pause help lookfor

3
How to run MATLAB
• First run windows
• Click on MATLAB 5.3 icon
• >> cd d:/students/<your directory>/<your working directory for MATLAB>
This will be your working directory, all the data files, m_script files will be stored
here.
Examples:
1. Elementary matrix operations
To Enter an Array
>>M = 0:1:5 = [0, 1, 2, 3, 4, 5]
>>M = linspace(1,5,3) = [1,3,5]
>>M = logspace(1,5,3) = [10,1000,100000]
>>M = [(2+4/5), sqrt(2.8), 4.2,7]
To Enter a matrix with real elements
>>M = [1 2 3; 4 5 6] >>M = [1,2,3; sqrt(2.8),5.2,5e-2]
To Enter matrix with complex elements
>>a = 2 + 5i
>>A = [5+3j 7+8j; 9+2j 6+5j]
>>A = [1 2;3 4] + i*[5 6;7 8]
• Manipulations / Functions
Given Matrix A = [1 2 9; 4 4 6;7 8 7]
B = [3 6 9;2 4 6;1 2 3],
>>A’ >>Inv(A) >> Det(A) >>A*B >>Diag(A)
>> Eig(A) >>rank(A) >>A.*B >>triu(A) >>tril(A)

Accessing submatices >>A(1:2,2:3); >>A(1,:); >>B(:,2)


Concatenating two matrices >>D=[A B]; >>E=[A;B]
Adding a row >>A(4,:)=[1 1 0]
Deleting acolumn >>B(:,2)=[ ]
>>A(3) is the third element of A.
>>A([1 2 3]) is the first three elements of A. So is
>>A([SQRT(2), SQRT(3), 4*ATAN(1)]).
If A has N components, >>A(N:-1:1) reverses them.
>>A([1,5],:) = A([5,1],:) interchanges rows 1 and 5 of A.

• Given an array A=[1 5 3 10 2 0 4 6], sort in ascending order.


>>sort(A)

• Matrix generation functions


>>[ ] Empty matrix
>>zeros(3) 3×3 matrix of zeros

4
>>ones(2) 2×2 matrix of ones
>>eye(3) identity matrix of size 3
>>rand(3) 3×3 matrix of random numbers
• Familiarise the following useful commands in the matlab command window
>>who lists variables in workspace
>>whos lists variables and their sizes
>>clc clear command window
>>clear clear workspace
>>save session1 to save variables of the workspace in session1.mat
>>load session1 to load variables to workspace
>> save myfile.dat a b –ascii saves a,b in myfile.dat in ascii format
>>help inv
>>lookfor inverse
>>disp(‘I have successfully completed MATLAB basics’)
>> R = input('How many apples') gives the user the prompt in the text string and then
waits for input from the keyboard.
• dot operators
Eg: A = [1 2 3];
B = [2 4 6];

C = A .* B = [1*2, 2*4, 3*6] ;


C = A ./ B = [1/2, 2/4, 3/6] ;
C = A.^2 = [1, 4, 9];
• display formats...
>>format Default. Same as SHORT
>>format short Scaled fixed point format with 5 digits.
Eg. 1.3333
>>format long Scaled fixed point format with 15 digits.
Eg. 1.33333333333333

• Polynomials
Consider the Polynomial
a(s) = s2 +2s + 3 and
b(s) = 4s2 + 5s + 6.
Matlab representation of a(s) and b(s) are
a = [1 2 3] and
b = [4 5 6]

c = CONV(a,b) CONVOLUTION OF a AND b


b = DECONV(c,a) DIVISION OF POLYNOMIALS
Roots of polynomial

5
p = s3 – 6s2 – 72s –27
p = [1, –6, –72, –27]
r = ROOTS(p) = [12.1229; -5.7345; -0.3884]
The polynomial can be got from the roots as
p = POLY(r)

¾ Creating script files


Editing a file : click on Menu File - New, invokes Windows Notepad editor.
Save file with some filename with extension .m Eg :- filename1.m
NOTE : DO NOT GIVE THE FILENAME WHICH IS A BUILTIN m_file.
Example : %ex1.m
clear, clc,
% To compute inverse of a matrix and Determinant
A = [1 2 9; 4 4 6;7 8 7];
disp(‘The inverse and determinant of matrix A is:’)
A_inverse = inv(A)
A_determinant = det(A)
Assignment:
1. Create a 5×5 random matrix A,
-Multiply all elements and round off the elements to integers [try fix]
-Find maximum and minimum element of the array and also its index
[try max,min]
-Replace all elements of A<10 with zeros [try find]
-Extrct all 30<=aij<=50in a new matrix B, i.e find all the elements of a that are
between 30 and 50 and put them in matrix B.
2. Read a matrix from a data file array.dat [try load]
-Determine if the matrix is an upper triangular matrix, then print upper triangular
matrix or not upper triangular matrix [try triu, any]
-Determine if the matrix is an lower triangular matrix, then print lower triangular
matrix or not lower triangular matrix [try tril, any]
-Determine if the matrix is a diagonal matrix, then print diagonal or not
diagonal.if the matrix is diagonal check if it is an identity matrix.
-Determine if the matrix is a symmetric matrix, then print symmetric or not
symmetric
SIMULINK Exercises

1. Generate a sinusoidal waveform of amplitude 100 and frequency 50 Hz.


2. Generate balanced 3-phase sinusoidal voltage waveforms .
3 Obtain the derivative of a sinusoidal signal.

6
Introduction to SIMULINK

1. General Information

SIMULINK is a toolbox extension of the Matlab program. It is a program for simulating


dynamical systems.Briefly, the steps of using SIMULINK involve first defining a model or
mathematical representation and the parameters of your system, picking a suitable integration method,
and setting up the run conditions, such as run time and initial conditions. In SIMULINK model
definition is facilitated by the graphical interface and the library of templates or function blocks that are
commonly used in mathematical descriptions of dynamic systems. As mentioned before, SIMULINK
has block libraries shown in Fig. 1: Continuous, Discrete, Functions &Tables, Math, Nonlinear,
Signal & Systems, Sources, Sinks, Discrete, Linear, Nonlinear and Connections. To find out the
properties in SIMULINK, please follow the steps given below:
• Start Matlab (Start/matlab): The Matlab program starts with a display indicating the version
of Matlab
program after which it will display the Matlab prompt >> in a Matlab command window.
• Type simulink after the Matlab propmt >> in the Matlab command window. You will see the
block libraries as shown in Fig.1 for MATLAB 5.3. Spend time on exploring the components in the
libraries.

Figure 1: SIMULINK Block Library Figure 2: Contents of the Continuous library block

7
Double clicking on a menu heading will open up a display of menu commands under that heading. For
example, if you are starting a new and want to create a new SIMULINK model, click the create a new
model box in Fig.1 to produce a blank SIMULINK model screen onto which you can then select and
drag components from the block library to assemble your SIMULINK simulation. Note that the screen
will initially be named Untitled until you give it a name using the save as menu command under the file
menu heading. The assigned filename is automatically appended with an .mdl extension.
A variety of function blocks or templates are grouped under different library blocks. A template can be
copied from a library block onto the SIMULINK model screen by first selecting the template and then
dragging it to the desired location in the SIMULINK model screen, or by a sequence of copy and paste
commands, which are found under the edit menu. The combined actions of selecting and dragging are
carried out by clicking on the desired template with left-most button, keeping that button depressed, and
moving the pointer to the desired location on the SIMULINK model screen.
To find out the templates of the each library block, please double-click the block. That will
display all the templates that the block has. For example, if you need derivatives and integrators, you
first open up the Continuous library block by double clicking on the icon of the continuous icon block
to display its contents. Figure 2 shows the contents of the continuous library block, in which you will
find the derivative, integrator, and many more components as shown in Fig. 2. Many templates have
internal parameters which you must specify before you use these templates in a simulation. To view or
set up these parameters, you must double-click on the template, upon which a dialog window will appear
with boxes for parameter values to be inserted.
2. How to Choose an Integration Method
Before you start any simulation, you will need to choose an integration method and specify some
run conditions. Under the parameters sub-menu of the main menu heading simulation, you can select
one of the several integration methods and enter the values of simulation parameters, such as tolerance
and minimum and maximum step size. This version of the SIMULINK has five ODE solvers : ode45,
ode23, ode113, ode15s, ode23t and ode23tb. You can find much more detailed information on these
integration methods in any numerical analysis book.

3. How to Run a Simulation


Other than the parameters for the integration method, you will also need to specify the start and stop time
of the run before you can start your simulation. The simulation can be starting by clicking on the Start
button under the main menu heading Simulation.

Вам также может понравиться