Upload
anon639135002
View
165
Download
5
Tags:
Embed Size (px)
DESCRIPTION
Intoduction to matlab,by Dr.SP Simon,NIT Trichy
Citation preview
INTRODUCTION TO MATLAB
Presented by:
S P SIMON
DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERINGNATIONAL INSTITUTE OF TECHNOLOGY
TIRUCHIRAPPALLI-620 015
04/08/23 S.P.Simon-EEE-NITT 2
CONTENTS
DESKTOP TOOLS AND DEVELOPMENT ENVIRONMENT
BASIC PROGRAMMING
INTRODUCTION TO MATLAB ENVIRONMENT
MATHEMATICS
GRAPHICS
INTRODUCTION TO SIMULINK
MATLAB TOOL BOXES
04/08/23 S.P.Simon-EEE-NITT 3
INTRODUCTION TO MATLAB ENVIRONMENT
What is MATLAB? A language for technical computing An interactive system whose basic data element is a matrix MATLAB stands for MATrix LABoratory
Typical Uses Math and computation Algorithm development Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development including GUI
INTRODUCTION TO MATLAB ENVIRONMENT
04/08/23 S.P.Simon-EEE-NITT 4
Development Environment: This is the set of tools and facilities that help you use MATLAB functions and files. Many of these tools are graphical user interfaces. It includes the MATLAB desktop and Command Window, a command history, an editor and debugger, and browsers for viewing help, the workspace, files, and the search path.
The MATLAB Mathematical Function Library: This 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 eigen values, Bessel functions, and fast Fourier transforms.
The MATLAB Language: This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. It allows both "programming in the small" to rapidly create quick and dirty throw-away programs, and "programming in the large" to create large and complex application programs.
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.
The 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.
THE MATLAB SYSTEM
INTRODUCTION TO MATLAB ENVIRONMENT
04/08/23 S.P.Simon-EEE-NITT 5
DESKTOP TOOLS AND DEVELOPMENT ENVIRONMENT
INTRODUCTION TO MATLAB ENVIRONMENT
04/08/23 S.P.Simon-EEE-NITT 6
Start Matlab from the “start” menu
The command window is the dynamic command interpreter which allows the user to issue Matlab commands
The variable browser shows which variables currently exist in the workspace
The command history shows which commands have been executed in the past
Variable browser
Commandwindow
Command history
INTRODUCTION TO MATLAB ENVIRONMENT
04/08/23 S.P.Simon-EEE-NITT 7
CREATING MATLAB SCRIPTS Commands can be typed directly into the command
window (like a calculator), or they can be grouped together into a script file (or function)
A script is a text file with a “.m” extension (remember to change to your directory before doing any work cd p:/matlab)
A script file can be created using the Matlab editor edit TestScript.m
Just type the commands into the file
The script can be run by typing the name of the script in the command window (or press F5)
TestScript Any variables created in the script will be visible in
the workspace which are viewed in the variable browser
INTRODUCTION TO MATLAB ENVIRONMENT
04/08/23 S.P.Simon-EEE-NITT 8
WORKSPACE
workspace = the area of memory used by the MATLAB who = lists the current variables in the workspace clear = clear the workspace save = save the workspace variables to a file. load = load all variables from a specified file.
save my.dat clear clc who load my.dat -mat who
INTRODUCTION TO MATLAB ENVIRONMENT
04/08/23 S.P.Simon-EEE-NITT 9
MATRICES IN MATLAB
MATRICES GENERATION
eye - Identity matrix
ones - Matrix with all elements = 1
Contd..
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 10
rand – Random matrix zeros - Matrix with all elements = 0
Matrix Index Always starts with 1 (not 0)
Given:
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 11
MATRICES OPERATIONS
Given A and B:
Addition Subtraction Product Transpose
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 12
THE USE OF “.” – “ELEMENT” OPERATION
Given A:
Divide each element of A by 2
Multiply each element of A by 3
Square each element of A
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 13
USEFUL FUNCTIONS
Function Description
rank Matrix rank
det Determinant
null Null space
\ and / Linear equation solution
inv Matrix inverse
eig Eigenvalues and eigenvectors
poly Characteristic polynomial
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 14
Given B:
Inverse of B Determinant of B Eigenvalues of B
EXAMPLES
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 15
GET HELP FOR USE OF FUNCTIONS
>>help function_name
>>lookfor keyword
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 16
SOLVING LINEAR EQUATIONS
Given A and B:
Solve for X, s.t. AX = B Check that AX = B
Note: X = A\B denotes AX = B, X = B/A denotes XA = B
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 17
USE OF M FILE
Click to create a new M-File
Extension “.m” A text file containing script or function or program to run You can run more than 1 line of commands at a time
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 18
M-FILE AS SCRIPT FILESave file as filename.m
Type what you want to do, eg. Create matrices
If you include “;” at the end of each statement,result will not be shown immediately
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 19
RUN THE M-FILE
Run the file by typing the filename in the command window
That’s because the file path is not defined
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 20
TO ADD PATHRUN THE M-FILE
Add Folder…
Select the folder where you placed your M-File
File – Set Path…
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 21
RUN AGAIN
Notice that the statement thatdoes not have “;” at the end willhave the result shown immediately
Type the M-File name again
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 22
RUN AGAIN 2
If you want to see the values ofthe statement that has “;” at the end,simply type the valuable name and press Enter
MATHEMATICS
04/08/23 S.P.Simon-EEE-NITT 23
BASIC PROGRAMMING
COMMANDS PARSED & EXECUTED IN ORDER
% Comments start with "%" character
pause % Suspend execution - hit any key to continue.
keyboard % Pause & return control to command line.
% Type "return" to continue.
break % Terminate execution of current loop/file.
return % Exit current function
% Return to invoking function/command line.
% Comments start with "%" character
pause % Suspend execution - hit any key to continue.
keyboard % Pause & return control to command line.
% Type "return" to continue.
break % Terminate execution of current loop/file.
return % Exit current function
% Return to invoking function/command line.
FLOW CONTROL CONSTRUCTS Logic Control:
IF / ELSEIF / ELSE SWITCH / CASE / OTHERWISE
Iterative Loops: FOR WHILE
04/08/23 S.P.Simon-EEE-NITT 24
BASIC PROGRAMMING
THE IF, ELSEIF AND ELSE STATEMENTS
Works on Conditional statements
Short-circuited in MATLAB - once a condition is true, the sequence terminates.
»if_examp
i, j = imaginary unit ※ Don't use i or j as a variable except for-loop index!!!
04/08/23 S.P.Simon-EEE-NITT 25
SWITCH, CASE, AND OTHERWISE
BASIC PROGRAMMING
More efficient than elseif statements
Only the first matching case is executed
switch input_numcase -1
input_str = 'minus one';case 0
input_str = 'zero';case 1
input_str = 'plus one';case {-10,10} input_str = '+/- ten';otherwise
input_str = 'other value';end
switch input_numcase -1
input_str = 'minus one';case 0
input_str = 'zero';case 1
input_str = 'plus one';case {-10,10} input_str = '+/- ten';otherwise
input_str = 'other value';end
& | ~
Logical operators
< <= > >= == ~= true = 1 false = 0
Relational operators
04/08/23 S.P.Simon-EEE-NITT 26
THE FOR LOOP
Similar to other programming languages
Repeats loop a set number of times (based on index)
Can be nested
N=10;for I = 1:N
for J = 1:N A(I,J) = 1/(I+J-1);
endend
N=10;for I = 1:N
for J = 1:N A(I,J) = 1/(I+J-1);
endend
BASIC PROGRAMMING
04/08/23 S.P.Simon-EEE-NITT 27
THE WHILE LOOP
Similar to other programming languages
Repeats loop a set number of times (based on index)
Can be nested
I=1; N=10;while I<=N
J=1;while J<=N
A(I,J)=1/(I+J-1);J=J+1;
endI=I+1;
end
I=1; N=10;while I<=N
J=1;while J<=N
A(I,J)=1/(I+J-1);J=J+1;
endI=I+1;
end
BASIC PROGRAMMING
04/08/23 S.P.Simon-EEE-NITT 28
Using Array Operations:
Using Loops:
ARRAY OPERATION
Density = Mass(I,J)/(Length.*Width.*Height);Density = Mass(I,J)/(Length.*Width.*Height);
[rows, cols] = size(M); for I = 1:rows
for J = 1:cols Density(I,J) = M(I,J)/(L(I,J)*W(I,J)*H(I,J));
endend
[rows, cols] = size(M); for I = 1:rows
for J = 1:cols Density(I,J) = M(I,J)/(L(I,J)*W(I,J)*H(I,J));
endend
»array_vs_loops
BASIC PROGRAMMING
04/08/23 S.P.Simon-EEE-NITT 29
BASIC PROGRAMMING
M-FILE FUNCTIONS
Function name has the same constraints as variable name ONE function in ONE file cf) subfunction file name > function name The name of the M-file and of the function SHOULD be the same
Function name resolution Check to see if the name is a variable Check to see if the name is a subfunction Check to see if the name is a function on the current directory Check to see if the name is a function on the MATLAB search path
04/08/23 S.P.Simon-EEE-NITT 30
function y = mean(x)% MEAN Average or mean value.
% For vectors, MEAN(x) returns the mean value.
% For matrices, MEAN(x) is a row vector
% containing the mean value of each column.
[m,n] = size(x);
if m == 1
m = n;
end
y = sum(x)/m;
function y = mean(x)% MEAN Average or mean value.
% For vectors, MEAN(x) returns the mean value.
% For matrices, MEAN(x) is a row vector
% containing the mean value of each column.
[m,n] = size(x);
if m == 1
m = n;
end
y = sum(x)/m;
Keyword: function Function Name (same as file name .m)Output Argument(s) Input Argument(s)
Online Help
MATLABCode
»output_value = mean(input_value) Command Line Syntax
STRUCTURE OF A FUNCTION M-FILE
BASIC PROGRAMMING
04/08/23 S.P.Simon-EEE-NITT 31
local and global variables
save as tg.m Declare the variable as global in every function that requires access to it Issue the global command at the top of the M-file (Recommended!!)
function value=tg(x, y) global Z x1 = x^2; y1 = y^2; Z1 = Z^2 value=x1+y1+z1; return
global Z x = 3; y = 4; Z= 5; tg(x, y) x, y, Z
save as test.m and run test!
M-FILE FUNCTIONS
BASIC PROGRAMMING
04/08/23 S.P.Simon-EEE-NITT 32
eval and feval
eval : execute the contents of bracket in command window
for n = 1:12 eval(['M' num2str(n) ' = magic(n)']) end
for n = 0:pi/10:pi m=feval('sin',n); disp([n m]) end
feval : evaluate function by function name and argument(s) in bracket
M-FILE FUNCTIONS
BASIC PROGRAMMING
04/08/23 S.P.Simon-EEE-NITT 33
BASIC 2-D GRAPHICS
Creating a Plot
plot(x, y) = produces a 2D graph of y vs. x
figure = open a new figure window hold on/off = allows you to add plots to an existing graph ans = the variable which stores the results of most recent answer
t = 0:pi/100:2*pi; y = sin(t); plot(t, y)
figure y2 = sin(t - 0.25); plot(t, y2) hold on plot(t, y+y2)
GRAPHICS
04/08/23 S.P.Simon-EEE-NITT 34
plot Command
plot(x1, y1, x2, y2, ...)
plot(x1, y1, 'color_style_marker', x2, y2, 'color_style_marker, ...) color_style_marker = a 1/2/3 character string. color = c, m, y, r, g, b, w, k style = -, --, :, -., none marker = +, o, *, x
y3 = sin(t - 0.5); plot(t, y, t, y2, t, y3)
plot(t, y, 'c--', t, y2, 'r.')
BASIC 2-D GRAPHICS
GRAPHICS
04/08/23 S.P.Simon-EEE-NITT 35
Subplots
clf = clear the current figure window subplot = display multiple plots in the same window
clf y4 = cos(t); subplot(2, 2, 1); plot(t, y) subplot(2, 2, 2); plot(t, y2) subplot(2, 2, 3); plot(t, y3) subplot(2, 2, 4); plot(t, y4)
BASIC 2-D GRAPHICS
GRAPHICS
04/08/23 S.P.Simon-EEE-NITT 36
Axes
grid on = draw the grid lines axis([xmin xmax ymin ymax]) = set scaling for the axes xlabel/ylabel = adds text beside the X-axis/Y-axis
clf t = -pi:pi/100:pi; y = sin(t); plot(t, y) grid on axis([-pi pi -1 1]) xlabel('\pi \leq \itt \leq \pi') ylabel('sin(t)')
BASIC 2-D GRAPHICS
GRAPHICS
04/08/23 S.P.Simon-EEE-NITT 37
plot3(x,y,z) plots x,y,z in 3-dimentional space
t=(0:pi/10:8*pi); x=exp(-t/20).*cos(t); y=exp(-t/20).*sin(t); z=t; figure(1); plot3(x,y,z); xlabel('x'); ylabel('y'); zlabel('z');
view(20,70); view(2); view(3);
Specifies the viewing point in 3-dimentional plot
view(Az,El)
BASIC 3-D GRAPHICS
GRAPHICS
04/08/23 S.P.Simon-EEE-NITT 38
meshgrid(x,y) generates domain for plotting
x=(-5:0.2:5); y=(-5:0.2:5); [X,Y] = meshgrid(x,y); Z= X .* exp(-X.^2 - Y.^2); size(X); size(Y); size(Z);
mesh(Z); mesh(X,Y,Z);
plots colored meshed 3-D graph
mesh(Z)
BASIC 3-D GRAPHICS
GRAPHICS
04/08/23 S.P.Simon-EEE-NITT 39
surf plots 3-d surface graphs
surf(X,Y,Z)
[cs,h]=contour(Z) clabel(cs,h); colorbar;
plots 3-d surface graphs
contour
BASIC 3-D GRAPHICS
GRAPHICS
04/08/23 S.P.Simon-EEE-NITT 40
INTRODUCTION TO SIMULINK
Simulink is a graphical, “drag and drop” environment for building continuous time signal and system simulations.
It allows users to concentrate on the structure of the problem, rather than having to worry (too much) about a programming language.
The parameters of each signal and system block is configured by the user (right click on block)
Signals and systems are simulated over a particular time.
SIMULINK
04/08/23 S.P.Simon-EEE-NITT 41
STARTING SIMULINK
SIMULINK
Type the following at the Matlab command prompt simulink
The Simulink library will appear Note that you can also start Simulink by clicking on the icon on the Matlab toolbar Select
File – New Model To create a new area (model) to build signals and systems
04/08/23 S.P.Simon-EEE-NITT 42
SIGNALS IN SIMULINK
There are two main libraries for manipulating signals in Simulink:
Sources: generate a signal Sinks: display, read or store a signal
SIMULINK
04/08/23 S.P.Simon-EEE-NITT 43
CREATE AND VIEW A CONTINUOUS TIME SIGNAL
Drag Sine Wave source and Scope sink onto the new Simulink Model and connect them (click on Sine Wave block, hold down Ctrl and click on the Scope)
Modify Sine Wave parameters to 2 rad/sec, by right clicking on Sine Wave block and selecting Sin Parameters, and modify frequency
Run the simulationSimulation - Start
Open the scope and leave open while you change parameters (Sine Wave or Simulation Parameters) and re-run
You can save the simulation using File - Save
SIMULINK
04/08/23 S.P.Simon-EEE-NITT 44
MATLAB TOOLBOXES/BLOCK SETS
Simulink Version 6.1 (R14SP1) Aerospace Blockset Version 1.6.1 (R14SP1) Bioinformatics Toolbox Version 1.1.1 (R14SP1) CDMA Reference Blockset Version 1.1 (R14SP1) Communications Blockset Version 3.0.1 (R14SP1) Communications Toolbox Version 3.0.1 (R14SP1) Control System Toolbox Version 6.1 (R14SP1) Curve Fitting Toolbox Version 1.1.2 (R14SP1) Data Acquisition Toolbox Version 2.5.1 (R14SP1) Database Toolbox Version 3.0.1 (R14SP1) Datafeed Toolbox Version 1.6 (R14SP1) Embedded Target for Infineon C166 Microcontrollers Version 1.1.1 (R14SP1) Embedded Target for Motorola HC12 Version 1.1.1 (R14SP1) Embedded Target for Motorola MPC555 Version 2.0.1 (R14SP1) Embedded Target for OSEK VDX Version 1.1.1 (R14SP1) Embedded Target for TI C2000 DSP(tm) Version 1.1.1 (R14SP1) Embedded Target for TI C6000 DSP(tm) Version 2.2.1 (R14SP1) Excel Link Version 2.2.1 (R14SP1) Extended Symbolic Math Version 3.1.1 (R14SP1) Filter Design HDL Coder Version 1.1 (R14SP1) Filter Design Toolbox Version 3.1 (R14SP1) Financial Derivatives Toolbox Version 3.0.1 (R14SP1)
TOOLBOXES
04/08/23 S.P.Simon-EEE-NITT 45
MATLAB TOOLBOXES/BLOCK SETS
TOOLBOXES
Financial Time Series Toolbox Version 2.1.1 (R14SP1)Financial Toolbox Version 2.4.2 (R14SP1)Fixed-Income Toolbox Version 1.1 (R14SP1)Fixed-Point Toolbox Version 1.1 (R14SP1)Fuzzy Logic Toolbox Version 2.2 (R14SP1)GARCH Toolbox Version 2.0.1 (R14SP1)Gauges Blockset Version 2.0 (R14SP1)Genetic Algorithm Direct Search Toolbox Version 1.0.2 (R14SP1)Image Acquisition Toolbox Version 1.7 (R14SP1)Image Processing Toolbox Version 5.0.1 (R14SP1)Instrument Control Toolbox Version 2.1 (R14SP1)Link for Code Composer Studio Version 1.3.2 (R14SP1)Link for ModelSim Version 1.2 (R14SP1)MATLAB Builder for COM Version 1.1.2 (R14SP1)MATLAB Builder for Excel Version 1.2.2 (R14SP1)MATLAB Compiler Version 4.1 (R14SP1)MATLAB Report Generator Version 2.1.1 (R14SP1)MATLAB Web Server Version 1.2.3 (R14SP1)Mapping Toolbox Version 2.0.3 (R14SP1)Model Predictive Control Toolbox Version 2.1 (R14SP1)Model-Based Calibration Toolbox Version 2.1.2 (R14SP1)Neural Network Toolbox Version 4.0.4 (R14SP1)OPC Toolbox Version 1.1.1 (R14SP1)Optimization Toolbox Version 3.0.1 (R14SP1)Partial Differential Equation Toolbox Version 1.0.6 (R14SP1)
04/08/23 S.P.Simon-EEE-NITT 46
MATLAB TOOLBOXES/BLOCK SETS
TOOLBOXES
RF Blockset Version 1.0.2 (R14SP1)RF Toolbox Version 1.0.1 (R14SP1)Real-Time Windows Target Version 2.5.1 (R14SP1)Real-Time Workshop Version 6.1 (R14SP1)Real-Time Workshop Embedded Coder Version 4.1 (R14SP1)Robust Control Toolbox Version 3.0 (R14SP1)Signal Processing Blockset Version 6.0.1 (R14SP1)Signal Processing Toolbox Version 6.2.1 (R14SP1)SimMechanics Version 2.2.1 (R14SP1)SimPowerSystems Version 4.0 (R14SP1)Simulink Accelerator Version 6.0.1 (R14SP1)Simulink Control Design Version 1.1 (R14SP1)Simulink Fixed Point Version 5.0.1 (R14SP1)Simulink Parameter Estimation Version 1.1 (R14SP1)Simulink Report Generator Version 2.1.1 (R14SP1)Simulink Verification and Validation Version 1.0.1 (R14SP1)Spline Toolbox Version 3.2.1 (R14SP1)Stateflow Version 6.1 (R14SP1)Stateflow Coder Version 6.1 (R14SP1)Statistics Toolbox Version 5.0.1 (R14SP1)Symbolic Math Toolbox Version 3.1.1 (R14SP1)System Identification Toolbox Version 6.1 (R14SP1)Virtual Reality Toolbox Version 4.0.1 (R14SP1)Wavelet Toolbox Version 3.0.1 (R14SP1)xPC Target Version 2.6.1 (R14SP1)xPC Target Embedded Option Version 2.6.1 (R14SP1)
04/08/23 S.P.Simon-EEE-NITT 47