0% found this document useful (0 votes)
88 views60 pages

Updated MATLab Manual Content

The document provides an introduction to MATLAB for mechanical engineers. It covers MATLAB capabilities and interfaces, basic operations and functions, vectors, matrices, and other essential MATLAB concepts.

Uploaded by

Acchyutjh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views60 pages

Updated MATLab Manual Content

The document provides an introduction to MATLAB for mechanical engineers. It covers MATLAB capabilities and interfaces, basic operations and functions, vectors, matrices, and other essential MATLAB concepts.

Uploaded by

Acchyutjh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Basic Manual on “Mechanical Engineers and MATLAB”

CHAPTER 1
INTRODUCTION

MATLAB Software Version:


R2020a OR R2020b
R=Release a = Released in Spring b= released in fall,
2020 =Year of Release

1.1 Capabilities of MATLAB


• Dealing with Matrices and Arrays
• 2-D and 3-D Plotting and graphics
• Linear Algebra
• Algebraic Equations
• Non-linear Functions
• Statistics
• Data Analysis
• Calculus and Differential Equations

• Numerical Calculations
• Integration
• Transforms
• Curve Fitting

1
Basic Manual on “Mechanical Engineers and MATLAB”

1.2 GUI (Graphical User Interface) of MATLAB

Fig. 1.1 GUI of MATLAB

2
Basic Manual on “Mechanical Engineers and MATLAB”

1.3 Commonly Used Operators & Special Characters

Table. 1.1 Operators & special characters

OPERATOR PURPOSE
+ Plus; addition operator.
- Minus; subtraction operator.
* Scalar and matrix multiplication operator.
.* Array multiplication operator.
^ Scalar and matrix exponentiation operator.
.^ Array exponentiation operator.
\ Left-division operator.
/ Right-division operator.
.\ Array left-division operator.
./ Array right-division operator.
Colon; generates regularly spaced elements and
: represents an entire row or column.
() Parentheses; encloses function arguments and array
indices; overrides precedence.
[] Brackets; enclosures array elements.
. Decimal point.
… Ellipsis; line-continuation operator
, Comma; separates statements and elements in a row
; Semicolon; separates columns and suppresses
display.
% Percent sign; designates a comment and specifies
formatting.
_ Quote sign and transpose operator.
._ Non-conjugated transpose operator
= Assignment operator

3
Basic Manual on “Mechanical Engineers and MATLAB”

1.4 Special Variables & Constants

Table. 1.2 Special Variables


Name Meaning
ans Most recent answer.
eps Accuracy of floating-point precision.
i,j The imaginary unit √-1.
Inf Infinity.
NaN Undefined numerical result (Not a Number).
pi The number π

1.5 Command Syntax


>> a= 12 ; % variable a is assigned with value of 12

Matlab Prompt Comment operator


Assign Operator Suppresses the command output

Note: Semicolon (;) indicates end of statement. However, it suppresses and hides the
MATLAB output for an expression.

4
Basic Manual on “Mechanical Engineers and MATLAB”

CHAPTER 2
GETTING USED TO MATLAB BASICS

2.1 Basics of MATLAB

Type the following expression in the Command Window:

>> x=6;
>> y=x+9
And press ENTER, to display the result
Result returned is y =15

Tip 1: If you feel the gap between 2 individual lines are too large, the type
>> format compact

The default value of “pi” is 3.1416, you check by typing following commands

>> pi %presss Enter


ans =
3.1416

Value of “pi” can be altered by assigning various values to it


>> pi=6
pi =
6

Value of newly assigned variables can be erased by typing following commands


>> clear pi
>> pi
ans =
3.1416

5
Basic Manual on “Mechanical Engineers and MATLAB”

You can have multiple assignments on the same line


>> m=3;r=9;z=m*r
z =
27

Tips 2: The who command displays all the variable names you have used. MATLAB
will execute the above statement and return the following result.

>> who
Your variables are:
m r z

whos command displays little more about the variables:


• Variables currently in memory
• Type of each variable
• Memory allocated to each variable
• Whether they are complex variables or not

>> whos z
Name Size Bytes Class
z 1x1 8 double

2.1.1 Examples on Basic Operations

>> 4^3 %4 raised to the power of 3

ans =
64

>> tan(pi/4) %tan of angle pi/4 in radian

ans =
1.0000

6
Basic Manual on “Mechanical Engineers and MATLAB”

>> cosd(180) %cos of angle 180 deg

ans =
-1

>> 8/0 % Divide 8 by 0

ans =
Inf
{warning: division by zero}

Tips 3: Use clc command to clear the commands in command window but not the
data in the variables
Tips 4: Use clear command to erase the memory or data in workspace section

>> y=sqrt(36)
y =
6

>> 25/5 % right division operator i.e., 25 divided by 5

ans =
5

7
Basic Manual on “Mechanical Engineers and MATLAB”

2.2 Trigonometric & Hyperbolic Functions

Table. 2.1 Commonly used trigonometric & Hyperbolic Functions


Function Description
sin(x) Evaluates the sine of x, where x is in radians
cos(x) Evaluates the cosine of x, where x is in radians
tan(x) Evaluates the tangent of x, where x is in radians
asin(x) Evaluates the arcsine or inverse sine of x, where x must be between -1 & 1.
The function returns an angle in radians between – π/2 & π/2
acos(x) Evaluates the arccosine or inverse cosine of x, where x must be between -1
& 1. The function returns an angle in radians between 0 & π

atan(x) Evaluates the arctangent or inverse tangent of x, where x must be between


-1 & 1. The function returns an angle in radians between – π/2 & π/2

atan2(y, x) Evaluates the arctangent or inverse tangent of y/x, The function returns an
angle in radians between −π & π depending upon the signs of x & y

sinh(x) Evaluates the hyperbolic sine of x, which is equal to (ex – e –x )/2


asinh(x) Evaluates the inverse hyperbolic sine of x, which is equal to
ln (x +(x2+1) 1/2

2.3 Creating the Vectors


Row vectors are created by enclosing the set of elements in square brackets, using
space or comma to delimit the elements.

Example:

>> r = [9 84 20 10 33]
r =
9 84 20 10 33

>> m = [5,8,5,2,1]
m =
5 8 5 2 1

8
Basic Manual on “Mechanical Engineers and MATLAB”

Column vectors are created by enclosing the set of elements in square brackets,
using semicolon (;) to delimit the elements.

Example:
>> c = [1; 2; 4; 5; 6]
c =
1
2
4
5
6

Colon (:) is one of the most useful operators in MATLAB. It is used to create vectors,
subscript arrays, and specify for iterations.

Example:
>> 10:16
ans =
10 11 12 13 14 15 16

>> 10:2:20 % this creates a row matrix from 10 to 20 having intervals of 2

ans =
10 12 14 16 18 20

We can also create equally spaced vectors given the starting & ending numbers. It
creates regularly spaced vector
>> x = linspace(-3,3,6) % from -3 to 3, generate 6 numbers with equal intervals

x =
-3.0000 -1.8000 -0.6000 0.6000 1.8000 3.0000

9
Basic Manual on “Mechanical Engineers and MATLAB”

2.4 Generating Matrices

Magic Square: magic (n) returns an n by n matrix constructed from the integers 1
through n^2 with equal sums of rows, columns and diagonal values. Note: The order
n must be a scalar greater than or equal to 3.
>> f=magic(3)
f =
8 1 6
3 5 7
4 9 2

>> sum(f) % generate sum of column wise of “f” matrix

ans =
15 15 15

>> sum(f,2) % generate sum of row wise of “f” matrix

ans =
15
15
15

Zero Matrix: The zeros() function creates an array of all zeros.

>> zeros(4) % this generates 4x4 matrix of zero elements


ans =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

>> d=zeros(2,4) % this generates 2x4 matrix of only zero elements


d =
0 0 0 0
0 0 0 0

10
Basic Manual on “Mechanical Engineers and MATLAB”

Ones Matrix: ones() function generates a matrix of all ones


>> a=ones(3,6) % this generates 3x6 matrix of all ones elements

a =
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1

Eye matrix: eye() function generates an identity matrix.


>> eye(4) % generates an 4x4 matrix of identity matrix

ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

11
Basic Manual on “Mechanical Engineers and MATLAB”

2.5 Operations In MATLAB


In MATLAB, a matrix is created by entering each row as a sequence of space or
comma separated elements, and end of a row is demarcated by a semicolon.

Example:
>> A=[1 2 3; 3 2 1; 1 2 3]; B=[4 5 6; 6 5 4; 4 5 6];
>> X=A+B
X =
5 7 9
9 7 5
5 7 9

>> Y=A-B
Y =
-3 -3 -3
-3 -3 -3
-3 -3 -3

>> Z=A*B
Z =
28 30 32
28 30 32
28 30 32

With a dot product we multiply the corresponding elements of two equally sized
matrices using the .* operator.
Example:
>> E = [2 1;4 3]
F = [3 4;5 1]
E =
2 1

12
Basic Manual on “Mechanical Engineers and MATLAB”

4 3
F =
3 4
5 1

Tips 5: Use of help command, is very handy, he provides info on operations,


functions, etc. Display help text in Command Window.
>> G=Z'
G =
28 28 28
30 30 30
32 32 32

>> T= [ 10 8 9; 7 4 5; 6 1 2];
>> V=det(T) % generates value for determinant of T matrix

V=
5.0000

>> x= [2 3;6 1]; % generates an inverse of x matrix

>> c=inv(x)
c =
-0.0625 0.1875
0.3750 -0.1250

Use of colon in matrix:


>> v=c(:,1) % Displays only 1st column of c matrix

v =
-0.0625
0.3750

13
Basic Manual on “Mechanical Engineers and MATLAB”

>> v=c(2,:) % Displays 2nd row of c matrix

v =
0.3750 -0.1250

2.6 Determining the roots of the Polynomial Equations:

1. Find the root of 2𝑠4+3𝑠3−15𝑠2−𝑠+10 = 0


Solution:
>> t=[2 3 -15 1 10];
>> d=roots(t)
d =
-3.5438
1.7131
1.0878
-0.7571

2. Solve equation v-u-3t2 =0 for v


Solution:
% just ensure you clear your workspace windows so that previously operated values don’t interfere
undesirably
>> solve( ' v – u - 3*t^2 = 0' , 'v' )
ans =
3*t^2 + u

3. Solve the equations


5x+9y=6
9x+5y=1
Solution:
Such a system of linear equations can be written as a single Matrix equation where
Ax=b, where A is the co-efficient matrix, b is the column vector containing the right-

14
Basic Manual on “Mechanical Engineers and MATLAB”

hand side of the linear equations and X is the column vector representing the solution
as shown in the below program
>> z=[5 9; 9 5];
>> r=[6;1];
>> m=inv(z)*r
m =
-0.3750
0.8750

4. Solve the following polynomials


x + 3y - 2z = 5
3x + 5y + 6z = 7
2x + 4y + 3z = 8
Solution:
% you may use inv() command of A-1as both represent the inverse of a matrix.
>> i=[1 3 -2; 3 5 6; 2 4 3];
>> m=[5;7;8];
>> x=inv(i)*m
x=
-15.0000
8.0000
2.0000

15
Basic Manual on “Mechanical Engineers and MATLAB”

2.7 Plotting Graphs

1. Plot a random matrix of line graph


>> S = [5 6 8 3 1 2 4 5];
>> plot(S) % wait for few seconds an new tab will display the below
graph

Chart 2.1. Line Graph

16
Basic Manual on “Mechanical Engineers and MATLAB”

2. Plot (x.y) of vector y v/s x

Year 1988 1989 1990 1991 1992 1993 1994


Sales (millions) 8 12 20 22 18 24 27

Solution:
>>Year=[1988:1:1994];
>> Sales=[8 12 20 22 18 24 27];
>> plot(Year,Sales), xlabel('Year'),
ylabel('Sales(Millions)'),title('Sales v/s Years')
%you may use the aforementioned xlabel, ylabel or title in programming or you may individually
choose from options of figure windows individually

Chart 2.2 Sales v/s Years


Note: Make use of the tool bar options in the chart window, where there are plenty
of user-friendly tools, which can give you access to direct insertion of legends, title,

labels, formatting etc.


Fig.2.1 Options in chat window

17
Basic Manual on “Mechanical Engineers and MATLAB”

Just double tap that red encircled icon and you shall be greeted with numerous tools
to operate either your graphs, charts, etc.

Fig. 2.2 Useful tool to edit plot


% Make use of the edit tool bar to customize the charts, as per your requirements.
%Double click on the line to customize the xlabel, ylabel, title, etc.

3. Plot a random Sine Curve:


Solution:
>> x=linspace(0, 4*pi, 100);
>> y=sin(x); %Calculate y=sin(x) of the x-array

>> plot(x,y) %Plot the y-array

>> comet(x,y) %animation

18
Basic Manual on “Mechanical Engineers and MATLAB”

Chart 2.3 Random sinusoidal waves

19
Basic Manual on “Mechanical Engineers and MATLAB”

4. Generate a graph by adding plots to an existing figure.


Solution:
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y)
>> hold on
>> y2 = cos(x);
>> plot(x,y2)

Chart 2.4 Multiple lines in same chart

Table 2.2 Color Specifications and Line Style Options

Actual MATLAB
name name Style Symbol
White w Plus +
Black k Solid -
Green g Dash-dot -.
Cyan c Dotted :
Blue b Dashed --
Red r Circle o
Magenta m Point .
Yellow y Star *

20
Basic Manual on “Mechanical Engineers and MATLAB”

5. Plot a function y=3x3-26x+10, its first derivative & second derivative in same
plot
y′=9x2-26
y″=18x for -2≤ x ≤4
Solution:
>> x=[-2:0.01:4];
>> y=3*x.^3-26*x+10;
>> yd=9*x.^2-26;
>> ydd=18*x;
>> plot(x,y,'k');
>> hold on;
>> plot(x,yd,'-b');
>> hold on;
>> plot(x,ydd,'g');
>> hold off;

Chart 2.5 1st & 2nd Derivative

21
Basic Manual on “Mechanical Engineers and MATLAB”

6. Generate a random Area Plot.


Solution:
>> t=[0:0.1:22];
>> a=[sin(t).*cos(2.*t)];
>>area(a),title('AreaPlot'),xlabel('Time(seconds)'),ylabe
l('Amplitude(mm)')

Chart 2.6 Area Plot

22
Basic Manual on “Mechanical Engineers and MATLAB”

7. Generate a random Bar plot


Solution:
>> x=[2 9 6 4 3 7 5 8 1];
>> y=[0.2 3 5.5 6.6 1.3 7 2 1 4.5];
>> bar(x,y),title('Random Bar Plot'), xlabel('whole
numbers'), ylabel('decimal integers')

Chart 2.7 Random Bar Plot

23
Basic Manual on “Mechanical Engineers and MATLAB”

8. Generate a random 3D plot of your own values.


𝒙 = √𝒕 𝒔𝒊𝒏𝒕(𝟐𝒕) , 𝒚 = √𝒕 𝒄𝒐𝒔(𝟐𝒕) , 𝒛 = 𝟎. 𝟓𝒕
for 0 ≤ t ≤ 6π
Solution:
>> t=0:0.1:6*pi;
>> x=sqrt(t).*sin(2*t);
>> y=sqrt(t).*cos(2*t);
>> z=0.5*t;
>>plot3(x,y,z), xlabel('x values'), ylabel('y values'),
zlabel('z values'), title('Generating a Helical Curve');
grid on

24
Basic Manual on “Mechanical Engineers and MATLAB”

Chart 2.8 Helical Curve

9. Generate a random Meshgrid Plot, by using x,y & z variables.


Solutions:
% Three-dimensional plots typically display a surface defined by a function in two variables, z =
f(x,y) . To evaluate z, first create a set of (x,y) points over the domain of the function using
“meshgrid”.

>> [x,y]=meshgrid(-3:0.1:3, -3:0.2:3);


>> z=x.*exp(-x.^2-y.^2);
>> surf(x,y,z)

Note:
.* implies array multiplication operator
.^ implies array exponential operator

25
Basic Manual on “Mechanical Engineers and MATLAB”

Chart 2.9 Meshgrid

10. Plot a sine function as Meshgrid form.

Solution:

>> [x,y]=meshgrid(-7.5:0.2:7.5,-7.5:0.2:7.5);

>> k=sqrt(x.^2+y.^2)+eps;

>> z=sin(k)./k;

>> mesh(x,y,z); grid on

26
Basic Manual on “Mechanical Engineers and MATLAB”

Chart 2.10 Sine Mesh grid form

27
Basic Manual on “Mechanical Engineers and MATLAB”

11. Generate a Ribbon 3D plot with x,y & z variables.

Solutions:

>> [x,y]=peaks(30);

>> z=[(x.^2)-(y.^2)];

>> ribbon(z); zlabel('z axis'); ylabel('y axis');


xlabel('x axis'); title('Ribbon Plot'); grid on

Chart 2.11 Ribbon Plot

28
Basic Manual on “Mechanical Engineers and MATLAB”

12. Find the temperature at various times of the day in-between above timings.

Time of the 1 2 3 4 5 6 7 8 9
Day
Temperature 25.4 25.7 26 26.8 27 27.7 28 28.5 5.7
in Celsius

Solution:

>> d=1:9;

>> t=[25.4,25.7,26,26.8,27,27.7,28,28.5,5.7];

>> di=[1.5,2.5,4.75,5,6.75];

>> ti=spline(d,t,di); % Syntax for Spline Yinterpolated=spline(xdata, ydata,


xinterpolated);
>> [di;ti]

ans =

1.5000 2.5000 4.7500 5.0000 6.7500

25.6227 25.7773 26.9132 27.0000 27.6603

29
Basic Manual on “Mechanical Engineers and MATLAB”

13. Interpolate a Karizma motorcycle speed when reaching & exiting out from the
REVA main gate.

Time (sec) 0 10 20 30 40 50 60 70 80 90
Speed 33 25 10 0 0 18 25 38 45 60
(km/hr)
Solution:

% t=time, s=speed, ti=interpolated time & si=interpolated speed

>> t=0:10:90;

>> s=[33 25 10 0 0 18 25 38 45 60];

>> ti=[5:10:85];

>> si=spline(t,s,ti);

>> [ti;si] , plot(t,s);hold on;plot(ti,si,'b*')

ans =

5.0 15.0 25.0 35.0 45.0 55.0 65.0 75.0


85.0

30.8 17.4 4.2 -2.3 8.7 22.0 31.2 42.0

30
Basic Manual on “Mechanical Engineers and MATLAB”

49.8

Chart 2.12 Interpolation of motorcycle speed

14. Using a loop function, script a MATLAB code to print the sum of natural
numbers from 3 to 13.

Solution:

>> n=0;

>> i=3;

>> for i=3:13;

n=n+i;

i=i+1;

end

>> n

n =
88

31
Basic Manual on “Mechanical Engineers and MATLAB”

CHAPTER 3

SOLVING MECHANICAL PROBLEMS

1. Plot the variation of natural frequency and the time period with static deflection
of an undamped system using MATLAB for deflection range of 0 to 0.5 m.
Solution:
𝟏 𝐠 𝟏 𝛅𝐬𝐭
𝒇𝒏 = 𝟐 √𝛅𝐬𝐭 𝑻 = 𝒇𝒏 𝑻 = 𝟐𝛑√ 𝐠

>> g=9.81;
>> for i=1:101
d(i)=(0.5)*(i-1)/100;
f(i)=(g/d(i))^0.5;
T(i)=2*pi/f(i);
end
>> plot(d,f);
>> hold on; plot(d,T); hold off

Chart 3.1 Static deflection of undamped vibrations

32
Basic Manual on “Mechanical Engineers and MATLAB”

2. Solve for seven cycles, the response of an unforced system given by the equation
m x” + c x’+ kx = 0
ξ = 0.2 m = 2 kg k = 150 N/m x (0) = 0.02 m x’ (0) = 0

Solution:
MATLAB uses Runge-Kutta method to solve the differential equations, which are only
in the form of first order equations only.
But the above equations are second order differential equations.
Let m x” + c x’+ kx = 0 …………………….……………………….(1)

Consider x’=v …………………………………………………………….(2)

So, the equation turns out to be mv’+cv+kx=0

−c k
Eqn. 1 shall be formulated as v=( m ) 𝑣 − (m)𝑥

Now the 2nd Order DE is reduced to 2 different 1st order DE


For our ease, consider x=y(1) and x’=y(2)
Y’(x)=y(2)
In order to evaluate ‘c’, compare eqn (1) with this eqn

x’’+2ωnξ x+ ωn2 =0
c
m
= 2 ξ ωn and ωn2 = mk

By using the values of ‘k’ and ‘m’, calculate the different values of ‘c’ corresponding
to each value of ξ. Once the values of ‘c’ are known, equations (4) and (5) can be
solved using MATLAB.
Now, we require to solve for 5 cycles. So first we need to find the damped period of
system and later the time interval.
Natural frequency ωn = (k / m)1/2 = 8.6 rad/sec
For ξ = 0.2
Damped natural frequency ωd = ωn (1- ξ2)1/2 = 8.42rad/sec
Damped time period Td = 2π/ ωn = 0.73 sec
We need for 7 times the time cycles i.e, 0.63*5 = 5.14 sec
>>edit unfocrced1
% the moment you type the aforementioned line, a new editor window would pop up.
% It is to be note that we have to create a new function as to represent the MATLAB for the
retrieved equations separately by defining them in “.m” files

33
Basic Manual on “Mechanical Engineers and MATLAB”

% 𝑚𝑐 = 2𝜉 ωn = 3.44 % ωn2 =mk = 75

function yp = unforced1(t,y)
yp = [y(2) ;(-(3.44*y(2))-(75*y(1)))];
end
%we are assigning yp to have 2 different values
%Initially open a M-file from “New Script” and input the 2 aforementioned lines.
%Main point to ponder is, begin the script with “function” and save that file in “unforced1.m”
only. As the MATLAB can accesses the code when you enter this argument.
%Now enter the below lines in command window section
>> tspan=[0 4]; % tspan represents time interval

>> y0=[0.02;0]; % y0 represents the initial conditions

>> [t,y]=ode45('unforced1',tspan,y0);

>> plot(t,y(:,1)); grid on; xlabel('time');


ylabel('Displacement'); title('Displacement v/s Time')

Chart 3.2 Displacement v/s Time

34
Basic Manual on “Mechanical Engineers and MATLAB”

3. Using MATLAB, generate a table showing velocity against height from which a
body is dropped vertically. Consider the height from 0 m to 50 m with an
increment step of 5 m.

Solution:

format short g
g=9.81;
iteration=1;
for height=0:5:50;
velocity=sqrt(2*g*height);
table(iteration,1)=height;
table(iteration,2)=velocity;
iteration=iteration+1;
end
table

table =
0 0
5 9.9045
10 14.007
15 17.155
20 19.809
25 22.147
30 24.261
35 26.205
40 28.014
45 29.714
50 31.321

35
Basic Manual on “Mechanical Engineers and MATLAB”

4. Write a MATLAB program to generate set of elongation, strain and stress developed in
a circular bar of length 2 m and diameter 30 mm subjected a load of 4000 N to 40 kN in
a step of 4000 N. Assume Modulus of Elasticity as 210 GPa. Display the results under
the following title: Force in N, Elongation in mm, Strain, Stress in N/mm2.
Solution:
>> format short g
>> l=2000; % Length of the bar in mm
>> d=30; % Diameter of the bar in mm
>> E=2.1e5; % Modulus of Elasticity in N/mm^2
>> A=(pi/4)*d^2; % Area of Cross-section of the bar in mm^2
>> i=1;
>> for P=4000:4000:40e3; % Load applied from 3000 to 30,000 N increment of
3000N
delta=((P*l)/(A*E));
strain=delta/l;
stress=P/A;
Res(i,1)=P;
Res(i,2)=delta;
Res(i,3)=strain;
Res(i,4)=stress;
i=i+1;
end
>> disp('Load(N) Elongation(mm) Strain Stress(N/mm^2)
');Res

Load(N) Elongation(mm) Strain Stress(N/mm^2)


Res =
4000 0.053894 2.6947e-05 5.6588
8000 0.10779 5.3894e-05 11.318
12000 0.16168 8.0841e-05 16.977
16000 0.21557 0.00010779 22.635
20000 0.26947 0.00013473 28.294
24000 0.32336 0.00016168 33.953
28000 0.37726 0.00018863 39.612

36
Basic Manual on “Mechanical Engineers and MATLAB”

32000 0.43115 0.00021557 45.271


36000 0.48504 0.00024252 50.93
40000 0.53894 0.00026947 56.588

Note: Res stands for result in short form and it is a user defined term. Res(ii,1) = P;
% It create a Matrix in the name of Res and the value of P is stored in the iith row
and 1st column. Since, ii is 1 in the 1st iteration; the value of P will be stored in 1st
row – 1st column. In the 2nd iteration ii will be incremented to 2 and so on.

37
Basic Manual on “Mechanical Engineers and MATLAB”

5. A cantilever circular steel bar of diameter 60 mm and 0.6 m long is subjected to a


point load varying from 200 N to 4 kN in a step of 200 N at the free end. Assume
Modulus of Elasticity as 210 GPa. Determine the Bending moment, maximum
deflection and bending stress induced in the bar using MATLAB.

Fig. 3.1 Cantilever circular steel bar


Solution:
π𝑑 4
• Moment of Inertia of Area for Circular c/s = 64
π𝑑 3
• Modulus of this section = 32

format short g
l=0.6e3;
d=60;
E=210e3;
A=(pi*d^4)/64;
I = (pi*d^4)/64;
z = (pi*d^3)/32;
% Programming part starts from this section onwards
ii=1;
for P=200:200:4e3;
M=(P*l);
max_def=(P*(l^3))/(3*E*I);
stress=M/z;
% Storing the calculated values in array forms begins from this section
Res(ii,1)=P;
Res(ii,2)=M;

38
Basic Manual on “Mechanical Engineers and MATLAB”

Res(ii,3)=max_def;
Res(ii,4)=stress;
ii=ii+1;
end
disp('Load (N) Bending Moment (M) Max Deflection (mm)
Stress(N/mm^2)'); Res

Load (N) Bending Moment (M) Max Deflection (mm)


Stress(N/mm^2)
Res =
200 1.2e+05 0.10779 5.6588
400 2.4e+05 0.21557 11.318
600 3.6e+05 0.32336 16.977
800 4.8e+05 0.43115 22.635
1000 6e+05 0.53894 28.294
1200 7.2e+05 0.64672 33.953
1400 8.4e+05 0.75451 39.612
1600 9.6e+05 0.8623 45.271
1800 1.08e+06 0.97009 50.93
2000 1.2e+06 1.0779 56.588
2200 1.32e+06 1.1857 62.247
2400 1.44e+06 1.2934 67.906
2600 1.56e+06 1.4012 73.565
2800 1.68e+06 1.509 79.224
3000 1.8e+06 1.6168 84.883
3200 1.92e+06 1.7246 90.541
3400 2.04e+06 1.8324 96.2
3600 2.16e+06 1.9402 101.86
3800 2.28e+06 2.048 107.52
4000 2.4e+06 2.1557 113.18
4000 2.4e+06 2.1557 113.18

39
Basic Manual on “Mechanical Engineers and MATLAB”

6. Generate a table showing kinetic energy generated in a body of weight 120 N


moving with a velocity varying from 0 to 150 m/s, with an increment step of 15
m/s.
Solution:
>> format short g
>> m=120/9.81; % mass = weight / gravity

>> i=1;
>> for v=0:15:150; %increment for every 15 m/s
KE=0.5*m*(v^2); % K.E. of a body formula
table(i,1)=KE;
table(i,2)=v;
i=i+1;
end
>> table

table =
0 0
1376.1 15
5504.6 30
12385 45
22018 60
34404 75
49541 90
67431 105
88073 120
1.1147e+05 135
1.3761e+05 150

40
Basic Manual on “Mechanical Engineers and MATLAB”

7. The below figure shows the location of C.G. of 35,000 N weight pickup truck
under unloaded condition. At the cargo section additional weights are added with
load of WL at a distance of x cm behind the rear axle. Generate the MATLAB
program and plot WL as a function of x, where x value ranges from 0 to 50cm.
The front wheel midpoint lies 120cm from C.G. point and the rear wheels
midpoint lies 200cm from C.G point.

Fig. 3.2 Pickup truck under loaded

Solution:
Equilibrium equations:
∑Fy= 0 ➔ N + N – 35000 – WL = 0
2N = 35000 - WL
35,000+WL
𝑁= 2

Moment about the rear wheel axle:


∑MR = 0 ➔ 35000(200) – N(320) – WL(x) = 0

Now, substitute the value of N in the moment equation and solve:


35,000+WL
70,00,000 – ( )(320) - WL = 0
2

70,00,000 – (56,00,000 + 160WL) - WL = 0

41
Basic Manual on “Mechanical Engineers and MATLAB”

14,00,000 - 160 WL - xWL = 0


𝟏𝟒,𝟎𝟎,𝟎𝟎𝟎
W L= 𝟏𝟔𝟎+𝐱

>> x=0:0.1:50; %we have discretized 50cm to finer data points

>> wl=1400000./(160+x);
>> plot(x,wl);xlabel('x in cm'); ylabel('additional cargo
weight in N'); title('addition of cargo weight (N) v/s
dispalcement in cargo position (cm)'); grid on

Chart 3.3 Cargo weight v/s cargo position

Note: This graph represents, how the semitruck would react for the after-cargo input
without toppling of vehicle under maneuvering conditions.

42
Basic Manual on “Mechanical Engineers and MATLAB”

8. Generate a MATLAB program to compute the following using Px, Py and q.


Calculate:
i) Stresses on inclined plane
ii) Principal stresses and planes
iii) Maximum Shear stresses and planes.
iv) Also Plot Mohr circle and mark the vital points.

Case a: Px=100 MPa Py=-50 MPa q=40 MPa

Case b: Px=200 MPa Py=0 MPa q=60 MPa

Solution:

Px +Py Px−Py 𝑃𝑥−𝑃𝑦


Pn = + 𝑐𝑜𝑠2θ + qsin2θ 𝑃𝑖 = 𝑠𝑖𝑛2𝜃 − 𝑞𝑐𝑜𝑠2𝜃
2 2 2

𝑃𝑥+𝑃𝑦 𝑃𝑥−𝑃𝑦 2 𝑃𝑥+𝑃𝑦 𝑃𝑥−𝑃𝑦 2


𝑃1 = + √( ) + 𝑞2 𝑃1 = − √( ) + 𝑞2
2 2 2 2

For Case (a):


% Using linspace we say MATLAB to generate 1500 points in 1 complete circle using 2π i.e.,
1800+1800=3600, the finer the graphs will be obtained only if more points are generated.

>> theta = linspace(0,2*pi,2000);


>>p_x = input('Enter normal-stress along x-axis, p_x
(in MPa) = ');
Enter normal-stress along x-axis, p_x (in MPa) = 100
>> p_y = input('Enter normal-stress along y-axis, p_y
(in MPa) = ');
Enter normal-stress along y-axis, p_y (in MPa) = -50
>> q = input('Enter shear-stress along xy-plane, q (in
MPa) = ');
Enter shear-stress along xy-plane, q (in MPa) = 40
>> circle_center = ((0.5*(p_x-p_y))^2+q^2)^.5;
>> p_1 = (p_x+p_y)/2 + circle_center

43
Basic Manual on “Mechanical Engineers and MATLAB”

p_1 =
110
>> p_2 = (p_x+p_y)/2 - circle_center
p_2 =
-60

>> p_3 = circle_center


p_3 =
85

>> p_n = (p_x+p_y)/2 + 0.5*(p_x-p_y)*cos(2*theta) +


q*sin(2*theta);
>> p_t = 0.5*(p_x-p_y)*sin(2*theta) - q*cos(2*theta);
>> plot(p_n,p_t); axis equal; grid on
>> xlabel('Direct Normal Stress (MPa)');
ylabel('Direct Shear Stress (MPa)')
>> text(p_1,0,'Major Principal Stress')
>> text(p_2,0,'Minor Principal Stress')
>> text(p_3,0,'Circle centre for Mohr Circle')
>> title('Case (a) - Mohr Circle')

% The “text” function, induced the MATLAB to insert the text message inside the enclosed
brackets with single quotes.

44
Basic Manual on “Mechanical Engineers and MATLAB”

Chart 3.4 Mohr Circle case (a)


For Case (b):
>> theta = linspace(0,2*pi,2000);
>> p_x = input('Enter normal-stress along x-axis, p_x (in
MPa) = ');
Enter normal-stress along x-axis, p_x (in MPa) = 200
>> p_y = input('Enter normal-stress along y-axis, p_y (in
MPa) = ');
Enter normal-stress along y-axis, p_y (in MPa) = 0
>> q = input('Enter shear-stress along xy-plane, q (in
MPa) = ');
Enter shear-stress along xy-plane, q (in MPa) = 60
>> circle_center = ((0.5*(p_x-p_y))^2+q^2)^.5;
>> p_1 = (p_x+p_y)/2 + circle_center
p_1 =

45
Basic Manual on “Mechanical Engineers and MATLAB”

216.6190

>> p_2 = (p_x+p_y)/2 - circle_center


p_2 =
-16.6190

>> p_3 = circle_center


p_3 =
116.6190

>> p_n = (p_x+p_y)/2 + 0.5*(p_x-p_y)*cos(2*theta) +


q*sin(2*theta);
>> p_t = 0.5*(p_x-p_y)*sin(2*theta) - q*cos(2*theta);
>> plot(p_n,p_t); axis equal; grid on
>> xlabel('Direct Normal Stress (MPa)'); ylabel('Direct
Shear Stress (MPa)')
>> text(p_1,0,'Major Principal Stress')
>> text(p_2,0,'Minor Principal Stress')
>> text(p_3,0,'Circle centre for Mohr Circle')
>> title('Case (a) - Mohr Circle')

46
Basic Manual on “Mechanical Engineers and MATLAB”

Chart 3.5 Mohr Circle case(b)

47
Basic Manual on “Mechanical Engineers and MATLAB”

9. Generate a MATLAB program to obtain shear force and bending moment


figures for a beam loaded as shown below.

Fig. 3.3 Loaded Beam


Solution:

𝑅𝐴 + 𝑅𝐵 = 30 × 3 + 20
ΣMA = 0 = 30 × 3 × (3/2) − 6 × 𝑅𝐵 + 20 × 8 = 0

Portion AD:
𝑥^2
F = 60.8 – 30x M = 608 x – 30 2

Portion AD:
F = RA – 30*3 M = RA*x – 30*(x-1.5)

Portion BC:
F = RA – 30*3 + RB M = RA* x – 30*3*(x-1.5) + RB*(x-6)

>> R_B = (30*3*3/2+20*8)/6;

>> R_A = 30*3+20-R_B;

>> x_AD = linspace(0,3,30);

>> x_DB = linspace(3,6,30);

>> x_BC = linspace(6,8,20);

>> F_AD = R_A - 30*x_AD;

48
Basic Manual on “Mechanical Engineers and MATLAB”

>> M_AD = R_A*x_AD - 30*(x_AD.^2)/2;

>> F_DB = (R_A - 30*3)*ones(1,30);

>>M_DB = R_A*x_DB - 30*3*(x_DB-1.5);

>> F_BC = (R_A - 30*3 + R_A)*ones(1,20);

>>M_BC = R_A*x_BC - 30*3*(x_BC-1.5)+R_B*(x_BC-6);

>> x = [x_AD x_DB x_BC];

>>F = [F_AD F_DB F_BC];

>>M = [M_AD M_DB M_BC];

>> subplot(2,1,1)

>> plot(x,F)

>> ylabel('Shear Force (kN)')

>> title('SFD')

>> subplot(2,1,2)

>> plot(x,M)

>> title('BMD')

>> ylabel('Bending Moment (kN.m)')

49
Basic Manual on “Mechanical Engineers and MATLAB”

Chart 3.6 SFD & BMD


10. A manometer is utilized to measure the pressure of a gas in a tank. The specific
gravity of the fluid is found to be 13.5 g/cm3 and the column height is 50cm. If
the atmospheric pressure is 101 kPa, determine the absolute pressure within the
tank.

Fig.3.4 Manometer for a tank


Solution:

>> sp_g= input('Enter the specific gravity for the


fluid = ');
Enter the specific gravity for the fluid = 0.96
>> atm_pr = input ('Enter the local atmospheric
pressure in KPa = ');
Enter the local atmospheric pressure in KPa = 101
>> g=9.81
>> h = input('Input the manometer coulmn height in m =
');
Input the manometer coulmn height in m = 0.5
>> rho_water=9810; % density is taken as (1000*9.81) to get N/m3
>> rho=sp_g*rho_water;
>> p=atm_pr + (rho*g*h)/1000;
>> fprintf('Absolute Pressure is %4.1f KPa\n',p)
% not that after % in above line the “4” means, commanding MATLAB to leave 4 spaces and
‘.1’ after 4 means saying MATLAB to include just 1 value after whole values. And including ‘f’
means suggesting MATLAB to start accepting decimal values in results.

50
Basic Manual on “Mechanical Engineers and MATLAB”

Absolute Pressure is 147.2 KPa


11. Compute and plot linear and non-linear response for a simple pendulum having a
mass of 50 grams and a length of 150 cm. The initial conditions are taken as θ as
800 and 00.

Fig. 3.5 Simple Pendulum

Solution:

Simple D.E. of motion for simple pendulum without damping system is given by
−𝑔
θ’’= θ ( )sinθ
𝐿

For linear system if considered, we assume smaller incremental angles

sinθ = θ

For non-linear D.E. at above reduces to


−𝑔
θ’’=( 𝐿

MATLAB is versatile with Runge-Kutta method, thereby we reduce the above 2nd
O.D.E to 2 first order differential equation.

θ = y(1) and θ’=y(2)

Now, y(1)=y(2)

For nonlinear system, sin θ ≠ θ.

51
Basic Manual on “Mechanical Engineers and MATLAB”

−𝑔
Now 2 first order D.E.:: y(1)=y(2) and y(2)=( )sin(y(1))
𝐿

−𝑔 −9.81
= = 6.54 %150cm to 1.5m
𝐿 1.5

>>edit linear_1

function yp=linear_1(t,y) %from her enter the 3 lines in editor window


yp=[y(2);((-6.54) *(y(1)))] %ensure you save the file in the same as ‘linear_1’
end
>> tspan = [0 5];

>> y0=[1.39;0];

>> [t,y]=ode45('linear_1',tspan,y0);

>> plot(t,y(:,1))

>> grid on

>> xlabel('Time')

>> ylabel('Theta')

>> hold on; %this “hold on”, causes the MATLAB to plot the next
graphs details to the previous one. And must be released back to hold off

>>edit nonlinear

function yp=nonlinear(t,y)
yp=[y(2);((-6.54) *sin(y(1)))];
end

>> [t,y]=ode45('nonlinear',tspan,y0);

>> plot(t,y(:,1))

>> title('Linear and Non-Linear motion representing


for simple pendulum:: Theta v/s Time')

52
Basic Manual on “Mechanical Engineers and MATLAB”

Chart 3.7 Simple Pendulum motion

12. A can of Coke is taken out from the refrigerator at 5°C, and is placed on a table
in a room at 25°C. Sketch T(t).
Related questions:

(1) What do you base on to sketch the curve like that?


(2) Are you able to compute T(t) now? If not, why not?
Answer:
(1) T with increase with t exponentially. Initially, Coke is cold, so T_coke will
increase rapidly. As it is warmed up, the warming process will slow down.
(2) No, we are not able to compute T(t) now. Because we have not learned how to
related Q_in with T. (We did learn: ∆U = m 𝑐𝑣 ΔT from thermodynamics)

53
Basic Manual on “Mechanical Engineers and MATLAB”

A MATLAB code to plot T vs. t


>>clc; clear;
c1=0.7; t=linspace(0, 5, 51);
T=(-20)*exp(-c1*t)+25;
plot(t, T)
13. On a Sunday, you and your family go for an outing. In the morning, T_air =
25°C, and h = 20 W/m2 -K. At noontime, it becomes windy with h = 40 W/m2 -
K. At the same time, you nonetheless feel the same cooling effect. What is T_air
at noontime?
Answer:
q’’ = 20 *(37C – 25C) = 240 W/𝑚2 .
240 = 40* ( 37C – x ) ➔ x = 31°C.
MATLAB code:
>>clc; clear
h1=20; Tair1=25; h2=40;
qs=h1*(37-Tair1);
Tair2= 37-qs/h2

14. If the temperature of our body tissue is 37°C, T_room is 25°C, and the thickness
of the tissue is 0.002m, find T_skin. Relevant data:
L = 0.002m,
h = 20 W/𝑚2 -K,
k = 0.61 W/m-K

54
Basic Manual on “Mechanical Engineers and MATLAB”

Answer:
k_skin*(37 – T_skin)/L = h (T_skin – T_room)

or T_skin = (37 + Bi*T_room)/(1 + Bi),

Where Bi (Biot number) = h L / k_skin.

MATLAB code:
>>clc; clear
k=0.61; h=20; L=0.002;
Bi = h*L/k % = 0.0656
Troom = 25;
Tskin = (37 + Bi*Troom)/(1+Bi)

15. Consider a 2-D concrete column. Initially, the air and the column are at 20C.
Suddenly, T_west is raised to 1000C. Relevant data include:
k = 0.8; ρ = 2100; 𝑐𝑣 =1100;
Lx=Ly=0.3m; Δt = 100s; one node;
Find T1 at t = 100s. Use the implicit method.

55
Basic Manual on “Mechanical Engineers and MATLAB”

MATLAB code:
>>clc; clear
rho=2100; k=0.8; cv=1100; aLf=k/(rho*cv);
Lx=0.3; dx=Lx/2; dt=100; dxs=dx*dx;
r=aLf*dt/dxs; %dimensionless aspect ratio parameter
Tp=20;
T=(Tp+ r*(1000+3*20))/(1+4*r)
Transient Lumped-Capacitance Heat Conduction
Consider a small copper plate placed in the outer space.
m cv (T – Tp) = εσ𝑇𝑝 4 (1) ( explicit )
m cv (T – Tp) = εσ𝑇 4 (2) ( implicit )

Solving Eq. (1) is easier.


Solving Eq. (2) is more stable.
Tp: temperature at the previous time step
T : temperature at the current time step.

56
Basic Manual on “Mechanical Engineers and MATLAB”

16. Determine the internal energy for superheated water vapor at 90°C and 0.20 bar

MATLAB code:
u1=interp1([80 120],[2487.3 2544.7],90);
u2=interp1([80 120],[2483.7 2542.4],90);
u=interp1([.06 .35],[u1 u2],.2)

Tips 6:You can make the best use of ‘help’ tool to the fullest, by understudying the
basic till solved examples of all functions and arguments.

>>help ode45
% Get down to the bottom of the message, you find the references

Fig. 3.6 Reference instructions

% This is linked to the default documentations of MathWorks, where there are solved
examples from beginning to pro levels.

57
Basic Manual on “Mechanical Engineers and MATLAB”

FUN TASK

Create the iconic MATLAB Logo in MATLAB session:

% 1: first eigen value


%1000: number of points on 1/3 of boundary
L = 160*membrane(1,1000)

% Generating figures and axes initiation


f = figure;
ax = axes;

s = surface(L);
s.EdgeColor = 'none';
view(3) %Turning on 3D view insertion

% Setting up the limits around the logo


ax.XLim = [1 201];
ax.YLim = [1 201];
ax.ZLim = [-53.4 159];

%Setting up the camera view for logo view in iconic style, just like zooming in and out
ax.CameraPosition = [-145.5 -229.7 283.6];
ax.CameraTarget = [77.4 60.2 63.9];
ax.CameraUpVector = [0 0 1];
ax.CameraViewAngle = 36.7;

%Setting up axis positions to fill unfilled spaces


ax.Position = [0 0 1 1];
ax.DataAspectRatio = [1 1 .9];

%Turning on photoshoot settings and adjusting the controls


l1 = light;

58
Basic Manual on “Mechanical Engineers and MATLAB”

l1.Position = [160 400 80];


l1.Style = 'local';
l1.Color = [0 0.8 0.8];

l2 = light;
l2.Position = [.5 -1 .4];
l2.Color = [0.8 0.8 0];

%Changing the colours by makeup and filters.


s.FaceColor = [0.9 0.2 0.2];

%Touch up session
s.FaceLighting = 'gouraud';
s.AmbientStrength = 0.3;
s.DiffuseStrength = 0.6;
s.BackFaceLighting = 'lit';
s.SpecularStrength = 1;
s.SpecularColorReflectance = 1;
s.SpecularExponent = 7;

%Turing off the axis display, to show only the logo, with transparency background .
axis off
f.Color = 'black';

59
Basic Manual on “Mechanical Engineers and MATLAB”

Fig. 3.6 MATLAB Logo

ACKNOWDEGEMENT:

We owe a deep sense of gratitude to Chancellor and Vice-Chancellor of REVA University,


Bengaluru. We also acknowledge the support by Director and Assistance Director, School of
Mechanical Engineering, REVA University.

60

You might also like