bs lab_demo
TRANSCRIPT
-
8/12/2019 BS Lab_Demo
1/62
P. Srikanth, Associate Professor, ECE. 1
Basic Simulation Using
MATLAB
-
8/12/2019 BS Lab_Demo
2/62
P. Srikanth, Associate Professor,ECE.
2
MATLAB Overview
What is MATLAB?
History of MATLAB
Who developed MATLAB Why MATLAB was developed
Who currently maintains MATLAB
Strengths of MATLAB Weaknesses of MATLAB
-
8/12/2019 BS Lab_Demo
3/62
P. Srikanth, Associate Professor,ECE.
3
What is MATLAB?
MATLAB
MATrix LABoratory
Interactive system
Programming language
-
8/12/2019 BS Lab_Demo
4/62
P. Srikanth, Associate Professor,ECE.
4
What is MATLAB cont: 2
Considering MATLAB at home
Standard edition
Available for roughly 2 thousand dollars
Student edition
Available for roughly 1 hundred dollars.
Some limitations, such as the allowable size of amatrix
-
8/12/2019 BS Lab_Demo
5/62
P. Srikanth, Associate Professor,ECE.
5
What is MATLAB? Cont: 3
MATLAB is a tool for doing numerical
computations with matrices and vectors. It is
very powerful and easy to use. It integratescomputation, graphics and programming in the
same environment.
-
8/12/2019 BS Lab_Demo
6/62
P. Srikanth, Associate Professor,ECE.
6
History of MATLAB
Ancestral software to MATLAB
Fortran subroutines for solving linear
(LINPACK) and eigenvalue (EISPACK)
problems
Developed primarily by Cleve Moler in the
1970s
-
8/12/2019 BS Lab_Demo
7/62
P. Srikanth, Associate Professor,ECE.
7
History of MATLAB, cont: 2
Later, when teaching courses in
mathematics, Moler wanted his students to
be able to use LINPACK and EISPACK
without requiring knowledge of Fortran
MATLAB developed as an interactive
system to access LINPACK and EISPACK
-
8/12/2019 BS Lab_Demo
8/62
P. Srikanth, Associate Professor,ECE.
8
History of MATLAB, cont: 3
MATLAB gained popularity primarily
through word of mouth because it was not
officially distributed
In the 1980s, MATLAB was rewritten in C
with more functionality (such as plotting
routines)
-
8/12/2019 BS Lab_Demo
9/62
P. Srikanth, Associate Professor,ECE.
9
History of MATLAB, cont: 4
The Mathworks, Inc. was created in 1984
The Mathworks is now responsible for
development, sale, and support for
MATLAB
The Mathworks is located in Natick, MA
-
8/12/2019 BS Lab_Demo
10/62
P. Srikanth, Associate Professor,ECE.
10
Strengths of MATLAB
MATLAB is relatively easy to learn
MATLAB code is optimized to be relativelyquick when performing matrix operations
MATLAB may behave like a calculator oras a programming language
MATLAB is interpreted, errors are easier
to fix Although primarily procedural, MATLAB
does have some object-oriented elements
-
8/12/2019 BS Lab_Demo
11/62
P. Srikanth, Associate Professor,ECE.
11
Weaknesses of MATLAB
MATLAB is NOT a general purpose
programming language
MATLAB is an interpreted language
(making it for the most part slower than a
compiled language such as C++)
MATLAB is designed for scientific
computation and is not suitable for some
things (such as parsing text)
-
8/12/2019 BS Lab_Demo
12/62
P. Srikanth, Associate Professor,ECE.
12
FORTRAN:
real*8 A(10,10), B(10,10), C(10,10)
do i=1,10do j=1,10
C(i,j) = A(i,j) + B(i,j)
10 continue20 continue
MATLAB:
C = A + B
-
8/12/2019 BS Lab_Demo
13/62
P. Srikanth, Associate Professor,ECE.
13
Matrix
MATLAB works with essentially only one
kind of objecta rectangular numerical
matrix with possible complex entries.
-
8/12/2019 BS Lab_Demo
14/62
P. Srikanth, Associate Professor,ECE.
14
Entering a matrix
Matrices can be
Entered manually
Generated by built-in functions
-
8/12/2019 BS Lab_Demo
15/62
P. Srikanth, Associate Professor,ECE.
15
An example
A = [1, 2, 3; 7, 8, 9]
Use ; to indicate the end of each row
Use comma to separate elements of a row
-
8/12/2019 BS Lab_Demo
16/62
P. Srikanth, Associate Professor,ECE.
16
Matrix operations
+addition
-subtraction
*multiplication^power
transpose
To make *and ^operate element-by-
element, we write .*and .^
-
8/12/2019 BS Lab_Demo
17/62
P. Srikanth, Associate Professor,ECE.
17
Example
A= [1, 2; 3, 4]
B = [0.5, 0.6; 1, 1.5]
C = A*B
C = A.*B
-
8/12/2019 BS Lab_Demo
18/62
P. Srikanth, Associate Professor,ECE.
18
Subscripts
The element in row i and column j of A is
denoted by A(i, j).
Example: A = zeros(2,2);
A(1,1) + A(1,2) + A(2,2)
-
8/12/2019 BS Lab_Demo
19/62
P. Srikanth, Associate Professor,ECE.
19
The colon operator
The colon :is one of MATLAB s mostimportant operators. It has many uses.
3:-2:-11is a row vector containing integersfrom 3 to -11 with a increment of -2.
Subscript expressions involving colons referto portions of a matrix. A(1:3, 2)is the first tothe third elements of the second column of
A.
-
8/12/2019 BS Lab_Demo
20/62
P. Srikanth, Associate Professor,ECE.
20
Working with matrices
MATLAB provides four functions thatgenerate basic matrices.
zeros: all zeros. A = zeros(1,3)
ones: all ones. A = ones(2,4)
rand: uniformly distributed random
numbers. A = rand(3,5)randn: normally distributed random
numbers. A = randn(2,2)
-
8/12/2019 BS Lab_Demo
21/62
P. Srikanth, Associate Professor,ECE.
21
Working with matrices
Concatenation: join small (compatible)
matrices to make bigger ones. B = [A A-2;
A*2 A/4]
Deleting rows and columns. B(:,2) = [ ]
-
8/12/2019 BS Lab_Demo
22/62
P. Srikanth, Associate Professor,ECE.
22
Functions
MATLAB provides a large range of standardelementary mathematical functions, including abs,sqrt, exp, and sin.
For help on functions, type
help elfun(elementary mathematical functions)
help specfun(advanced mathematical functions)
help elmat(advanced matrix functions)
help datafun(data analysis functions)
-
8/12/2019 BS Lab_Demo
23/62
P. Srikanth, Associate Professor,ECE. 23
Suppressing output
If you simply type a statement and pressEnter,MATLAB automatically displays the
results on screen. If you end the line with asemicolon ; MATLAB performs thecomputation but does not display any result.
Example: C = randn(5,1)
C = randn(5,1);
-
8/12/2019 BS Lab_Demo
24/62
P. Srikanth, Associate Professor,ECE. 24
Programming with MATLAB
Files that contain code in the MATLAB
language are called M-files. You create M-
files using a text editor, then use them as
you would any other MATLAB functions or
command.
-
8/12/2019 BS Lab_Demo
25/62
P. Srikanth, Associate Professor,ECE. 25
Flow Control
MATLAB has many flow controls. The most
basic are
if statement
for loopswhile loops
-
8/12/2019 BS Lab_Demo
26/62
P. Srikanth, Associate Professor,ECE. 26
if elseif else end
ifA > B
greater
elseifA < Bless
elseifA = = B
equalend
-
8/12/2019 BS Lab_Demo
27/62
P. Srikanth, Associate Professor,ECE. 27
for end
fori = 1:m
forj = 1:n
H(i,j) = 1/(i+j)end
end
-
8/12/2019 BS Lab_Demo
28/62
P. Srikanth, Associate Professor,ECE. 28
while end
i = 0;
while(i
-
8/12/2019 BS Lab_Demo
29/62
P. Srikanth, Associate Professor,ECE. 29
Graphics
x = 0 : 0.01 : 100;
y = x.^2;
plot(x,y)
Adding plots to an existing graph: hold on
Multiple plots in one figure: subplot
-
8/12/2019 BS Lab_Demo
30/62
P. Srikanth, Associate Professor,ECE. 30
MATLAB supports many types of graph and surfaceplots:
line plots (x vs. y), filled plots,
bar charts,
pie charts,
parametric plots, polar plots,
contour plots,
density plots,
log axis plots,
surface plots, parametric plots in 3 dimensions and spherical
plots.
-
8/12/2019 BS Lab_Demo
31/62
P. Srikanth, Associate Professor,ECE. 31
In Windows
systems
MATLAB is
started bydouble-clicking
the mouse on
the appropriateicon.
-
8/12/2019 BS Lab_Demo
32/62
P. Srikanth, Associate Professor,ECE. 32
MATLABCommand
Window
-
8/12/2019 BS Lab_Demo
33/62
P. Srikanth, Associate Professor,ECE. 33
File
-
8/12/2019 BS Lab_Demo
34/62
P. Srikanth, Associate Professor,ECE. 34
Edit
-
8/12/2019 BS Lab_Demo
35/62
P. Srikanth, Associate Professor,ECE. 35
View
-
8/12/2019 BS Lab_Demo
36/62
P. Srikanth, Associate Professor,ECE. 36
View
-
8/12/2019 BS Lab_Demo
37/62
-
8/12/2019 BS Lab_Demo
38/62
P. Srikanth, Associate Professor,ECE. 38
Web
-
8/12/2019 BS Lab_Demo
39/62
P. Srikanth, Associate Professor,ECE. 39
Help
-
8/12/2019 BS Lab_Demo
40/62
P. Srikanth, Associate Professor,ECE. 40
-
8/12/2019 BS Lab_Demo
41/62
P. Srikanth, Associate Professor,ECE. 41
MATLAB includes hundreds
of functions for: Data analysis and visualization,
Numeric and symbolic computation,
Engineering and Scientific graphics,
Modeling, simulation, and prototyping,
Eigenvalue, singular value
MAT AB D
-
8/12/2019 BS Lab_Demo
42/62
P. Srikanth, Associate Professor,
ECE.
42
MATLAB Demos
Demonstrations areinvaluable since they
give an indication of
the MATLAB
capabilities.
A comprehensive set
are available by
typing the command
>>demoin MATLAB
prompt.
Matlab Variables
-
8/12/2019 BS Lab_Demo
43/62
P. Srikanth, Associate Professor,
ECE.
43
A MATLAB variable is essentially a tag that you
assign to a value in memory.
MATLAB does not require any type declarations or
dimension statements.
When MATLAB encounters a new variable name, itautomatically creates the variable and allocates the
appropriate amount of storage.
If the variable already exists, MATLAB changes itscontents.
Variable names consist of a letter, followed by any
number of letters, digits, or underscores.
-
8/12/2019 BS Lab_Demo
44/62
P. Srikanth, Associate Professor,
ECE.
44
Matlab Variables contd..
MATLAB uses only the first 31 characters
of a variable name.
MATLAB is case sensitive; it distinguishes
between uppercase and lowercase letters.
MATLAB stores variables in a part of
memory called workspace.
To view what is stored in a variable type its
name
-
8/12/2019 BS Lab_Demo
45/62
P. Srikanth, Associate Professor,
ECE.
45
Matrix
Solve the following equation:
X+Y=5; 2X+Y=7; %use CAP
Cramers Rule to solve a 2x2 matrix:
A=[1 1;2 1]; C=[5; 7];
Solution [X Y]
inv(A)*C [X Y]=[2 3]
-
8/12/2019 BS Lab_Demo
46/62
P. Srikanth, Associate Professor,
ECE.
46
2. Plotting
Commands covered: plot, xlabel, ylabel, title grid,axis, stem, subplot
xlabel('time (sec)'); ylabel('step response'); title('My
Plot');Eg:To plot more than one graph on the screen, use the
command subplot(mnp) which partitions the screeninto an mxn grid where p determines the position ofthe particular graph counting the upper left corner as
p=1. For example, subplot(211),semilogx(w,magdb);
subplot(212),semilogx(w,phase);
-
8/12/2019 BS Lab_Demo
47/62
P. Srikanth, Associate Professor,
ECE.
47
3D - Plotting example
x=[0:10]; y=[0:10]; z=x*y;
mesh(x,y,z); title(3-D Graph);
M tl b Pl t t i plot(x y s);
-
8/12/2019 BS Lab_Demo
48/62
P. Srikanth, Associate Professor,
ECE.
48
Matlab Plot t ing plot(x,y, s);
s allows to plot : colors, symbols, different lines
b blue . point - solid
g green o circle : dotted
r red x x-mark -. Dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square k black d diamond
plot (x,y,'c+:') plots a cyan dotted line with a plus at each
data point
-
8/12/2019 BS Lab_Demo
49/62
P. Srikanth, Associate Professor,
ECE.
49
%Matlab - Plotting
cleart=0:0.01:10; % time seconds
signalSin=sin(2*pi*t); % signal1 - frequency =1 Hz
signalCos=0.5*cos(2*pi*t); % signal2 - frequency =1 Hz
plot(t,signalSin);
hold onplot(t,signalCos, '-*r');
xlabel('time'); ylabel('signal');
legend('Sin', 'Cos');
title('Two Signals','FontSize',12)
Other commands: xlabel
ylabel
legend, title
-
8/12/2019 BS Lab_Demo
50/62
P. Srikanth, Associate Professor,
ECE.
50
plot plotyy stem subplot
-
8/12/2019 BS Lab_Demo
51/62
P. Srikanth, Associate Professor,
ECE.
51
plot, plotyy, stem, subplot
plot(Y)
plot(X1,Y1,...)
plot(X1,Y1,LineSpec,PropertyName',PropertyValue,...)
plotyy (X1,Y1,X2,Y2)
plots Y1 versus X1 with y-axis labeling on the left and plots Y2versus X2 with y-axis labeling on the right.
stem (X,Y) plots the data sequence Y at the values specified in X.
suplot (m,n,p), breaks the Figure window into an m-by-n matrix of
small axes, selects the p-th axes for for the current plot
-
8/12/2019 BS Lab_Demo
52/62
P. Srikanth, Associate Professor,
ECE.
52
The following table describes different color codes and styles in plotting the wave forms in figure window:
COLOR CODE COLOR NAME
y Yellow
m Magenta
c Cyan
r Red
g Green
b Blue
k Black
w White
LINE TYPE LINE NAME
. Point
o Circle
x x-mark
+ Plus
- Solid
* Star
: Dotted
-. dash dot
-- Dashed
*- star mark on solid+- plus mark on solid
x- x-mark on solid
^- triangle mark on solid
.- dot mark on solid
PROGRAM 1 a: Basic operations on Single Matrix
-
8/12/2019 BS Lab_Demo
53/62
P. Srikanth, Associate Professor, ECE.
53
PROGRAM 1.a: Basic operations on Single Matrix
%% Program 1.a Basic operations on Single Matrix
clc;
clear all;mat1=[1 1 2 ; 2 1 2 ; 1 3 3]
row2col3=mat1(2,3)
col3=mat1(:,3)
diag_val=diag(mat1)
det_val=det(mat1)
transpose_val=transpose(mat1) %mat1'uppertri_val=triu(mat1)
lowertri_val=tril(mat1)
inverse_val=inv(mat1)
rank_val=rank(mat1)
trace_val=trace(mat1)
eigen_val=eig(mat1)polynomial_val=poly(mat1)
roots_val=roots(polynomial_val)
size_val=size(mat1)
flip_val=fliplr(mat1) %turns the matrix from left to right
% finding sub matrices
-
8/12/2019 BS Lab_Demo
54/62
P. Srikanth, Associate Professor,
ECE.
54
% g _
part_of_matrix=mat1(1:2,2:3) %(1strow to 2nd row,2nd col: 3rdcol)
part_of_matrix1=mat1(1:3,1:2) %(1strow to 3rdrow,1stcol:2ndcol)
part_of_matrix2=mat1([1,3],[1,3]) %([1strow,3rdrow],[1stcol, 3rdcol])
last_row=mat1(end,:) %displays last rowlast_coloumn=mat1(:,end) %displays last column
col1col2=mat1(:,1:2) %displays 1stand 2nd columns of
the matrix
row1row2row3=mat1(1:2,:) %displays 1stand 2nd rows of the
matrix
sel_row=mat1(:,3) %selecting 3rdcolumnsel_col=mat1(2,:) %selecting 2ndrow
mat1(:,3)=[] %deleting 3rdcolumn(now mat1 is
modified)
mat1(2,:)=[] %deleting 2ndrow in the above
mat1% (since mat1 is modified after deleting 3rdcolumn)
% deleting an element from the matrix
-
8/12/2019 BS Lab_Demo
55/62
P. Srikanth, Associate Professor, ECE.55
g
mat2=[1 2 3 ; 4 5 6 ; 7 8 9]
mat2(8)=[] %deletes 8thelement and displays
all the elements as a row vector
mat3=[1 2 3 ; 4 5 6 ; 7 8 9]mat3([4,4])=[] %mat3(4)=[]
% deletes 4th element and displays all the elements as a row vector
mat4=[1 2 3 ; 4 5 6 ; 7 8 9]
mat4([1,2])=[]
% deletes 1st 2ndelements and displays all the elements as a row vector
magic_matrix=magic(3) %sum of all rows and columns is equal
%the no. passing in the magic function argument should be>=3
orthogonal_matrix=orth(4) %A*A'=A'*A=I
identity_matrix=eye(4,4)
zero_matrix=zeros(2,3)one_matrix=ones(2)
random_matrix=rand(3,3)
symmetric_matrix=symdec(3,4) %for skew symmetric matrix---->skewdec
PROGRAM 1.b: Basic operations on Matrices
-
8/12/2019 BS Lab_Demo
56/62
P. Srikanth, Associate Professor,
ECE.
56
p
%% Program 1.b Basic operations on Matrices
% Arithmetic operations on two matrices
clc;
clear all;
a=[1,1,1;2,2,2;3,3,3]
b=[2 3 4;5 6 8;9 1 7] %try b with another size
addition_val=a+b
sbtraction_val=a-bnormalmulti_val=a*b
arraymulti_val=a.*b % element wise multiplication and also try a(1,:).*b(1,:)
division_val=a/b %a*inv(b)
arraydivision_val=a./b %element wise division or array division
power_val=a^3arraypower_val=a.^3 %v=power(a,3)
PROGRAM 1.c: Concatenation of matrices
-
8/12/2019 BS Lab_Demo
57/62
P. Srikanth, Associate Professor,
ECE.
57
%% Program 1.c Concatenation of matrices
clc;
clear all;
x=[1 2 3]
y=[1 1 1]
z=[x,y] %concatenating the matrices
z1=z(4) %choosing 4thelement
z(4)=[] %assigning the 4thelement with null valuez(6)=3 %adding an element to the concatenated matrix
p=[1 2 3;7 8 9]
q=[4 5 6;10 11 12]
r=[p(1,:),q(1,:)] %concatenating 1st rows of two matrices
PROGRAM 1.d: Scalar functions
-
8/12/2019 BS Lab_Demo
58/62
P. Srikanth, Associate Professor, ECE.
58
%% Program 1.d Scalar functions
clc;
clear all;
sine_fun=sin(pi/2)
cosine_fun=cos(pi/2) %answer is almost 0tangent_fun=tan(pi/4)
inverse_sine_fun=asin(pi/2)
inverse_cosine_fun=acos(pi/2)
inverse_tangent_fun=atan(pi/4)
exp_fun=exp(5)
natlog_fun=log(5)comonlog_fun=log10(5)
absolute_fun=abs(-5)
sign_fun=sign(-5) %answer is -1 for 0;answer is 0 for
=0
squareroot_fun=sqrt(25)
remainder_fun=rem(12,4)rounding_fun=round(1.4) %answer is 1 i.e; rounds to nearest integer
% rounding_fun=round(1.5) and answer is 2
floor_fun=floor(1.4) %answer is 1 i.e; rounds towards -ve infinity
ceil_fun=ceil(1.4) %answer is 2 i.e; rounds towards +ve infinity
PROGRAM 1.e: Vector functions
-
8/12/2019 BS Lab_Demo
59/62
P. Srikanth, Associate Professor,
ECE.
59
%% Program 1.e Vector functions
clc;
clear all;z=[1 2 6 4 5]
maximum_fun=max(z)
minimum_fun=min(z)
length_fun=length(z)
sort_fun=sort(z)
sum_fun=sum(z)product_fun=prod(z)
meadian_fun=median(z) %answer is 4 i.e; middle value
mean_fun=mean(z)
standard_deviation_fun=std(z) %square root of mean
PROGRAM 1.f: Relational and Logical operations
-
8/12/2019 BS Lab_Demo
60/62
P. Srikanth, Associate Professor, ECE.60
g p
%% program 1.f Relational and Logical operations
%for relational operations, the result is 1 if the relation is true else 0
clc;clear all;
x=5
y=3
greaterthan_val=x>y %result is 1
lessthan_val=x=y1 %result is 1
lessthanequal_val=x1
-
8/12/2019 BS Lab_Demo
61/62
P. Srikanth, Associate Professor,
ECE.
61
%% program 1.g Complex Numbers
clc;
clear all;
x=complex(2,3) %directly we can give x=2+3iabsolute_val=abs(x)
angle_val=angle(x)
real_val=real(x)
imaginary_val=imag(x)
-
8/12/2019 BS Lab_Demo
62/62
THANK YOU