matlab basics
DESCRIPTION
MATLAB BASICSTRANSCRIPT
MATLAB Applications to electrical Engineering
V R SIDDHARTHA ENGINEERING COLLEGEEEE DEPARTMENT
S.V.R.LAKSHMI KUMARIASSOCIATE PROFFSSOR
P.VENKATESHASSISTANT PROFESSOR
Introduction to MATLAB MATLAB Basics Vectors and Matrices Loops Plots Examples Simulink Modelling examples
MATLAB
SIMULINK
CONTENTS
Introduction to MATLAB MATLAB Basics Vectors and Matrices Loops Plots Examples
04/21/2023 07:39:39 PM MATLAB PRESENTATION 4
MATLAB has been developed by Math Works ,It is a powerful software package used for high performance scientific numeric computation ,data analysis and visualization
MATLAB stands for MATrix Laboratory
MATLAB provides matrix as one of the basic elements. It provides basic operations like addition , subtraction , multiplication by use of simple mathematical operators
Programs can be run step by step, with full access to all variables, functions etc
MATLAB INTRODUCTION
We need not declare the type and size of any variable in advance and MATLAB is case sensitive and so we have to be careful about the case of variables while using them in our program
MATLAB gives an interactive environment with hundreds of reliable and accurate built in functions. These functions help in providing the solutions to a variety of mathematical problems including matrix algebra ,linear systems ,differential equations ,optimization, nonlinear systems and other scientific and technical computations
It facilitates access to FORTRAN and C codes by means of external interfaces
Rows and columns are always numbered starting at 1
MATLAB matrices are of various types to hold different kinds of data (usually floats or integers)
A single number is really a 1 x 1 matrix in MATLAB
Any matrix can be assigned to any variable
7
Advantages and Disadvantages of MATLAB
• Advantages: Ease of Use
Platform Independent (All versions of Windows, Linux, Unix, Mac.)
Predefined Functions and Toolboxes
Device-Independent Plotting
Graphical User Interface
Matlab compiler
• Disadvantages:
Interpreted programming language, slower than C++ and
Fortran.
MATLAB BASICS
Introduction to Matlab MATLAB Basics Vectors and Matrices Loops Plots MATLAB examples
04/21/2023 07:39:39 PM MATLAB PRESENTATION 9
Command Window
Workspace
CommandHistory
Change the current directory to the location of your
Matlab file at startup
10
MATLAB WindowsMATLAB desktop
Workspace: All the information and details of every variable entered into the
command window is displayed here.
Command History : stores history of every command.
Command window: Every operation which we want to perform is to be entered in command window.
Editor Window :This window is used to write any program, which includes many command statements. By using this window one can edit any previously written command.
Figure Window :All the figures are shown in a separate figure window.
04/21/2023 07:39:40 PM MATLAB PRESENTATION 11
3 ways to open a new m-file using MATLAB editor
1. Type >> edit myprogram.m at the command prompt
2. Click on the blank page on MATLAB main window toolbar
3. Click File → New → M-file
Variables1. In MATLAB environment, every variable is an array or matrix
2. Once a variable is entered into the system, you can refer to it later
3. When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later
4. You can have multiple assignments on the same line
Ex : a = 2; b = 7; c = a * b5. The who command displays all the variable names you have used6. The whos command displays little more about the variables7. A valid variable name starts with a letter, followed by letters, digits, or underscores8. Avoid creating variables with the same name as a function (such
as i, j, mode, char, size, and inf etc.)9. Check whether a proposed variable name is already in use with
the exist or which function. exist returns 0 if there are no existing variables, functions, or other artifacts with the proposed name
Predefined variables
Break,Case,Catch,continue,else,elseif end,for,function,global,if,otherwise,return,
switch,try ,while,pi,j,I,ans,NaN,inf etc
Creating VectorsCreate vector with equally spaced intervals>> x=0:0.5:pix = 0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000
Create vector with n equally spaced intervals>> x=linspace(0, pi, 7)x = 0 0.5236 1.0472 1.5708 2.0944 2.6180 3.1416
Equal spaced intervals in logarithm space>> x=logspace(1,2,7)x = 10.0000 14.6780 21.5443 31.6228 46.4159 68.1292 100.0000
Some Built-in functions• mean(A):mean value of a vector• max(A), min (A): maximum and
minimum. • sum(A): summation.• sort(A): sorted vector• median(A): median value• std(A): standard deviation. • det(A) : determinant of a square
matrix • dot(a,b): dot product of two vectors• Cross(a,b): cross product of two vectors• Inv(A): Inverse of a matrix A
04/21/2023 07:39:40 PM MATLAB PRESENTATION 16
Arithmetic Operations and PrecedenceOperation Algebraic Matlab
Form Scalar
addition a + b a + bsubtraction a – b a – bmultiplication a x b a * bdivision a ÷ b a / bExponentiation ab a ^ b
Precedence Operation
1 Parenthesis, innermost first.
2 Exponentiation, left to right
3 Multiplication & division, left to right
4 Addition & subtraction, left to right2^3^4 equals (2^3)^4 2/3*4 equals (2/3)*4 2-3+4 equals (2-3)+4
04/21/2023 07:39:40 PM MATLAB PRESENTATION 17
Function Descriptionexp(x) Exponential (ex)log(x) Natural logarithm
log10(x) Base 10 logarithmsqrt(x) Square root
04/21/2023 07:39:40 PM MATLAB PRESENTATION 18
Trigonometric OperationsFunction Description
sin(x) Computes the sine of x, where x is in radians.
csc(x) Computes the cosec of x, where x is in radians.
sind(x) Computes the sin of x, where x is in degrees.
asin(x) Computes the arcsine or inverse sine of x, where x is in radians.
sinh(x) Computes the hyperbolic sine of x, where x is in radians.
atanh(x) Computes the inverse hyperbolic tangent of x.
04/21/2023 07:39:40 PM MATLAB PRESENTATION 19
Complex Number FunctionsFunction Description
conj(x)Computes the complex conjugate of the complex number x. Thus, if x is equal to a+ib, then conj(x) will be equal to a-ib.
real(x) Computes the real potion of the complex number x.
imag(x) Computes the imaginary potion of the complex number x.
abs(x) Computes the absolute value of magnitude of the complex number x.
angle(x) Computes the angle of the complex number x.
04/21/2023 07:39:41 PM MATLAB PRESENTATION 20
Commands for Managing VariablesCommand Description
clear Removes all variables from the memory.
clear a, b Clears only variables a and b from memory.
who Lists the variables currently in workspace.
whos Displays a lists of the variables currently in the memory and their size together with information about their bytes & class.
Examples>> x=1:3
x = 1 2 3
>> exp(x)
ans = 2.7183 7.3891 20.0855
>> log(x)
ans = 0 0.6931 1.0986
>> sqrt(x)
ans = 1.0000 1.4142 1.7321
Addition,substraction and division of complex numbers
clc;
clear;
z1=1+2i;
z2=3+4i;
z3=z1+z2
z4=z1-z2
z5=z1*z2
z6=z1/z2
abs(z2)
angle(z3)
Output
z3 = 4.0000 + 6.0000i
z4 = -2.0000 - 2.0000i
z5 = -5.0000 +10.0000i
z6 = 0.4400 + 0.0800i
ans =5
ans = 0.9828
04/21/2023 07:39:41 PM MATLAB PRESENTATION 24
Solve the following examples using MATLAB
04/21/2023 07:39:41 PM MATLAB PRESENTATION 25
04/21/2023 07:39:41 PM 26
Program to calculate trignometric values
• Program:x=0:30:180;y=[sind(x);cosd(x);tand(x);cscd(x);secd(x);cotd(x)]z=[x;y]
MATLAB PRESENTATION
04/21/2023 07:39:41 PM MATLAB PRESENTATION 27
Solving linear equations
A System of simultaneous linear equations is written , AX =B
A is a given square matrix of order n , B is a given column vector of n components and X is an unknown column vector of n components
we have learn that the solution to AX =b ,can be written as X=A-1b ,where A-1 is the inverse of A
04/21/2023 07:39:41 PM MATLAB PRESENTATION 28
• Example :
Solutions to Systems of Linear Equations (con’t…)
• Solution by Matrix Inverse:Ax = bA-1Ax = A-1bx = A-1b
• MATLAB:>> A = [ 3 2 -1; -1 3 2; 1 -1 -1];>> b = [ 10; 5; -1];>> x = inv(A)*bx = -2.0000 5.0000 -6.0000
Answer:x1 = -2, x2 = 5, x3 = -6
• Solution by Matrix Division:The solution to the equation
Ax = bcan be computed using left division.
Answer:x1 = -2, x2 = 5, x3 = -6
NOTE: left division: A\b b A right division: x/y x y
MATLAB:>> A = [ 3 2 -1; -1 3 2; 1 -1 -1];>> b = [ 10; 5; -1];>> x = A\bx = -2.0000 5.0000 -6.0000
“linsolve” command
• Solve the system:
• A*S=B• MATLAB Code:
609
234
3325
zyx
zy
zyx
04/21/2023 07:39:42 PM
>> A=[5,-2,-3;0,4,3;1,-1,9];>> B=[-3,-2,60]'; % Note vector transpose (‘)>> S=linsolve(A,B)S = 1.0000 -5.0000 6.0000
‘’ Solve ‘’ command
MATLAB CODE OUTPUT
1)Quadratic equation x2 -7x +12 = 0
>> Eq = X^2-7*X+12;>>S= Solve(Eq); (or)solve('x^2-7*x+12=0')
s = 3 4
2) X4-7X3+3X2-5X+9=0
>> Eg= X^4-7*X^3+3X^2-5X+9=0; >>S=solve(Eg);
S= 6.6304 ,1.06 ,-0.34 – 1.077 and -0.34 + 1.077
The solve command used to solve quadratic equations. The function returns the roots of the equation Example :
EX: syms a b c x fun=a*x^2+b*x+c; solve(fun,x)
Output:ans = -(b + (b^2 - 4*a*c)^(1/2))/(2*a) -(b - (b^2 - 4*a*c)^(1/2))/(2*a)
04/21/2023 07:39:42 PM MATLAB PRESENTATION 33
Expand and the Collect commands
• The expand and the collect command expands and collects an equation respectively. The following example demonstrates the concepts
MATLAB Code :
04/21/2023 07:39:42 PM MATLAB PRESENTATION 34
Factor command :
• The factor command factorizes an expression and the simplify command simplifies an expression.
Examples :MATLAB code Answer
factor(x^3 - y^3) (x - y)*(x^2 + x*y + y^2)
factor([x^2-y^2,x^3+y^3]) [ (x - y)*(x + y), (x + y)*(x^2 - x*y + y^2)]
simplify((x^4-16)/(x^2-4)) x^2 + 4
Simplify((x^3-y^3)/(x-y) X^2+x*y+y^2
04/21/2023 07:39:42 PM MATLAB PRESENTATION 35
‘Polyval’ command:
‘POLYVAL’ command Evaluates polynomial in a matrix senseEx 1:>> a=[1 2 3]; % polynomial X2 + 2X +3 >> polyval(a,1) % polynomial is evaluated at ‘1’ans =6
Ex 2:
>>a=[1 2 3]>>b= 1:5>>C=polyval(a,b) Output :C=[6 11 18 27 38]
Polyval and poly
EX :(with breakpoints)clcclearp=[1 2 1]x=-2:1:2y=polyval(p,x)plot(x,y)r=roots(p)q=poly(r)
04/21/2023 07:39:42 PM MATLAB PRESENTATION 37
‘Diff’ command
• MATLAB provides the diff command for computing symbolic derivatives
• Examples :MATLAB CODE ANSWER
syms tf = 3*t^2 + 2*t^(-2);diff(f)
6*t - 4/t^3
f = x*exp(-3*x);diff(f, 2)
9*x*exp(-3*x) - 6*exp(-3*x)
04/21/2023 07:39:42 PM MATLAB PRESENTATION 38
Integration:
• MATLAB Code :syms x int(2*x)ans = x^2
For example, to calculate the value of we writeint(x, 4, 9)ans = 65/2
04/21/2023 07:39:43 PM MATLAB PRESENTATION 39
Dsolve command:
MATLAB provides the dsolve command for solving differential equations symbolically. The most basic form of the dsolve command for finding the solution to a single equation is :
second order differential equation as: y" - y = 0, y(0) = -1, y'(0) = 2.
MATLAB Code : dsolve('D2y - y = 0','y(0) = -1','Dy(0) = 2')
ans = exp(t)/2 - (3*exp(-t))/2
04/21/2023 07:39:43 PM MATLAB PRESENTATION 40
Polynomial Algebra (Convolution Operator)
82026218)445)(23( 2345232 xxxxxxxxxx
• Polynomial products and factoring:
MATLAB code :For onvolution For Deconvolution
>> p1=[1,3,2];>> p2=[1,5,4,4];>> pc=conv(p1,p2)pc = 1 8 21 26 20 8
>> deconv(pc,p2)ans = 1 3 2>> deconv(pc,p1)ans = 1 5 4 4
Mathematics Example:Polynomial Roots
• Find the roots of the following system:
• MATLAB code:
812 2 xxy
04/21/2023 07:39:43 PM
>> roots([12 -1 -8])ans = 0.8592 -0.7759
Finding the Maxima and Minima of a Curve
ExampleLet us find the stationary points of the function f(x) = 2x3 + 3x2 − 12x + 17 syms x;y = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function ezplot(y)
Our aim is to find some local maxima and minima on the graph, so let us find the local maxima and minima for the interval [-2, 2] on the
graph
syms x;y = 2*x^3 + 3*x^2 - 12*x + 17; ezplot(y, [-2, 2])
Laplace and Inverse Laplace Transforms
MATLAB Code Answer
laplace(a) 1/s^2
laplace(t^2) 2/s^3
ilaplace(1/s^3) t^2/2
Fourier Transforms and Inverse Fourier Transforms
MATLAB Code Answer
f = exp(-2*x^2); FT = fourier(f)
FT = (2^(1/2)*pi^(1/2)*exp(-w^2/8))/2
f = ifourier(-2*exp(-abs(w))) f =-2/(pi*(x^2 + 1))
Transfer function representation Using Matlab
• MatLab• >>num = [1 -2 1 -6.3];• >>den = [1 0.05 -3.14];• >>f = tf(num,den)
14.305.0
3.622
23
XX
XXSf
Example
04/21/2023 07:39:44 PM MATLAB PRESENTATION 49
Examples
04/21/2023 07:39:44 PM MATLAB PRESENTATION 50
04/21/2023 07:39:44 PM MATLAB PRESENTATION 51
04/21/2023 07:39:44 PM MATLAB PRESENTATION 52
Matlab Programming for Engineers
Introduction to Matlab Matlab Basics Vectors and Matrices Loops Plots MATLAB examples
04/21/2023 07:39:44 PM MATLAB PRESENTATION 54
Matrix Index• The matrix indices begin from 1 (not 0 (as in C)) • The matrix indices must be positive integer
Given:
A(-2), A(0)
Error: ??? Subscript indices must either be real positive integers or logicals.
A(4,2)Error: ??? Index exceeds matrix dimensions.
04/21/2023 07:39:44 PM MATLAB PRESENTATION 55
Vectors and Matrices• Vectors (arrays) are defined as• >> v = [1, 2, 4, 5]• >> w = [1; 2; 4; 5]
>> A = [1,2,3;4,-5,6;5,-6,7]
04/21/2023 07:39:45 PM MATLAB PRESENTATION 56
Vectors and Matrices
• How do we assign values to matrices ?
Columns separated by space or a comma
Rows separated by semi-colon
>>> A=[1 2 3;4 5 6;7 8 9]A = 1 2 3 4 5 6 7 8 9>>>
987
654
321
04/21/2023 07:39:45 PM MATLAB PRESENTATION 57
Vectors and Matrices
• How do we access elements in a matrix or a vector?
>>> A(2,3)ans = 6
>>> A(:,3)ans = 3 6 9
>>> A(1,:)ans = 1 2 3
>>> A(2,:)ans = 4 5 6
04/21/2023 07:39:45 PM MATLAB PRESENTATION 58
Vectors and Matrices
• Arithmetic operations – Matrices
Performing operations to every entry in a matrix
Add and subtract>>> A=[1 2 3;4 5 6;7 8 9]A = 1 2 3 4 5 6 7 8 9>>>
>>> A+3ans = 4 5 6 7 8 9 10 11 12
>>> A-2ans = -1 0 1 2 3 4 5 6 7
04/21/2023 07:39:45 PM MATLAB PRESENTATION 59
Vectors and Matrices
• Arithmetic operations – Matrices
Performing operations to every entry in a matrix
Multiply and divide>>> A=[1 2 3;4 5 6;7 8 9]A = 1 2 3 4 5 6 7 8 9>>>
>>> A*2ans = 2 4 6 8 10 12 14 16 18
>>> A/3ans = 0.3333 0.6667 1.0000 1.3333 1.6667 2.0000 2.3333 2.6667 3.0000
04/21/2023 07:39:45 PM MATLAB PRESENTATION 60
Vectors and Matrices
• Arithmetic operations – Matrices
Performing operations to every entry in a matrix
Power>>> A=[1 2 3;4 5 6;7 8 9]A = 1 2 3 4 5 6 7 8 9>>>
A^2 = A * A
To square every element in A, use the element–wise operator .^
>>> A.^2ans = 1 4 9 16 25 36 49 64 81
>>> A^2ans = 30 36 42 66 81 96 102 126 150
04/21/2023 07:39:45 PM MATLAB PRESENTATION 61
Vectors and Matrices
• Arithmetic operations – Matrices
Performing operations between matrices>>> A=[1 2 3;4 5 6;7 8 9]A = 1 2 3 4 5 6 7 8 9
>>> B=[1 1 1;2 2 2;3 3 3]B = 1 1 1 2 2 2 3 3 3
A*B
A.*B
393837
262524
131211
xxx
xxx
xxx
272421
12108
321=
=
505050
323232
141414
04/21/2023 07:39:45 PM MATLAB PRESENTATION 62
Vectors and Matrices
A./B
0000.36667.23333.20000.35000.20000.20000.30000.20000.1
=
3/93/83/72/62/52/41/31/21/1
A.^B
333
222
111
987
654
321
729512343
362516
321=
Tril/triu commands>> a=[1 2 3;4 5 6;7 8 9]a = 1 2 3 4 5 6 7 8 9
>> tril(a)ans =
1 0 0 4 5 0 7 8 9>> triu(a)ans =
1 2 3 0 5 6 0 0 9
04/21/2023 07:39:45 PM MATLAB PRESENTATION 64
• To extracts a sub matrix such that it contains all the elements corresponding to row number and column number
54
21
)2:1,2:1(
987
654
321
D
AD
A
04/21/2023 07:39:45 PM MATLAB PRESENTATION 65
Long Array, Matrix • t =1:10
t = 1 2 3 4 5 6 7 8 9 10• k =2:-0.5:-1
k = 2 1.5 1 0.5 0 -0.5 -1
• X = [1:4; 5:8]
x = 1 2 3 4 5 6 7 8
04/21/2023 07:39:46 PM MATLAB PRESENTATION 66
Generating Vectors from functions• zeros(M,N) MxN matrix of zeros
• ones(M,N) MxN matrix of ones
• rand(M,N) MxN matrix of uniformly distributed
random numbers on (0,1)
x = zeros(1,3)x =
0 0 0
x = ones(1,3)x =
1 1 1
x = rand(1,3)x =0.9501 0.2311 0.6068
04/21/2023 07:39:46 PM MATLAB PRESENTATION 67
Concatenation of Matrices• x = [1 2], y = [4 5], z=[ 0 0]
A = [ x y]
1 2 4 5
B = [x ; y]
1 2 4 5
C = [x y ;z] Error:??? Error using ==> vertcat CAT arguments dimensions are not consistent.
04/21/2023 07:39:46 PM MATLAB PRESENTATION 68
Indexing Matrices• Indexing using parentheses
>> A(2,3)
• Index submatrices using vectorsof row and column indices >> A([2 3],[1 2])
• Ordering of indices is important!>> B=A([3 2],[2 1])>> B=[A(3,2),A(3,1); A(2,2);A(2,1)]
04/21/2023 07:39:46 PM MATLAB PRESENTATION 69
Indexing Matrices(Cond) • Index complete row or column using
the colon operator >> A(1,:)
• Can also add limit index range>> A(1:2,:)>> A([1 2],:)
• General notation for colon operator>> v=1:5>> w=1:2:5
Matrix Concatenation Functions
The following functions combine existing matrices to form a new matrix.
Function Description
cat Concatenate matrices along the specified dimension.
horzcat Horizontally concatenate matrices.
vertcat Vertically concatenate matrices.
repmat Create a new matrix by replicating and tiling existing matrices.
blkdiag Create a block diagonal matrix from existing matrices
This example constructs a new matrix C by concatenating matrices A and B in a vertical direction
Example : >>A = ones(2, 5) * 6; % 2-by-5 matrix of 6's
>>B = rand(3, 5); % 3-by-5 matrix of random values
>>C = [A; B] % Vertically concatenate A and B
Output :C = 6.0000 6.0000 6.0000 6.0000 6.0000 6.0000 6.0000 6.0000 6.0000 6.0000 0.9501 0.4860 0.4565 0.4447 0.9218 0.2311 0.8913 0.0185 0.6154 0.7382 0.6068 0.7621 0.8214 0.7919 0.1763
Example :
a =
1 2 3 4 5 6 7 8 9
>> b=repmat(a,2,3)
b =
1 2 3 1 2 3 1 2 3 4 5 6 4 5 6 4 5 6 7 8 9 7 8 9 7 8 9 1 2 3 1 2 3 1 2 3 4 5 6 4 5 6 4 5 6 7 8 9 7 8 9 7 8 9
Creating a Block Diagonal Matrix
• The blkdiag function combines matrices in a diagonal direction and all other elements of the matrix are set to zero
>>A = magic(3); >>B = [-5 -6 -9; -4 -4 -2]; >>C = eye(2) * 8;
>>D = blkdiag(A, B, C)
• Output:D = 8 1 6 0 0 0 0 0 3 5 7 0 0 0 0 0 4 9 2 0 0 0 0 0 0 0 0 -5 -6 -9 0 0 0 0 0 -4 -4 -2 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 8
04/21/2023 07:39:47 PM MATLAB PRESENTATION 76
Example
04/21/2023 07:39:47 PM MATLAB PRESENTATION 77
04/21/2023 07:39:47 PM MATLAB PRESENTATION 78
04/21/2023 07:39:47 PM MATLAB PRESENTATION 79
04/21/2023 07:39:47 PM MATLAB PRESENTATION 80
04/21/2023 07:39:47 PM MATLAB PRESENTATION 81
Diagonal elements
04/21/2023 07:39:47 PM MATLAB PRESENTATION 82
fprintf ,Disp commands
Disp(x)Disp(‘string’)
disp(x) displays the arrayIf X is a string, the text is displayed
Ex :z=2+3i;fprintf('z= ');disp(z)
Output :Z= 2+3i
04/21/2023 07:39:47 PM MATLAB PRESENTATION 83
Format Code Purpose
%s Format as a string.
%d Format as an integer.
%f Format as a floating point value.
%e Format as a floating point value in scientific notation.
%g Format in the most compact form: %f or %e.
\n Insert a new line in the output string.
\t Insert a tab in the output string.
The fscanf and fprintf commands behave like C scanf and printf functions. They support the following format codes:
Fprintf examples :
>> n=2;>> fprintf('value is %d\n',n)
Output:value is 2
fprintf('I have %d brother and %d sister\n',1,1)Output :I have 1 brother and 1 sister
>> fprintf(‘This is %s department , we got %d years of NBA accrediation/n','EEE',5)
Output : This is EEE department ,we got 5 years of NBA accrediation/n>>
‘input ‘ command
Example :x=input('enter the value of x');y=input('enter the value of y');z=x+y;fprintf('the value of z is %d\n',z)
Output:enter the value of x30enter the value of y0the value of z is 30
Input
Write the program to display 6th table
6*1=66*2=126*3=186*4=246*5=306*6=366*7=426*8=486*9=546*10=60
n=input('enter n value');for i=1:10 fprintf('%d*%d=%d\n',n,i,n*i)end
Importing data files into MATLAB
1.First create text file with name ‘data’2.In matlab file , load data.txt