Mat Lab Manual - Updated
Mat Lab Manual - Updated
DEPARTMENT OF MECHANICAL
ENGINEERING
LAB MANUAL
Prepared by:
Dr. Manjunath Y J
Supported by:
Dr. Roopa K M
Dr. Maya B S
AY 2023 - 24
COURSE OBJECTIVES
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.
Features of MATLAB
Following are the basic features of MATLAB:
It is a high-level language for numerical computation, visualization and application
development.
It also provides an interactive environment for iterative exploration, design and
problem solving.
It provides vast library of mathematical functions for linear algebra, statistics, Fourier
analysis, filtering, optimization, numerical integration and solving ordinary differential
equations.
It provides built-in graphics for visualizing data and tools for creating custom plots.
MATLAB's programming interface gives development tools for improving code
quality, maintainability, and maximizing performance.
It provides tools for building applications with custom graphical interfaces.
It provides functions for integrating MATLAB based algorithms with external
applications and languages such as C, Java, .NET and Microsoft Excel.
Uses of MATLAB
Following are some additional shortcuts that are not listed on menu items.
.
MATLAB Windows
Window Purpose
Notation Purpose
EXPERIMENTS - 1
\ 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
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; ← 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
>> vb= linspace(30,10,11) 11 elements, first element 30, last element
10
vb = 30 28 26 24 22 20 18 16 14 12 10
MATLAB will execute the above statement and return the following result:
m=
1 2 3
4 5 6
7 8 9
>> b=[7 2 76 33 8 The enter key is pressed a new line is entered
1 98 6 25 6
5 54 68 9 0]
Ans
b= 7 2 76 33 8
1 98 6 25 6
5 54 68 9 0
Rows of a matrix can also be entered as vectors using the notation for
creating vectors with constant spacing, or the linspace command. For
example
>> A=[1:2:11; 0:5:25; linspace(10,60,6); 67 2 43 68 4 13]
A=
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
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.
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
2314 -2376 -249 4695
2256 -1892 -549 4310
r=
-6.8661 + 0.0000i
-1.4247 + 0.0000i
0.6454 + 0.7095i
0.6454 - 0.7095i
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
Experiment 2:
% MATLAB code for syms function that creates a variable
% dynamically and automatically assigns
% to a MATLAB variable with the same name
syms x
% Declare the function
f1= sin(x);
% inline creates a function of string containing in f1
f = inline(f1);
a=input('Enter lower limit, a:');
b=input('Enter upper limit, b:');
n=input('Enter no. of subintervals, n: ');
h=(b-a)/n;
S0=0;s1=0;
s0=f(a)+f(b);
for i=1:n-1
x=a+i*h;
s1=s1+f(x);
end
s=(h/2)*(s0+2*s1);
fprintf('The approximate value of integral by Trapizoidal Rule is: %11.8f\n\n',
s);
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
Simpson’s 1/3 rule
Example 1: SIMPSON 1/3 RULE FOR cos(x)-log(x)+exp(x)
% MATLAB code for syms function that creates a variable
% dynamically and automatically assigns
% to a MATLAB variable with the same name
syms x
% Declare the function
f1 = cos(x)-log(x)+exp(x);
% inline creates a function of string containing in f1
f = inline(f1);
a=input('Enter lower limit a:')
b=input('Enter upper limit b:')
n=input('Enter the no. of subinterval:')
if rem(n,2) ==1
fprintf('\n Please enter valid n!!!');
n=input('\n Enter n as even number')
end
h=(b-a)/n;
% X stores the summation of first and last segment
X = f(a)+f(b);
% variables Odd and Even to store
% summation of odd and even
% terms respectively
Odd = 0;
Even = 0;
for i = 1:2:n-1
xi=a+(i*h);
Odd=Odd+f(xi);
end
for i = 2:2:n-2
xi=a+(i*h);
Even=Even+f(xi);
end
% Formula to calculate numerical integration
% using Simpsons 1/3 Rule
I = (h/3)*(X+4*Odd+2*Even);
disp('The approximation value of integral by Simsons 1/3 Rule is: ');
disp(I)
OUTPUT
Enter lower limit a:0
a=
0
Enter upper limit b:10
b=
10
Enter the no. of subinterval:5
n=
5
Please enter valid n!!!
Enter n as even number6
n=
6
The approximation value of integral by Simsons 1/3 Rule is: Inf
OUTPUT
Enter lower limit a:0
a=
0
Enter upper limit b:10
b=
10
Enter the no. of subinterval:6
n=
6
The approximation value of integral by Simsons 1/3 Rule is: 2.4492
Example 3:
% MATLAB code for syms function that creates a variable
% dynamically and automatically assigns
% to a MATLAB variable with the same name
syms x
% Declare the function
f1 = log(x);
% inline creates a function of string containing in f1
f = inline(f1);
a=input('Enter lower limit a:')
b=input('Enter upper limit b:')
n=input ('Enter the no. of subinterval:')
h=(b-a)/n;
if rem(n,2) ==1
fprintf('\n Please enter valid n!!!');
n=input('\n Enter n as even number')
end
% X stores the summation of first and last segment
X = f(a)+f(b);
% variables Odd and Even to store
% summation of odd and even
% terms respectively
Odd = 0;
Even = 0;
for i = 1:2:n-1
xi=a+(i*h);
Odd=Odd+f(xi);
end
for i = 2:2:n-2
xi=a+(i*h);
Even=Even+f(xi);
end
% Formula to calculate numerical integration
% using Simpsons 1/3 Rule
I = (h/3)*(X+4*Odd+2*Even);
disp('The approximation value of integral by Simsons 1/3 Rule is:');
disp(I)
Output:
simsons1
Enter lower limit a:4
a=
4
Enter upper limit b:5.2
b=
5.2000
Enter the no. of subinterval:6
n=
6
The approximation value of integral by Simsons 1/3 Rule is:
1.8278
Experiment 4
Linear and Nonlinear Equations: Eigen values, Eigen vectors, Solution of linear
algebraic equations using Gauss Elimination and LU decomposition, Solution of
nonlinear equation in single variable using Gauss-Siedal and Newton-Raphson
method.
Eigen Values
Example 1:
Eigenvalues and EigenVectors:
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:
solution is x=9.000000e+00
solution is x=-3.600000e+01
solution is x=3.000000e+01
for j=i+1:n
guess=guess+A(i,j)*x_old(j);
end
x(i)=(1/A(i,i))*(b(i)-guess);
end
iter=iter+1;
normVal=norm(x_old-x);
end
fprintf('Solution of the system is : \n%f\n%f\n%f\n%f\n%f in %d
iterations',x,iter);
OUTPUT:
Solution of the system is :
10.143142
-2.952420
-2.333466
9.000000
% Input Section
y = input('Enter non-linear equations: ');
a = input('Enter initial guess: ');
e = input('Tolerable error: ');
N = input('Enter maximum number of steps: ');
% Initializing step counter
step = 1;
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
OUTPUT:
g=
xn=[2 3 4 4]
N=length(xn)
n=0:N-1
k=0:N-1;
WN=exp(-1j*2*pi/N);
nk=n'*k;
WNnk=WN.^nk;
Xk=xn*WNnk
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
Resl =
h = 1;
tspan = [0 3];
f = @(t,y) 2*t;
dydt(1) = 0;
t(1) = 0;
y = @(t) t.^2;
x = linspace(0,tspan(end));
figure
plot(x,y(x))
xlabel('t'), ylabel('y(t)')
hold on
plot(t,dydt,'-o')
h = h/2;
end
legend('Exact Solution', 'h=1','h=0.5','h=0.25','h=0.125',...
'Location','NorthWest')
title('Solution of y''=2t using Euler''s method with several step sizes')
f = input('Enter your function: '); %right hand side of ODE
to= input('Enter intial value of independent variable: ');
yo =input('Enter intial value of dependent variable: ');
h=input('Enter step size: ');
tn =input('Enter point at which you want to evaluate solution: ');
n=(tn-to)/h;
t(1)= to; y(1) = yo;
for i=1:n
t(i+1) = to + i*h;
k1= h*f (t(i),y(i));
k2= h*f(t(i+1),y(i)+k1);
y(i+1) = y(i) + (1/2)*(k1+k2);
fprintf('y(%.2f) = %.4f\n', t(i+1),y(i+1))
end
Output:
Enter your function: @(t,y) -20*y+ 7*exp(-0.5*t)
Enter intial value of independent variable: 0
Enter intial value of dependent variable: 5
Enter step size: 0.1
Enter point at which you want to evaluate solution: 0.2
y(0.10) = 4.9829
y(0.20) = 4.9667
Example 2
Write a MATLAB program to plot the ratio of M/F as a function of crank angle
α from 0 to 180 degrees. Given a = 50 mm and l = 150 mm. Determine the value
of crank angle α for which the ratio M/F is maximum and the corresponding
value of M/F.
MATHEMATICAL MODEL
Free-body diagram of the system is shown in Figure.
Differentiating gives
TRUSS PROBLEM
Figure shows the members CJ and CF of the loaded truss cross which are not
connected to members BI and DG. Determine the values of α for which the truss
cannot be in equilibrium.
Write a MATLAB program to plot the forces in members BC, JC, IC and IG as a
function of α.
MATHEMATICAL MODEL
• Free-body diagram
Joint I:
Note in the above that substitutions have been made in order to express each
force explicitly in terms of θ. This has been done primarily for completeness.
The program below shows that the explicit substitution is not necessary. The
computer will substitute automatically provided each force is expressed in terms
of functions that have been previously defined.
th=0:0.05:2*pi;
Jy=10+6*sin (th)–2*cos (th);
AJ=–6*sin (th);
BC=–6*cos (th);
JC=sqrt (13)/2*(AJ + Jy);
IJ=–3/sqrt (13)*JC;
IC=5;
IG=IJ–3;
plot(th,BC,th,JC,th,IC,th,IG)
legend (‘BC’,‘JC’,‘IC’,‘IG’)
xlabel (‘Theta (rads)’)
ylabel (‘Force (kN)’)
Solution
CABLE PROBLEM
A 5 kg block is attached to a cable and to a spring as shown in Figure.
The constant of the spring is k = 3 kN/m and the tension in the cable is 30 N.
When the cable is cut,
(a) derive an expression for the velocity of the block as a function of its
displacement x,
(b) determine the maximum displacement xm and the maximum speed vm,
(c) plot the speed of the block as a function of x for 0 ≤ x ≤ xm.
MATHEMATICAL MODEL
Free-body diagram of the block before and after the cable is cut is shown in
Figure For the static case we have entire forces are in equilibrium.
T + R – W = 0 with T = 30 N, W = mg = 50 N from which R = 20 N
But,
R = kδst or δst = R/k
k which is initial tension in
spring.
δ st = 20/3000 = 0.006667 m
Substituting yields
Solution
MATHEMATICAL MODEL
Solution
The first three natural frequencies are The corresponding mass-ortho
0.7071 normalized mode shapes are
1.4142 Mode- 1
1.7321 -0.3651
-0.5477
-0.3651
Mode - 2 Mode- 3
0.8165 -0.4472
-0.0000 0.4472
-0.4082 -0.4472
RLC PROBLEM
Figure shows an electrical circuit with resistors and voltage sources.
Write a MATLAB program to determine the current in each resistor using the
mesh current method based on Kirchhoff’s voltage law
MATHEMATICAL MODEL
Let i1, i2, i3 and i4 be the loop currents as shown
According to Kirchhoff’s voltage law: sum of voltage around closed circuit is
zero. Thus, the loop equations can be written by taking in each loop clockwise
direction as reference.
The equations can be written in matrix form as follows: