0% found this document useful (0 votes)
3 views

Slide MATLAB

Uploaded by

shorif4437
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Slide MATLAB

Uploaded by

shorif4437
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Workshop on MATLAB

Conducted By

Md. Tarequzzaman
Lecturer
Dept. of EEE, JUST
Introduction to MATLAB

The MATLAB package is employed in wide ranges of engineering and


scientific computing applications and is associated with the dynamic
system simulation package called Simulink.

The package has a few advantages and remarkable strengths, such as


user-friendly and intuitive programming syntax, high-quality
numerical algorithms for various numerical analyses, powerful and
easy-to-use graphics, simple command syntax to perform
computations, and many add-ons as toolboxes and real and complex
vectors and matrices, including sparse matrices as fundamental data
types
This main desktop window is shown in Figure

The Command Window is in the central pane (by default). All


commands and/or (small) scripts/codes/built-in function/tool box can be
entered directly after

This window shows all the files in the directory and the folder
directory.

The Workspace pane of the default desktop window shows the current
entries and saved variables during the session.
Command Window and Variables

 MATLAB is case-sensitive and all  Variable names must start with a


letter and can be combined with any
of its built-in commands are integer numbers, such as 0, 1, 2, …
lowercase. 9 and (_) an underscore sign.
 No other symbols can be used for
 When you perform computations, variable names.
you assign a name to the result of  The maximum length of the variable
name is 63 characters. MATLAB
the computation. treats the variables called a and A
 The assigned name is the variable as two different variables because of
its ANSI/ASCII symbol conversions.
name.
 The fundamental unit of data in any The size of an array is
MATLAB program is the array. specified by the number of
 An array is a collection of data values rows and the number of
organized into rows and columns, and columns in the array, with
known by a single name. the number of rows
 Individual data values within an array mentioned first.
are accessed by including the name of the
array followed by subscripts in The total number of elements
parentheses that identify the row and in the array will be the
column of the particular value. product of the number of
 Arrays can be classified as either vectors rows and the number of
or matrices. The term “vector” is usually columns.
used to describe an array with only one
dimension, while the term “matrix” is
usually used to describe an array with two
or more dimensions.
Variable Declaration MATLAB is an abbreviation for "matrix
laboratory."
Variable name = value; Array Creation: To create an array with four
elements in a single row, separate the
Ex: a = 2; b = 3; elements with either a comma (,) or a space.
c = a + b;
d = cos(a); a = [1 2 3 4];
This type of array is a row vector. To create a
If you end a statement matrix that has multiple rows, separate the
with a semicolon, rows with semicolons.
MATLAB performs the a = [1 2 3; 4 5 6; 7 8 10];
computation, but
suppresses the display of Another way to create a matrix is to use a
output in the Command function, such as ones, zeros, or rand. For
Window. example, create a 5-by-1 column vector of
zeros.
Column vectors are created in On the other hand, a row vector
a similar way, however, is converted to a column vector
semicolon (;) must separate using the transpose operator.
the components of a column The transpose operation is
vector,
w = [1;4;7;10;13] denoted by an apostrophe or a
single quote (’).

Access: Thus, v(1) is the first element of vector v, v(2) its second element,
and so forth.
Furthermore, to Or, all elements Entering a matrix
access blocks of from the third
elements, we through the last A matrix is an array of
use MATLAB’s elements, numbers. To type a matrix
colon notation into MATLAB you must-
(:). • begin with a square
where end signifies
the last element in bracket, [
the vector. • separate elements in a
row with spaces or
commas (,)
• use a semicolon (;) to
Location: (3,2) separate rows
• end the matrix with
another square bracket, ]
Matrix indexing
Correcting any entry is easy
The element of row i and column j of the through indexing. Here we
matrix A is denoted by A(i,j). Thus, A(i,j) substitute A(3,3)=9 by A(3,3)=0.
in MATLAB refers to the element Aij of The result is
matrix A. The first index is the row
number and the second index is the
column number. For example, A(1,3) is
an element of first row and third column.
Linear spacing
Colon operator
On the other hand, there is a command
Often we must deal with to generate linearly spaced vectors:
matrices or vectors that are too linspace. It is similar to the colon
large to enter one element at a operator (:), but gives direct control
time. For example, suppose we over the number of points. For
want to enter a vector x example,
consisting of points (0; 0:1; 0:2;
0:3; 5). We can use the
command generates a row vector y of 100 points
linearly spaced between and including
a and b.

generates a row vector y of n points


linearly spaced between and including a
and b.
Colon operator in a matrix It is important to note that the
colon operator (:) stands for all
The colon operator can also be used
columns or all rows.
to pick out a certain row or column.
For example, the statement
A(m:n,k:j) specifies rows m to n and
column k to j. Subscript expressions A row or a column of a
refer to portions of a matrix. matrix can be deleted
by setting it to a null
vector, [ ].
Creating a sub-matrix

The colon operator can also be used


to extract a sub-matrix from a
matrix A.
To interchange rows 1 and 2 of Deleting row or column
A, use the vector of row indices To delete a row or column of a matrix,
together with the colon use the empty vector operator, [ ].
operator.

As a special case, a colon (:) as the Dimension


row or column specifier covers all
To determine the dimensions of a
entries in that row or column; thus
matrix or vector, use the command
 A(:,j) is the jth column of A, while
size.
 A(i,:) is the ith row, and
 A(end,:) picks out the last row of
A.
Continuation Concatenating matrices

If it is not possible to type the entire Matrices can be made up of sub-


input on the same line, use matrices.
consecutive periods, called an ellipsis
…, to signal continuation, then
continue the input on the next line.
Matrix generators
Matrix Array
Multiplication Multiplication

C = A*B or B*A C = A.*2


Inverse of a matrix: inv(A)
Matrix Division Array Division Determinant of a Matrix: det(A)
Rank of a matrix: rank(A)
C = A/B right C = A./2 right Eigen value: eig(A) or [v,
division division d]=eig(A)
C = A\B left division C = A.\2 left division
Multi dimensional Array
Matrix Addition Matrix
Subtraction
C=A+B
C=A-B
format long Long, fixed-decimal format with 15 digits after the
Format style decimal point for double values, and 7 digits after the
changes the output decimal point for single values.
display format in format short Short, fixed-decimal format with 4 digits after the
the Command decimal point.

Window to the format shortEng Short engineering notation (exponent is a multiple of


3) with 4 digits after the decimal point.
format specified by
format longEng Long engineering notation (exponent is a multiple of 3)
style. with 15 significant digits.
format, by itself, format shortE Short scientific notation with 4 digits after the decimal
resets the output point.
format to the format longE Long scientific notation with 15 digits after the
default, which is the decimal point for double values, and 7 digits after the
decimal point for single values.
short, fixed-decimal
format bank Currency format with 2 digits after the decimal point.
format for floating-
point notation and format hex Hexadecimal representation of a binary double-
precision number
loose line spacing
format rat Ratio of small integers.
for all output lines.
format long format short format longEng
>> pi pi pi
Ans = ans = 3.1416 ans =
3.141592653589793 3.14159265358979e+000
format longE format bank format hex
pi >> pi pi
ans = ans = 3.14 ans = 400921fb54442d18
3.141592653589793e+00

format rat format shortE format shortEng


>> pi pi >> pi
ans = 355/113 ans = ans = 3.1416e+000
3.1416e+00
pi 3.14159265358979
3
I or j 0 + 1i
inf 1/0
nan 0/0
clock 2023.00 10.00
16.00 23.00
44.00 49.67
date '16-Oct-2023'
The disp function accepts an X = rand(5,3);
array argument and displays disp(' Corn Oats A = [15 150];
the value of the array in the Hay') S = 'Hello
Command Window. Corn Oats Hay World.';
disp(X) disp(A)
If the array is of type char, 0.8147 0.0975 0.1576
then the character string 15 150
0.9058 0.2785 0.9706 disp(S)
contained in the array is 0.1270 0.5469 0.9572
printed out. Hello World.
0.9134 0.9575 0.4854
0.6324 0.9649 0.8003
This function is often
combined with the functions name = 'Alice';
num2str (convert a number to age = 12;
a string) and int2str (convert X = [name,' will be ',num2str(age),' this
an integer to a string) to year.'];
create messages to be disp(X)
Alice will be 12 this year.
Formatted Output with the
fprintf Function

An even more flexible way to


display data is with the fprintf
function. The fprintf function
displays one or more values
together with related text and
lets
M-File Scripts M-File functions
functions are programs (or
A script file is an external file that routines) that accept input
contains a sequence of MATLAB arguments and return output
statements. arguments. Each M-file function
(or function or M-file for short)
Script files have a filename extension .m has its own area of workspace,
and are often called M-files. separated from the MATLAB
base workspace.
M-files can be scripts that simply execute
a series of MATLAB statements, or they
can be functions that can accept
arguments and can produce one or more
outputs
Use the. MATLAB editor to create a file:
File  New  M-file.
function function [m,s] = stat(x)
Declare function name, inputs, and outputs n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
Syntax:
end
function [y1,...,yN] = myfun(x1,...,xM)

Description values = [12.7, 45.4, 98.9, 26.6,


function [y1,...,yN] = myfun(x1,...,xM) 53.1];
[ave,stdev] = stat(values)
declares a function named myfun that
accepts inputs x1,...,xM and returns outputs
y1,...,yN. function ave =
average(x)
This declaration statement must be the first ave =
executable line of the function. sum(x(:))/numel(x);
end
z = 1:99;
Valid function names begin with an ave = average(z)
alphabetic character and can contain letters,
numbers, or underscores.
Hierarchy of Operations
Built-in MATLAB Functions
x = [1.3 -3.56 8.23 -5 -
0.01]' x = [0.5i 1+3i -2.2+i];
x = 5×1 y = acos(x) x = -pi:0.01:pi;
Z = cos(x)
1.3000
y = 1×3 complex
-3.5600 x = -pi:0.01:pi;
8.2300 Z = sin(x)
1.5708 - 0.4812i
-5.0000
1.2632 - 1.8642i
-0.0100
2.6799 - 1.5480i log(-1)
ans = 0.0000 +
y = abs(x)
3.1416i
y = 5×1 z = 2*exp(i*0.5)
z = 1.7552 + 0.9589i
1.3000 r = abs(z) z = 4 + 3i;
3.5600 r=2 r = abs(z)
8.2300 theta = angle(z) r=5
5.0000 theta = 0.5000 theta =
0.0100 Degree= rad2deg(0.5) atan2(imag(z),real(z))
If dim = 1, then max(A,[],1)
A = [1.77 -0.005 3.98 -2.95
A = [23 42 37 18 returns a row vector
NaN 0.34 NaN 0.19];
52]; containing the largest element
M = max(A,[],'omitnan’)
M = max(A) in each column.
M = max(A,[],'includenan')
A = [2 8 4; 7 3 9]
A = 2×3
Create a matrix A and compute
2 8 4
the largest elements in each
7 3 9
column, as well as the row
indices of A in which they
M = max(A) If dim = 2, then max(A,[],2)
appear.
M = 1×3 A = [1 9 -2; 8 4 -5] returns a column vector
A = 2×3 containing the largest element in
7 8 9 1 9 -2 each row.
8 4 -5
[M,I] = max(A)
M = max(A,[],2) M = 1×3
8 9 -2
M= I = 1×3
max(A,[],1) 2 1 1
k = find(X) returns a vector Use the k2 = find(~X)
containing the linear indices of logical not k2 = 4×1
each nonzero element in array operator on 2
X. 3
X to locate
4
X = [1 0 2; 0 1 1; 0 0 the zeros 6
4]
X = 3×3
Find the first five elements that are less than 10 in
1 0 2
a 4-by-4 magic square matrix.
0 1 1
0 0 4 k= X(k)
k = find(X) X = magic(4) find(X<10,5) ans = 5×1
k = 5×1 X = 4×4 k = 5×1
1 16 2 3 13 2 5
5 5 11 10 8 3 9
7 9 7 6 12 4 4
8 4 14 15 1 5 2
9 7 7
To find a specific integer value, use
the == operator. For instance, find X = [18 3 1 11; 8 10 11 3; 9 14 6 1; 4 3 15
the element equal to 13 in a 1-by-10 21]
vector of odd integers. X = 4×4
18 3 1 11
x = 1:2:20 8 10 11 3
x = 1×10 9 14 6 1
1 3 5 7 9 11 13 15 4 3 15 21
17 19
k = find(x==13) [row,col] = find(X>0 & X<10,3)
k=7 row = 3×1
2
3
Find the first three elements in a 4- 4
by-4 matrix that are greater than 0 col = 3×1
and less than 10. Specify two outputs 1
to return the row and column 1
subscripts to the elements. 1
row = 5×1
1
2
1
Find the nonzero elements in a 3-by-3 matrix. Specify
2
three outputs to return the row subscripts, column
3
subscripts, and element values.
col = 5×1
1
1
X = [3 2 0; -5 0 7; 0 0 2
1] 3
X = 3×3 3
3 2 0 v = 5×1
-5 0 7 3
0 0 1 -5
[row,col,v] = find(X) 2
7
1
A = [77 65 84 76 65 66]; chr = int2str(3.14159) chr = int2str([5 10 20;100 200
C = char(A) chr = '3' 400])
C = 'MATLAB' Convert a numeric matrix. chr = 2x13 char array
' 5 10 20'
chr = int2str(256) '100 200 400'
chr = '256' X = str2num('100 200 300 400')
s = num2str(pi)
Round off a floating-point value and X = 1×4
s = '3.1416'
convert it. 100 200 300 400
Solving linear equations This equation can be solved for x using
linear algebra. The result is x = A-1b.
With matrix notation, a
system of simultaneous linear
equations is written

The second one is to use the backslash


(\)operator.

With matrix notation, a system


of simultaneous linear equations
is written
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3], [x,
2x+y+z=2 y, z])
−x+y−z=3
A= B=
x+2y+3z=−10 [ 2, 1, 1] 2
[ -1, 1, -1] 3
Declare the system of [ 1, 2, 3] -10
equations.
syms x y z Use linsolve to solve AX = B for the vector of
eqn1 = 2*x + y + z == 2; unknowns X.
eqn2 = -x + y - z == 3;
eqn3 = x + 2*y + 3*z == -10; X = linsolve(A,B)
X=
3
Use equationsToMatrix to convert
1
the equations into the form AX = B. -5
The second input to From X, x = 3, y = 1 and z = -5.
equationsToMatrix specifies the
independent variables in the
Solve the system of equations using Solve this differential equation.
solve. The inputs to solve are a
vector of equations, and a vector of
variables to solve the equations for.
First, represent y by using syms to create the
sol = solve([eqn1, eqn2, eqn3], [x, y, symbolic function y(t).
z]);
xSol = sol.x syms y(t)
ySol = sol.y Define the equation using == and represent
zSol = sol.z differentiation using the diff function
xSol = 3
ode = diff(y,t) == t*y
ySol = 1
zSol = -5 Solve the equation using dsolve.

ySol(t) = dsolve(ode)
ySol(t) = C1*exp(t^2/2)
Solve Differential Equation with Condition

cond = y(0) == 2;
ySol(t) = dsolve(ode,cond)

Nonlinear Differential Equation with Initial syms y(x)


Condition Dy = diff(y);

ode = diff(y,x,2) == cos(2*x)-


y;
cond1 = y(0) == 1;
syms y(t) cond2 = Dy(0) == 0;
ode = (diff(y,t)+y)^2 == 1; conds = [cond1 cond2];
cond = y(0) == 0; ySol(x) = dsolve(ode,conds);
ySol(t) = dsolve(ode,cond) ySol = simplify(ySol)
ySol(x) = 1 - (8*sin(x/2)^4)/3
ySol(t) = exp(-t) – 1 or 1 - exp(-t)
q = integral(fun,xmin,xmax)
numerically integrates function fun
3rd Order Differential from xmin to xmax using global
Equation adaptive quadrature and default
error tolerances.

syms u(x)
Du = diff(u,x);
D2u = diff(u,x,2); fun = @(x) exp(-
x.^2).*log(x).^2;
ode = diff(u,x,3) == u; Evaluate the integral from x=0 to
cond1 = u(0) == 1; x=Inf.
cond2 = Du(0) == -1; q = integral(fun,0,Inf)
cond3 = D2u(0) == pi;
conds = [cond1 cond2
cond3];
uSol(x) = dsolve(ode,conds)
uSol(x) = fun = @(x)log(x);
(pi*exp(x))/3 - exp(-x/2)*cos((3^(1/2)*x)/2)*(pi/3 -
1) - (3^(1/2)*exp(-x/2)*sin((3^(1/2)*x)/2)*(pi + 1))/3 format long
q1 =
integral(fun,0,1)
Introduction to Plotting
MATLAB’s extensive, device-
independent plotting
capabilities are one of its most
powerful features.
To plot a data set, just create
two vectors containing the x and
y values to be plotted and use
the plot function.

For example, suppose that we


wish to plot the function for
values of x between 0 and 10.
Multiple Plots

Line Color, Line Style, Marker


Style, and Legends

legend('string1', 'string2',...,
pos)
x = linspace(-2*pi,2*pi); subplot(m,n,p) divides
y1 = sin(x); the current figure into
y2 = cos(x); an m-by-n grid and
figure creates axes in the
plot(x,y1,'r-',x,y2,'bo',... position specified by p.
'LineWidth',2,...
'MarkerSize',2,... subplot(2,1,1);
'MarkerEdgeColor','b',...
x = linspace(0,10);
'MarkerFaceColor',[.3,.3,.3])
title('X Vs Y') y1 = sin(x);
xlabel('X') plot(x,y1)
ylabel('Y')
%legend('V','I') subplot(2,1,2);
legend({'V','I'},'Location','southwest','NumColumns y2 = sin(5*x);
',1) plot(x,y2)
%legend('off')
Semi log
Graph
x = logspace(-1,2);
y1 = x;
y2 = -x; Loglog Graph
semilogx(x,y1,x,y2)
grid on x = logspace(-1,2);
y1 = 10.^x;
y2 = 1./10.^x;
loglog(x,y1,x,y2)
grid on

You might also like