Basics of MATLAB.
Basics of MATLAB.
Basics of MATLAB.
DEPARTMENT OF MECHANICAL
ENGINEERING
LAB MANUAL
Prepared by-
Mr Sudhir B S
AY 2023 - 24
IBASICS OF MATILAB
Course Code 2lME581 CIE Marks 50
Teaching Hours/Week (L:T:P: S) 0:0:2 ':0 SEE Marks 50
Credits 01 Exam HOtffS 02
* Ad,dition,at one hou.r may be considered for instructions, if required
Course objectives:
1. To kriow about fundamentals of MATLAB tool.
2. To provide an overview to program CtJrve fitting & solve linear and Nonlinear Equatiions.
3. To understand the concept and importance of Fourier tiransforms.
4. To gain knowledge abotJt MATLAB Simulink & solve Electrical engineering problems.
SI.NO Experiments
1
Introduction to MATLAB Programming: Basicsof MATLAB Programming, array operations in MATLAB, loops
2 and execution of control, working with files: Scripts and fonction.s, plotting and programming outpllt, examples.
Numerical! Methods and their applications: Curve Fining: Straigiht lineii, Poll1inomiallit.
4
7
Linear and N,onlinear Equatiions: IEigen values, Eigen vectors, Solution of linear algebraic equations using GatJss
Elimination and LU decomposition, Solution •Of nonlinear equation in single varliable using Gauss-Siedal and
8
Newton-Raphson method.
9
Oirdinall"VIDiffeirential E.quation.s: Introduction to ODE's, Euler's method, second order RungaKutta method,
10 MATLAB ode45 algorithm in single variable and multivariables. Tiransfoirms: Discrete FotJrler Tran.sforms,
11
Application of MATLAB to analyse problems in basic engineering mechanics, mechanical vibrations, control
12 system, statistics and dynamicsof different circuits.
MATLAB Simullinlk: Introduction to MATLAB Simulink, Simulink libraries,d, evelopment of basic models in
13 Simscape Power Systems
• .Able to implement loops, branching, control instriuctiion and fonctions in MATLAB programming environment.
• .Able to program curve fitting, numerical differentiation and integration, solution of linear equations in MATILAIB
and solve electrical engineering problems.
• .Able to understand Implementation of ODE using ode 45 and execute Solutions of nonlinear equations and DFT
in MA11LAB.
• .Able to srmulate MAHAIB Simlllink examples
INTRODUCTION TO MAT LAB
The name MATLAB stands for MATrix LABoratory. MATLAB was written originally to
provide easy access to matrix software developed by the LINPACK (linear system package)
and EISPACK (Eigen system package) projects.
Starting MATLAB
After logging into your account, you can enter MATLAB by double-clicking on the
MATLAB shortcut icon (MATLAB 17.0.4) on your Windows desktop. When you start
MATLAB, a special window called the MATLAB desktop appears. The desktop is a window
that contains other windows. The major tools within or accessible from the desktop are:
The Command Window
The Command History
The Workspace
The Current Directory
The Help Browser
The Start button
Desktop Tools
The following tools are managed by the MATLAB desktop, although not all of them appear
by default when you first start. If you prefer a command line interface, you can use functions
to perform most of the features found in the MATLAB desktop tools. Instructions for using
these function equivalents are provided with the documentation for each tool.
Command Window – Run MATLAB functions.
Command History – View a log of the functions you entered in the Command
Window, copy them, and execute them.
Launch Pad – Run tools and access documentation for all of your MathWorks
products.
Current Directory Browser – View MATLAB files and related files, and perform
file operations such as open, and find content.
Help Browser – View and search the documentation for the full family of MATLAB
products.
Workspace Browser – View and make changes to the contents of the workspace.
Array Editor – View array contents in a table format and edit the values.
Editor/Debugger – Create, edit, and debug M-files (files containing MATLAB
functions).
Following are some additional shortcuts that are not listed on menu items.
.
MATLAB Windows
Window Purpose
Notation Purpose
\ Left-division operator.
/ Right-division operator.
. Decimal point.
= Assignment operator.
Hands on Practice
Semicolon (;) indicates end of statement. However, if you want to suppress and
hide the MATLAB output for an expression, add a semicolon after the
expression.
For example,
x = 3;
y=x+5
When you click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is:
y=8
>> 4 + 5/3 + 2
→ 5/3 is executed first
ans = 7.6667
>> 5 ^3/2
→ 5^3 is executed first, /2 is executed next
ans = 62.5000
>> 27^(1/3)+32^0.2
→ 1/3 is executed first, 27^(1/3) and 32^0.2 are executed next, and + is executed
last
Ans = 5
>> 27^1/3+32^0.2
→ 27^1/3 and 32^0.2 are executed first, 1/3 is executed next, and + is executed
last
Ans = 11
By default, MATLAB displays numbers with four decimal place values. This is
known as short format.
However, if you want more precision, you need to use the format command.
The format long command displays 16 digits after decimal.
For example:
format long
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result:
x = 17.231981640639408
format short
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result:
x = 17.2320
The format bank command rounds numbers to two decimal places. For
example,
format bank
daily_wage = 177.45;
weekly_wage = daily_wage * 6
MATLAB will execute the above statement and return the following result:
weekly_wage = 1064.70
The format short e command allows displaying in exponential form with four
decimal places plus the exponent. For example,
format short e
4.678 * 4.9
MATLAB will execute the above statement and return the following result:
ans = 2.2922e+01
The format long e command allows displaying in exponential form with four
decimal places plus the exponent. For example,
format long e
x = pi
MATLAB will execute the above statement and return the following result:
x = 3.141592653589793e+00
The format rat command gives the closest rational expression resulting from a
calculation. For example,
format rat
4.678 * 4.9
MATLAB will execute the above statement and return the following result:
Ans =2063/90
Some more Examples
Command Description
Examples
Example:
>> x=3*x - 12
← A new value is assigned to x. The new value is 3 times the previous value of
x minus 12.
Ans x = 33
>> a=12 ← Assign 12 to a
a = 12
>> b=4 ← Assign 4 to b
b=4
>> c=(a-b)+40-a/b*10 ← Assign the value of the expression on the right-hand
side to the variable c.
c =18
>> a=12; ← The variables a, b and c are defined but are not displayed since a
>> b=4; semicolon is typed at the end of each statement
>> c=(a-b)+40-a/b*10;
>> c ← The value of the variable c is displayed by typing the name of the
variable
c =18
>> LHS=cos(x/2)^2
LHS = 0.9045
>> RHS=(tan(x)+sin(x))/(2*tan(x))
RHS = 0.9045
Creating Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two
types of vectors:
Row vectors
Column vectors
Variable name=[ type vector element]
Row vector: To create a row vector type the elements with a space or a comma
between the elements inside the square brackets.
Column vector: To create a column vector type the left square bracket [ and
then enter the elements with a semicolon between them, or press the Enter key
after each element. Type the right square bracket ] after the last element.
Row vectors are created by enclosing the set of elements in square brackets,
using space or comma to delimit the elements.
For example,
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result:
r=
Columns 1 through 4
7 8 9 10
Column 5
11
Another example
r = [7 8 9 10 11];
t = [2, 3, 4, 5, 6];
res = r + t
MATLAB will execute the above statement and return the following result:
res =
Columns 1 through 4
9 11 13 15
Column 5
17
Column vectors are created by enclosing the set of elements in square brackets,
using semicolon (;) to delimit the elements.
MATLAB will execute the above statement and return the following result:
c=
7
8
9
10
11
Creating a vector with constant spacing by specifying the first term, the spacing,
and the last term
Variable_name= [m:q:n] or variable_name= m:q:n
Examples :
>> x=[1:2:13] First element 1, spacing 2, last element 13
x=
1 3 5 7 9 11 13
>> y=[1.5:0.1:2.1] First element 1.5, spacing 0.1, last element 2.1
y=
1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 2.1000
>> z=[-3:7] First element -3, last element 7. If spacing is omitted, the
default is 1
z=
-3 -2 -1 0 1 2 3 4 5 6 7
Creating a vector with constant spacing by specifying the first and last terms and
the number of terms
Variable_name=linspace(xi,xf,n)
Examples :
>> va= linspace(0,8,6) 6 elements, first element 0, last element 8
va = 0 1.6000 3.2000 4.8000 6.4000 8.0000
MATLAB will execute the above statement and return the following result:
m=
1 2 3
4 5 6
7 8 9
>> cd=6; e=3; h=4; Three variables are defined
>> mat=[e, cd*h, cos(pi/3); h^2, sqrt(h*h/cd), 14]
Elements are defined by Mathematical expressions
mat =
3.0000 24.0000 0.5000
16.0000 1.6330 14.0000
1 3 5 7 9 11
0 5 10 15 20 25
10 20 30 40 50 60
67 2 43 68 4 13
The zeros, ones and eye Commands
The zeros(m,n) and the ones(m,n) commands create a matrix with m rows and n
columns, in which all the elements are the numbers o and 1 respectively. The
eye(n) command creates a square matrix with n rows and n columns in which the
diagonal elements are equal to 1, and the rest of the elements are 0. This matrix
is called the identity matrix. Examples are:
>> zr=zeros(3,4) >> a=zeros(4) >> ne=ones(4,3)
zr = a= ne =
0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 1 1 1
>> idn=eye(5)
idn =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
Matrix operations
>> A=[3 11 6 5; 4 7 10 2; 13 9 0 8] Create a 3x4 matrix
A=
3 11 6 5
4 7 10 2
13 9 0 8
For a matrix
A(:,n) Refers to the elements in all the rows of column n of the matrix A
A(n,: ) Refers to the elements in all the columns of row n of the matrix A
A(:,m:n) Refers to the elements in all the rows between columns m and n of
the matrix A
A(m:n,:) Refers to the elements in all the columns between rows m and n of
the matrix A
A(m:n,p:q) Refers to the elements in rows m through n and columns p through
q of the matrix A
Examples
>> A=[1 3 5 7 9 11; 2 4 6 8 10 12; 3 6 9 12 15 18; 4 8 12 16 20 24;
5 10 15 20 25 30]
A=
1 3 5 7 9 11
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
Using a colon in addressing arrays
Examples:
>> B=A(:,3) Define a column vector B from the elements in all the rows of
column 3 in Matrix A
B=
5
6
9
12
15
>> C=A(2,:) Define a row vector C from the elements in all the columns
of row 2 in matrix A
C=
2 4 6 8 10 12
>> F=A(1:3,2:4) Create a matrix f from the elements in rows 1 through 3 and
columns 2 through 4 In matrix A
F=
3 5 7
4 6 8
6 9 12
>> u=V([3,5,7:10]) Create a vector u from the 3rd, the 5th, and 7th through
10 elements of V
u=
10 16 22 25 28 31
>> B=[5 7 2] Define vector B with 3 elements
B=
5 7 2
>> P(5)=24
P=
0 0 0 0 24
>> B=eye(3)
B=
1 0 0
0 1 0
0 0 1
A=
3 6 9 0 0 MATLAB changes the matrix size to 4X5, and
8 5 11 0 0 assigns zeros to the new elements
0 0 0 0 0
0 0 0 0 17
Deleting Elements
>> kt=[2 8 40 3 55 23 15 75 80] Define a vector with 10 elements
kt =
2 8 40 3 55 23 15 75 80
>> kt(6)=[ ] Eliminate the sixth element
kt =
2 8 40 3 55 15 75 80
>> kt(3:6)=[ ] Eliminate elements 3 through 6
kt =
2 8 75 80
>> mtr=[5 78 4 24 9; 4 0 36 60 12; 56 13 5 89 31] Define 3x5 matrix
mtr =
5 78 4 24 9
4 0 36 60 12
56 13 5 89 31
>> mtr(:,2:4)=[ ] Eliminate all the rows of columns 2 through 4
mtr =
5 9
4 12
56 31
>> F=[1 3; 5 7]
F=
1 3 Define two 2 X 2 matrices F and G
5 7
>> G=[4 2; 1 6]
G=
4 2
1 6
>> F*G ← Multiply F*G
ans =
7 20
27 52
>> G*F ← Multiply G*F
ans =
14 26
31 45
Note: The answer of F*G is not the same as the answer G*F
>> A*b
ans =
6 15 21 0
30 3 9 12
18 6 33 15
>> C=A*5 ← Multiply the matrix A by 5 and assign the result to a new
variable C
C=
10 25 35 0
50 5 15 20
30 10 55 25
>>C= 5*A
C=
10 25 35 0
50 5 15 20
30 10 55 25
Inverse of the Matrix
>> A=[7 3 8; 4 11 5; 6 7 10] >> A=[2 1 4; 4 1 8; 2 -1 3] ← Creating the
A= matrix A
7 3 8 A=
4 11 5 2 1 4
6 7 10 4 1 8
>> I=eye(3) 2 -1 3
I= >> B=inv(A) ← Use the inv function to
1 0 0 find the inverse of A and assign it to B
0 1 0 B=
0 0 1 5.5000 -3.5000 2.0000
>> A*I 2.0000 -1.0000 0
ans = -3.0000 2.0000 -1.0000
7 3 8
4 11 5
6 7 10
>> I*A
ans =
7 3 8
4 11 5
6 7 10
Xb =
-1.8049
0.2927
2.6341
>> C=[4 2 6; -2 8 10; 6 2 3]; ← Solving the form X C = D
>> D=[8 4 0];
>> Xc= D/C ← Solving by using right division X= D / C
Xc =
-1.8049 0.2927 2.6341
To create scripts files, you need to use a text editor. You can open the MATLAB
editor in two ways:
Using the command prompt
Using the IDE
If you are using the command prompt, type edit in the command prompt. This
will open the editor. You can directly type edit and then the filename (with .m
extension)
edit
Or
edit <filename>
Alternatively, if you are using the IDE, choose NEW -> Script. This also opens
the editor and creates a file named Untitled. You can name and save the file after
typing the code.
After creating and saving the file, you can run it in two ways:
Example 1
Create a script file, and type the following code:
a = 5; b = 7;
c=a+b
d = c + sin(b)
e=5*d
f = exp(-d)
When the above code is compiled and executed, it produces the following result:
c = 12
d = 12.6570
e = 63.2849
f = 3.1852e-06
Example 2
Create a script file with the following code:
=
Hello World!
n=
2345
d=
2345
un =
790
rn =
5.6789e+03
c=
5679
Example 3
The following examples show the use of arithmetic operators on scalar data.
Create a script file with the following code:
a = 10;
b = 20;
c=a+b
d=a-b
e=a*b
f=a/b
g=a\b
x = 7;
y = 3;
z=x^y
c = 30
d = -10
e = 200
f = 0.5000
g=2
z = 343
Example 4
Create a script file and type the following code:
a = 100;
b = 200;
if (a >= b)
max = a
else
max = b
end
max = 200
If statement
Switch statement
For loops
While loops
Break statements
Loop Description
Type
if….end Statement
An if ... end statement consists of an if statement and a boolean expression
followed by one or more statements. It is delimited by the end statement.
Syntax
The syntax of an if statement in MATLAB is:
if <expression>
% statement(s) will execute if the boolean expression is true
<statements>
end
If the expression evaluates to true, then the block of code inside the if statement
will be executed. If the expression evaluates to false, then the first set of code
after the end statement will be executed.
Example
a = 10;
% check the condition using if statement
if a < 20
% if condition is true then print the following
fprintf('a is less than 20\n' );
end
fprintf('value of a is : %d\n', a);
When you run the file, it displays the following result:
a is less than 20
value of a is : 10
if...else...end Statement
An if statement can be followed by an optional else statement, which executes
when the expression is false.
Syntax
The syntax of an if...else statement in MATLAB is:
if <expression>
% statement(s) will execute if the boolean expression is true
<statement(s)>
else
<statement(s)>
% statement(s) will execute if the boolean expression is false
end
If the boolean expression evaluates to true, then the if block of code will be
executed, otherwise else block of code will be executed.
Example
Create a script file and type the following code:
a = 100;
% check the boolean condition
if a < 20
% if condition is true then print the following
fprintf('a is less than 20\n' );
else
% if condition is false then print the following
fprintf('a is not less than 20\n' );
end
fprintf('value of a is : %d\n', a);
When the above code is compiled and executed, it produces the following result:
if...elseif...elseif...else...end Statements
An if statement can be followed by one (or more) optional elseif... and an else
statement, which is very useful to test various conditions.
When using if... elseif...else statements, there are few points to keep in mind:
An if can have zero or one else's and it must come after any elseif's.
An if can have zero to many elseif's and they must come before the else.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
Syntax
if <expression 1>
% Executes when the expression 1 is true
<statement(s)>
elseif <expression 2>
% Executes when the boolean expression 2 is true
<statement(s)>
Elseif <expression 3>
% Executes when the boolean expression 3 is true
<statement(s)>
else
% executes when the none of the above condition is true
<statement(s)>
end
Example
Create a script file and type the following code in it:
a = 100;
% check the boolean condition
if a = = 10
% if condition is true then print the following
fprintf('Value of a is 10\n' );
elseif ( a = = 20 )
% if else if condition is true
fprintf ('Value of a is 20\n' );
elseif a = = 30
% if else if condition is true
fprintf('Value of a is 30\n' );
else
% if none of the conditions is true '
fprintf('None of the values are matching\n');
fprintf('Exact value of a is: %d\n', a );
end
When the above code is compiled and executed, it produces the following result:
It is always legal in MATLAB to nest if-else statements which means you can
use one if or elseif statement inside another if or elseif statement(s).
Syntax
The syntax for a nested if statement is as follows:
if <expression 1>
% Executes when the boolean expression 1 is true
if <expression 2>
% Executes when the boolean expression 2 is true
end
end
You can nest elseif...else in the similar way as you have nested if statement.
Example
Create a script file and type the following code in it:
a = 100;
b = 200;
% check the boolean condition
if( a == 100 )
% if condition is true then check the following
if( b == 200 )
% if condition is true then print the following
fprintf('Value of a is 100 and b is 200\n' );
end
end
fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );
While Loop
while <expression>
<statements>
end
An expression is true when the result is nonempty and contains all nonzero
elements (logical or real numeric). Otherwise, the expression is false.
Example:1
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example 2:
x=3
while (x<100)
x=x*3;
end
x=243
Remark: one can think of while loop as a combination of for loop and an if
statement. Here, the looping will keep going indefinitely as long as the
condition (x<100), is satisfied. Therefore, the value of x progresses from
3,9,27,81, to 243 when loop is terminated.
Example 3:
x = input(‘Enter a Number:’);
count = 0;
while x > 1
x = x/2;
count = count + 1;
end
display (count);
Enter a Number:
130
Count =
8
Example : 4
x = input(‘Enter an integer:’);
Fact = 1;
While x > 1;
Fact = fact * x;
End
Display(fact);
Enter a Integer:
12
Fact =
479001600
For loop
A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
b=3
for k = 1:5
b = b^k
end
Output
3
9
27
81
243
Remark: the outputs are 3^1,3^2,3^3,3^4 and 3^5. The value of “k” keeps
changing as we go through the loop.
Example: 2
sum1 = 0;
for k = 1:9
sum1 = sum1+ k;
end
Example: 3
sum1 = 0;
for k = 1:2:9
sum1 = sum1+ k;
end
sum1
Output
25
Output
24
b = [3 8 9 4 7 5];
sum1 = 0;
for k = 1:2:5
sum1 = sum1+ b(k);
end
sum1
Output
19
Example: 6
for a = 10:20
fprintf(‘value of a:%d\n’,a);
end
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
Output
18
for n = 1:2
for m = 1:3
fprintf(‘n = %3u m = %3u \r’, n, m)
end
end
When the code above is executed, the result will be:
Output
n=1 m=1
n=1 m=1
n=1 m=1
n=2 m=2
n=2 m=2
n=2 m=2
b = [3 5 7 4 9 8 3];
c = [2 3 5 7];
sum1 = 0;
for k = 1:4
sum1 = sum1+ b (c(k));
end
sum1
Output
24
Numerical methods and their applications: Curve fitting: Straight line fit,
Polynomial fit
MATLAB has an excellent set of graphic tools. Plotting a given data set or the
results of computation is possible with very few commands. You are highly
encouraged to plot mathematical functions and results of analysis as often as
possible. Trying to understand mathematical equations with graphics is an
enjoyable and very efficient way of learning mathematics. Being able to plot
mathematical functions and data freely is the most important step, and this
section is written to assist you to do just that.
Creating simple plots
The basic MATLAB graphing procedure, for example in 2D, is to take a vector
of x- coordinates, x = (x1; : : : ; xN), and a vector of y-coordinates, y = (y1; : : :
; yN), locate the points (xi; yi), with i = 1; 2; : : : ; n and then join them by
straight lines. You need to prepare x and y in an identical array form; namely, x
and y are both row arrays and column arrays of the same length.
Example:1
Plot a graph considering the vectors, x = (1; 2; 3; 4; 5; 6) and y = (3; -1; 2; 4; 5;
1)
>> x = [1 2 3 4 5 6];
>> y = [3 -1 2 4 5 1];
>> plot(x,y)
Note: The plot functions have different forms depending on the input arguments.
If y is a vector plot(y) produces a piecewise linear graph of the elements of y
versus the index of the elements of y. If we specify two vectors, as mentioned
above, plot(x,y) produces a graph of y versus x.
Example: 2
Create x as a vector of linearly spaced values between 0 and 2π. Use an
increment of π/100 between the values. Create y as sine values of x. Create a line
plot of the data.
x = 0:pi/100:2*pi;
y = sin(x);
>> xlabel('x = 0:2\pi')
>> ylabel('Sine of x')
>> title('Plot of the Sine function')
>>plot(x,y)
Multiple data sets in one plot
Multiple (x; y) pairs arguments create multiple graphs with a single call to plot.
>> x = 0:pi/100:2*pi;
>> y1 = 2*cos(x);
>> y2 = cos(x);
>> y3 = 0.5*cos(x);
>> plot(x,y1,'--',x,y2,'-',x,y3,':')
>> xlabel('0 \leq x \leq 2\pi')
>> ylabel('Cosine functions')
>>
legend('2*cos(x)','cos(x)','0.5*co
s(x)'
)
>> title('Typical example of
multipleplots')
>> axis([0 2*pi -3 3])
The result of multiple data sets in one graph plot is shown in Figure.
Example
Define x as 100 linearly spaced values between −2π and 2π. Define y1 and y2 as
sine and cosine values of x. Create a line plot of both sets of data.
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
plot(x,y1,x,y2)
Three Curves in single Plot
Plot three sine curves with a small phase shift between each line. Use the default
line style for the first line. Specify a dashed line style for the second line and a
dotted line style for the third line.
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
%figure
plot(x,y1,x,y2,'--',x,y3,':')
Plot three sine curves with a small phase shift between each line. Use a green
line with no markers for the first sine curve. Use a blue dashed line with circle
markers for the second sine curve. Use only cyan star markers for the third sine
curve
x = 0:pi/10:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
plot(x,y1,'g',x,y2,'b--o',x,y3,'c*')
Bifurcation Plots
x = linspace(0,3);
y1 = sin(5*x);
y2 = sin(15*x);
subplot(2,1,1);
plot(x,y1)
title('Top Plot')
ylabel('sin(5x)')
subplot(2,1,2);
plot(x,y2)
title('Bottom Plot')
ylabel('sin(15x)')
Subplots
x = linspace(0,6);
subplot(2,2,1); % plot sine function
plot(x,sin(x));
subplot(2,2,2); % plot cosine function
plot(x,cos(x));
subplot(2,2,3); % plot negative exponential function
plot(x,exp(-x));
subplot(2,2,4); % plot x^3
plot(x, x.^3);
Plots Circle
r = 2;
xc = 4;
yc = 3;
theta =
linspace(0,2*pi);
x = r*cos(theta) + xc;
y = r*sin(theta) + yc;
plot(x,y) axis equal
Plotting in 3-D
p = [1 7 0 -5 9];
X = [1 2 -3 4; 2 -5 6 3; 3 1 0 2; 5 -7 3 8];
polyvalm(p, X)
ans=
2307 -1769 -939 4499
The function poly is an inverse of the roots function and returns to the
polynomial coefficients. For example:
p2 = poly(r)
p2 =
Columns 1 through 3:
1.00000 + 0.00000i 7.00000 + 0.00000i 0.00000 + 0.00000i
Columns 4 and 5:
-5.00000 - 0.00000i 9.00000 + 0.00000i
x: I 2 3 4 5
y: 14 13 9 5 2
Here 11=5 values of (x, y) are given. We first fonn the following Table.
1
n
'Hercand in expressions that follow, E denotes L·
i=I
'Nt1etha1La= a+ a+ a ... (11 terms)= na
,_ )
.r; y;
14 I
I
13 4 i6
2
9 9 27
3
4 5 16 20
5 2 25 10
From lhc deta•,Is ava1•1able in the Table, we find that the normal cquaiio
the line of bcsl fit are•
43 = 5a + 15b,
97 = 15a + 55b.
OUTPUT
Enter lower limit, a:1
Enter upper limit, b:2
Enter no. of subintervals, n: 5
The approximate value of integral by Trapizoidal Rule is: 0.40592741
Program with Example 2:f=sin(x)
OUTPUT
Enter lower limit, a:2
Enter upper limit, b:8
Enter no. of subintervals, n: 5
The approximate value of integral by Trapizoidal Rule is: -0.23736200
Lab Program 6-Numerical Integration and Differentiation:Simpson’s method
Simpson’s 1/3 rule
Program Code Example 1 : SIMPSON 1/3 RULE FOR cos(x)-log(x)+exp(x)
OUTPUT
Enter lower limit a:0
a =0
simsons1
Enter lower limit a:4
a =4
l ) -o
=-)
-"I :>'I
,-,.(),-,)
I I - f)
-
::) )? -
---
r-,...-,,;
(:. 'J-'.
o -,l o
) ( --t ".l.) ( ,-.- ) (') -t") :.D
--.. \\;'.; QA . d
'?
,. = -· ,, ,,6 'J
o.)-1:" t'-v.. A
f-Y ,i,.:;_ iot e •y 'Y'>l'\ON1'
(1-) t -1 ,i;_-n
r(-->i)tl -1, r
ll1'ij1 (\- ::r_-,ll
c c c;)
..
2... ..,,')
1.'{ ,,_ o · · Nil
-t3 : . - '( 1'1\' )
.. - ..- --...
'X. -=.L- - A.
(' l-1'F'.) • ( I-Ill)- (..a..a.- .-1 i)
.... z
t
'h_vM½
Lab Program 7: Program code for Egien values and Eigen vectors
A=[8 -6 2;
-6 7 -4;
2 -4 3];
disp("Matrix");
disp(A)
%Eigenvalues and right eigenvectors of matrix A
[V,D]=eig(A)
OUTPUT:
Matrix
8 -6 2
-6 7 -4
2 -4 3
V=
0.3333 0.6667 -0.6667
0.6667 0.3333 0.6667
0.6667 -0.6667 -0.3333
D=
0.0000 0 0
0 3.0000 0
0 0 15.0000
OUTPUT
Lab Program 8c: Solution of nonlinear equation in single variable using Gauss-Siedal
I l
Z2 =
418 - 2(9 2375)- ( - 2-8715)] = 4[- 7 6Q:15] = - 1.9006
rd
3- Approximation
1 l
=
X3
2[15 - ( - 2 8723) - ( - l_9QQ6)) = 2[J9_7731) = 9.8866
1 I
y3 =
5[U - 3(9.8866)- 2(- 1.9006)] =
5[- 14.8584] = - 2.9117
I l
Z3 = [8 - 2(9 8866)- ( - 2-9717)] = [- 8.80] ] = - 220
4 4
4,.., Approxrma ion
1 l
x4 =
2[15 -(-29717)-(-UOD )) = i20_171] = 10086
1 I
y4=
5[11 - ;(l0086)- (-22004)] = 5[-14.S:i 4] = -29 l:i
I l
Z4 =
418 - 2(10.086)- ( - 2_9715)] =
4[- 9 2006 = - 2.3001
Y"' Approxrmation
1
X; =1 [15 - - 29' 15) - ( - 23001)] = 2[20.2 Hi]= 10.L,58
1 1
y5 = -=[ll ,-(10 l'.358) - :1( - 2 3001)] =
5(- 1480 I] = -29614
1 ]
25 = -[8 - 2(W 1358)- ( - 2_9614)1 =
41- 93102] = -2.32 5
1
x6 =il:i-(-2961· )-(-23275)] =
2[20.2$9] = lO.l 5
1
y6 =
5[11 - 3(10_144:i) - 2(-232J5)] =j [- 14_7784) = - 2-9::Si'
1 1
x =il:i -(- 29'557)- ( - 23333)] = [20.289) = lO.l 5
2
1 I
y =
5c11-3( 0.1 5)-2(- 2. 3 3)J =
51-! .,66sJ = -2.953
]
]0.1445) - ( - 2_9534)] = [ - 9.J356] = - 2.'.h39
4
Lab Program 8c: Code for Gauss-Siedal
OUTPUT:
Solution of the system is :
10.143142
-2.952420
-2.333466
9.000000
Lab-Program 8d: Solution of nonlinear equation in single variable using Newton
Raphson Method
21:.1iteration:
-0.4606
-'2 =0.6531---3.7839
Absoluteerror
•= h. x,1=105313 - o.65311= 0.1211
3rd iteration:
-,, -0.0418
x, =O.),i, - -3.1118
x, = 0.5179
Lab Program -8d: Code using Newton Raphson Method
while abs(fa)> e
fa = eval(subs(y,x,a));
ga = eval(subs(g,x,a));
if ga == O
disp('Division by zero.');
break;
end
b = a - fa/ga;
fprintf('step=%d\ta=%f\tf(a)=%f\n',step,a,fa);
a= b;
if step>N
disp('Not convergent');
break;
end
step = step + 1;
end
g=
11.8
11.6
dt2 dt 11.4
>, 11
10.4
y=
10.2
12+2*exp(-2*t)-4*exp(-t)
10
0 2 3
>> ezplot(y, [D 6])
Xk =
Columns 1 through 2
13.0000 + 0.0000i -2.0000 + 1.0000i
Columns 3 through 4
-1.0000 - 0.0000i -2.0000 - 1.0000i
...
Ub,uy Block ..,
El
El
Oe!K'ription 80
el in this
fa pi al
Ii . 5. ddjn,
ha\' rm I.
rt the output port represented
ill turn i.nl li.n
$ln4, _...
·• . . Bl k iagram f r •
A sine signal is gen (a source) and • sco c
rat th dis ith the
m ignals in f rm
r n"\3
H .7.
unn.in • a ti 11.
s.im.ul ( th lickin
( ►, altcma • , L T, r choose I.art
ck
bl k int.er-es L
2.3Slmullnk block I_
n\ libr ri
II k Ii
I
• 11 Ul Ul.
•
I
nt .
•
I
•
• m .
3. Viewing and analyzing simulation results
pl lt win
•
tl
n.
. . Bl di
'l in
dia ram f r
4. Modeling mechanical systems with Simulink
gOC>d
The ot,,jecli f"
a.n n...- dL-.h "'t.a.
f IIYI S: IC'n"L ....; a....;;.c,. u.l I" gi.n-.ba..l" inner
i<nbal arod plal:t 1. ' sirn.u.lal-c the obtained d l.""la,ntl
f ... ;H (.l)
L rqu .."lb.h.lS drivi:n l r,tqu4::! p li :...I b)r I.he dj. ""'I. te:r ZTI'brrier ..U'l:d
rea.ct::ion l b l.h.c .ill.dpce.n t ia."'u'\iC'r .ernbic!-r _
dH
,Fl n1H + H (2)
JI
( )
(5)
A. • C<>St"'COS0su,0[ I_ I I_]
- I J
_, ---- ---,i,--------,...'-.l_(s.t?"".,.>- J
,: ,-_-+-,_- .,,,;b-- _ (6
,_-+-,_+J_ ,_+1_ ..... ,.. _ ....... -----
(8)
..
e blue su.bsysbecn. oon.:ta.i:ns the Stewart plal:form pla.rtl:P" in. £i:g_ _ 'The si.rru. .. ala.ti..on
O"I..Od.e.l in £ig.. 1.:8 is t::h..e c.o:n:trol oI the Ste:"7a..rt"pla.t:form's .a:n,otio:n "'i. l:he: f.n.-lcarprop-0.rt::ional-
i.nt:.egra..l-dc.riva.l:ivc (Pl.D) F.eed.back. sy:5-1_C:Ln. pr t:c-d in.fig_ 19_
Cl)
CMM#-!M\itM
a
0
"''""
15 £-#;t##h► l;GH•i-ifiPM,1---
" .
- ··.
·
"
•
0
..
..
\\tllflll• S.,,,oca,,_,
Wlwtll Slfflsc.p,11Mull!
.. ,_ AIIJ'VA ,,. OJ•ll)JSTI
0 "
, •............. ft,