LAB MAnual CPA
LAB MAnual CPA
(ME–214)
Name : ____________________________________
Year : ____________________________________
Batch : ____________________________________
Roll No : ____________________________________
Department : ____________________________________
Chairman
Checked/Verified By:
Name: _______________________
Signature: ____________________
Date: ________________________
TABLE OF CONTENT
Date of
Experiment Objective Pg. No Remarks
Performance
To determine the final temperature of a soda can
1 by using MATLAB arithmetic operations to apply 01
Newton’s law of cooling.
Write a script file to determine the magnitude of
2 12
the resultant force acting on the eyebolt.
Write a script file to determine the magnitude of
3 19
the resultant force acting on the eyebolt.
To determine the unknown forces on truss
4 28
members using array division in MATLAB.
Write down a script file to determine the pressure
5 at different altitudes using array input/output 43
commands.
To determine displacement for the vibrations of
the body of a helicopter due to the periodic force
applied by the rotation of the rotor can be modeled
6 55
by a frictionless spring-mass-damper system
subjected to an external periodic force. Also plot
the curve between displacement and time.
To determine the volume of the water in the tank
with complex geometry from the position (height
7 h) of the float. The program asks the user to enter 69
a value of h in m, and as output displays the
volume of the water in m3.
Write a MATLAB program that determines and
8 plots the speed and altitude of the rocket as a 82
function of time during the flight.
Create a function file that calculates the trajectory
of a projectile. The inputs to the Y function are the
initial velocity and the angle at which the
9 90
projectile is fired. The outputs from the function
are the maximum height and distance. In addition,
the function generates a plot of the trajectory.
To determine the function of velocity, v(t), and
acceleration, a(t), using a function for
10 101
displacement s(t). Plot the curves for
displacement, velocity and acceleration with time.
To determine a function 𝒘 = 𝒇(𝒕) (t is the
11 independent variable, w is the dependent variable) 110
for the given data set using curve fitting.
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 1
Objective
To determine the final temperature of a soda can by using MATLAB arithmetic operations to
apply Newton’s law of cooling.
1.1. Starting MATLAB
It is assumed that the software MATLAB R2018B is installed on the computer, and that the user
can start the program. Once the program starts, the MATLAB desktop window opens with the
default layout as shown in Figure 1.
Page 1 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Window Purpose
Command Window Main window, enters variables, runs programs.
Opens automatically when graphics commands are
Figure Window
executed.
Creates and debugs script and function files. This window
is opened by clicking on the New Script icon in the Tool
Editor Window
strip, or by clicking on the New icon and then selecting
Script from the menu that opens.
Provides help information. This window can be opened
Help Window from the Help icon in the Tool strip of the Command
Window
Command History
Logs commands entered in the Command Window.
Window
Workspace Window Provides information about the variables that are stored.
Current Folder Window Shows the files in the current folder.
The windows shown in Error! Reference source not found. can be displayed by clicking on the l
ayout icon and selecting Default in the menu that opens. The various windows in Error!
Reference source not found. are docked to the desktop. A window can be undocked by
dragging it out. An independent window can be redocked by clicking on the pull-down menu at
the top right-hand side of the window and then selecting Dock.
1.3. Command Window
The Command Window is MATLAB’s main window and can be used for executing commands,
opening other windows, running programs written by the user, and managing the software. An
example of the Command Window is shown in Error! Reference source not found..
Page 2 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Table 2: Important keys and characters when working in the command window
Keys/Characters Description
Enter Executes the last command in the command window
, Comma; separates commands in the same line.
up-arrow key to recall the previously typed command
The down-arrow key to move down the list of previously typed
commands.
; Semicolon: suppresses display, the output of the command is not
displayed
... Ellipsis: If a command is too long to fit in one line, it can be
continued to the next line by typing three periods … (called an
ellipsis) and pressing the Enter key
% Percent: typed at the beginning of a line to denote a comment
Error! Reference source not found. shows some important commands that when typed in the c
ommand window followed by the enter key execute a specific function.
Table 3: Managing commands in the Command Window
Command Description
cd Changes current directory.
Clears the Command Window (not the variables defined
clc
from the memory).
clear Removes all variables from the memory.
clear x y z Removes variables x, y, and z from the memory.
close Closes the active Figure Window.
help Displays help for MATLAB functions.
lookfor Search for specified word in all help entries.
who Displays variables currently in the memory.
Page 3 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 4 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 5 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
>> 290/7
Scientific notation with 4
format short e ans =
decimal digits.
4.1429e+001
>> 290/7
Scientific notation with 15
format long e ans =
decimal digits.
4.142857142857143e+01
>> 290/7
Best of 5-digit fixed or
format short g ans =
floating point.
41.429
>> 290/7
Best of 15-digit fixed or
format long g ans =
floating point.
41.4285714285714
>> 290/7
format bank Two decimal digits ans =
41.43
Page 6 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Variable Description
inf Infinity.
pi The number π.
Page 7 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 8 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
>> floor(-9/4)
floor(x) Round toward minus infinity. ans =
-3
>> rem(13,5)
Returns the remainder after x
rem(x,y) ans =
is divided by y.
3
Signum function. Returns 1 if x >> sign(5)
sign(x) > 0 , –1 if x < 0 , and 0 if x = ans =
0. 1
2. A soda can at a temperature of 120°F (after being left in the car) is placed inside a
refrigerator where the temperature is maintained at 38°F. By defining the input variables
in the command window, Determine, to the nearest degree, the temperature of the can
after three hours, if the temperature is changed according to the equation:
𝑇 = 𝑇𝑠 + (𝑇0 − 𝑇𝑠 )𝑒 −k𝑡
Where 𝑇 is the temperature of the soda at time t, k is a constant equal to 0.45, 𝑇0 is initial
temperature of the soda at time t=0, t is the time in hours and 𝑇𝑠 is the constant
temperature of the refrigerator.
Page 9 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
(a) 4𝑢
3𝑣
(b) 2𝑣 −2
(𝑢 + 𝑣)2
(c) 𝑣3
𝑣 3 − 𝑢3
(d) 4 2
𝜋𝑣
3
2) A total of 4217 eggs have to be packed in boxes that can hold 36 eggs each. By typing one
line (command) in the Command Window, calculate how many eggs will remain unpacked if
every box that is used has to be full. (Hint: Use MATLAB built-in function fix.)
Page 10 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 11 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 2
Objective
Write a script file to determine the magnitude of the resultant force acting on the eyebolt.
2.1. Drawbacks of working in a command window
1) The commands/program in the Command window cannot be saved
and hence cannot be retrieved later.
2) It is not interactive.
3) Already executed command cannot be modified.
Page 12 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
The Editor/Debugger Window has a Toolstrip at the top and three tabs EDITOR, PUBLISH, and
VIEW above it as shown in Error! Reference source not found.. Clicking on the tabs changes t
he icons in the Toolstrip. Commonly, when working in a script file, Editor Tab is selected.
Once the window is open, the commands of the script file are typed line by line. MATLAB
automatically numbers a new line every time the Enter key is pressed. The commands can also
be typed in any text editor or word processor program and then copied and pasted in the Editor.
Figure 7: Prompting message for the programmer to help MATLAB run the script file
2.4. Solved Problems
1) Write a script file to determine the magnitude of the resultant force acting on the eyebolt and
its direction measured clockwise from the positive x axis. Take 𝜃=30° and 𝑇 = 6 kN.
Figure 8: Eyebolt
Page 14 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Free-Body Diagram
Page 15 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
h=120; %m
g=9.807; %m/s^2
%power= Potential energy/time=mgh/t
P=m_dot*g*h/1000 %kW
Command window
P=
1765.26
2.5. Review Problems
1) Radioactive decay of carbon-14 is used for estimating the age of organic material. The
decay is modeled with the exponential function 𝒇(𝒕) = 𝒇(𝟎)𝒆𝒌𝒕 , where t is time, f(0) is
the amount of material at t = 0, f(t) is the amount of material at time t, and k is a constant.
Carbon-14 has a half-life of approximately 5,730 years. A sample taken from the ancient
footprints of Acahualinca in Nicaragua shows that 77.45% of the initial (t = 0) carbon-14
is present. Determine the estimated age of the footprint. Solve the problem by writing a
program in a script file. The program first determines the constant k, then calculates t for
𝑓(𝑡) = 0.7745𝑓(0), and fmally rounds the answer to the nearest year.
2) According to the Doppler effect of light, the perceived wavelength (𝜆𝑝) of a light source
with a wavelength (𝜆𝑠) of is given by:
𝒗
𝟏−𝒄
𝝀𝒑 = 𝝀𝒑 √ 𝒗
𝟏+
𝒄
where c is the speed of light (about 300 × 106 m/s) and v is the speed, the observer
moves toward the light source. Calculate the speed the observer has to move in order to
see a red light as green. Green wavelength is 530 nm and red wavelength is 630 nm.
3) The steady state heat conduction (q) from a cylinder
solid wall is determined by:
(𝑻𝒊 − 𝑻𝒐 )
q = 𝟐𝝅𝑳𝒌 𝒓
𝐥𝐧 ( 𝒐⁄𝒓𝒊 )
where, k is the thermal conductivity. Calculate q for a
copper tube (𝑘 = 401 𝑊𝑎𝑡𝑡𝑠/℃/𝑚) of length 𝐿 =
300 𝑐𝑚 with and outer radius of 𝑟2 = 5 𝑐𝑚 and inner
radius of 𝑟1 = 3 𝑐𝑚. The external temperature is 𝑇2 =
20℃ and the internal temperature is 𝑇1 = 100℃.
Page 16 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 17 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 18 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 3
Objective
To determine the accelerating force in a moving body at different accelerations by using arrays.
3.1. Creating Arrays in MATLAB
The array is a fundamental form that MATLAB uses to store and manipulate data. An array is a
list of numbers arranged in rows and/or columns. Some common types of arrays are:
1) Vectors: A one-dimensional array that is either a row or a column of numbers.
2) Matrices: A two-dimensional array that is a collection of numbers arranged in rows and
columns.
3) Strings: A collection of characters.
Page 19 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
or the function linspace can be used. For example, vector 𝐴 = [2 5 8 11 14] that begins
with element 2, ends at element 14, has a constant spacing of 3 between two consecutive
elements in the series and has total number of 5 elements. A snippet of the command window in
Figure 9 shows how the two can be used.
Colon operator: First element: Constant spacing: Last Element. Square brackets are optional
when creating vectors. MATLAB calculates the number of terms itself.
linspace function: it is a function used to create a series of elements that increase linearly hence
the function name. It requires three input arguments; first element, last element and the number
of elements all within the parenthesis, separated by comma.
2) If the number of elements in arithmetic series are 100, one may skip mentioning the
number of elements in the linspace function. So for example to obtain elements from 1 to
100 with spacing of 1, the syntax would be linspace(1,100).
3.1.3. Creating matrices
A matrix is created by assigning the elements of the matrix to a variable. This is done by typing
the elements, row by row, inside square brackets [ ]. First type the left bracket [then type the first
Page 20 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
row, separating the elements with spaces or commas. To type the next row, type a semicolon or
press Enter. Type the right bracket] at the end of the last row.
The elements that are entered can be numbers or mathematical expressions that may include
numbers, predefined variables, and functions. All the rows must have the same number of
elements. If an element is zero, it must be entered as such. MATLAB displays an error message
if an attempt is made to define an incomplete matrix.
An example of a matrix created in MATLAB is shown in Figure 10 that created its first row
using the colon operator because the first row observed arithmetic progression, second row
created using linspace function and last row by typing each element explicitly since the elements
in the third row did not observe any arithmetic progression. Note, each row has same number of
elements.
Page 21 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 22 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 23 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 24 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Figure 17: Use of a null vector to delete an entire column from a matrix.
3.6. Strings
A collection of characters is called strings. Unlike the array of numbers whose data type is saved
as double in MATLAB, the data type of strings is ‘char’. To define strings in MATLAB, the
characters are enclosed within single quotation marks. The font color once the single quotation
mark is opened turns to maroon, this color signifies that the characters forming a string are yet to
Page 25 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
be completed. Once the collection of characters is typed, they are enclosed within the single
quotation marks, this changes the font color to magenta. This highlights that the string is
completely written.
The number of elements in a string is a number of characters in it, including spaces and all
special characters. Strings are typically used when text messages need to be displayed.
3.7. Solved Problem
1) To determine the accelerating force in a moving body of mass 80 kg at different
accelerations of 2, 3, 4, 5 and 6 m/s2 by using arrays.
Page 26 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 27 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 4
Objective
To determine the unknown forces on truss members using array division in MATLAB.
4.1. Addition and subtraction with arrays
The operations + (addition) and – (subtraction) can be used to add (subtract) arrays of identical
size (the same numbers of rows and columns) and to add (subtract) a scalar to an array. When
two arrays are involved the sum, or the difference, of the arrays is obtained by adding, or
subtracting, their corresponding elements. By default, addition and subtraction of arrays are
element wise operations as shown by Figure 18. Similarly, adding and subtracting the vectors to
and from scalars is also an element wise operation as shown in Figure 19.
Page 28 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Figure 20 shows a scalar value being added to a vector in two ways, with and without
parenthesis. It shows that the colon operator observes lower order of precedence than the
addition operator.
Page 29 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 30 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Although the last two operations appear to give the same result, the method by which MATLAB
calculates X is different. In the first, MATLAB calculates 𝑨−𝟏 and then uses it to multiply B. In
the second (left division), the solution X is obtained numerically using a method that is based on
Gauss elimination. The left division method is recommended for solving a set of linear
equations, because the calculation of the inverse may be less accurate than the Gauss elimination
method when large matrices are involved.
4.3.2. Right Division (/)
The right division is used to solve the matrix equation XC=D. In this equation X and D are row
vectors. This equation can be solved by multiplying, on the right, both sides by the inverse of C:
𝑿𝑪𝑪−𝟏 = 𝑫𝑪−𝟏
Which gives,
𝑿 = 𝑫𝑪−𝟏
In MATLAB the last equation can be written using the right division character.
𝑿 = 𝑫/𝑪
4.4. Solving a system of linear equations using matrix division
A system of linear equations is solved using left and right division both and are demonstrated in
Figure 24 and Figure 25 respectively.
4𝑥 − 2𝑦 + 6𝑧 = 8 eq. (1)
2𝑥 + 8𝑦 + 2𝑧 = 4 eq. (2)
6𝑥 + 10𝑦 + 3𝑧 = 0 eq. (3)
This is extremely useful when calculating the value of a function at many values of its argument.
The feature of MATLAB in which arrays can be used as arguments in functions is called
vectorization.
For instance,
Page 32 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
𝒛𝟑 + 𝟓𝒛
Evaluate → 𝒚 = 𝟐
𝟒𝒛 − 𝟏𝟎
For these values of 𝑧 → 𝑧 = [1 3 5 7 9 11]
Figure 26 shows that in order to evaluate the function y’s values at each value of z, z is first
defined as vector and then the function’s equation is typed where it computes z element wise so
as to obtain the function’s value for each value of z.
Page 33 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 34 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
cross(a,b) Calculates the cross product of two vectors >> a=[1 3 2];
a and b, (a x b). The two vectors must have >> b=[2 4 1];
each three elements. >> cross(a,b)
ans =
-5 3 -2
inv(A) Returns the inverse of a square matrix A. >> A=[2 -2 1; 3 2 -1; 2 -3 2];
>> inv(A)
ans =
0.2000 0.2000 -0.0000
-1.6000 0.4000 1.0000
-2.6000 0.4000 2.0000
4.7. Solved Problems
1) A truss is a structure made of members joined at their ends. For the truss shown in the
figure, the forces in the seven members are determined by solving the following system
of seven equations.
𝑭𝟏 𝐜𝐨𝐬(𝟐𝟖. 𝟓) + 𝑭𝟐 − 𝟑𝟎𝟎𝟎 = 𝟎
𝑭𝟏 𝐬𝐢𝐧(𝟐𝟖. 𝟓) + 𝟔𝟓𝟐𝟏 = 𝟎
−𝑭𝟏 𝐜𝐨𝐬(𝟐𝟖. 𝟓) − 𝑭𝟑 𝐬𝐢𝐧(𝟓𝟖. 𝟒) + 𝑭𝟓 𝐜𝐨𝐬(𝟓𝟖. 𝟒) + 𝑭𝟔 𝐜𝐨𝐬(𝟐𝟖. 𝟓) + 𝟑𝟎𝟎𝟎 = 𝟎
−𝑭𝟏 𝐬𝐢𝐧(𝟐𝟖. 𝟓) − 𝑭𝟑 𝐬𝐢𝐧(𝟓𝟖. 𝟒) − 𝑭𝟓 𝐬𝐢𝐧(𝟓𝟖. 𝟒) − 𝑭𝟔 𝐬𝐢𝐧(𝟐𝟖. 𝟓) = 𝟎
−𝑭𝟒 − 𝑭𝟓 𝐜𝐨𝐬(𝟓𝟖. 𝟒) + 𝑭𝟕 = 𝟎
𝑭𝟔 𝐬𝐢𝐧(𝟐𝟖. 𝟓) + 𝟕𝟒𝟕𝟗 = 𝟎
−𝑭𝟕 − 𝑭𝟔 𝐜𝐨𝐬(𝟐𝟖. 𝟓) = 𝟎
Write the equations in matrix form and use MATLAB to determine the forces in the
members. A positive force means tensile force and a negative force means compressive
force. Display the results in a table where the first column displays the member number,
and the second column displays the corresponding force.
Page 35 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
2) The lamp has a mass of 15 kg and is supported by a pole AO and cables AB and AC. If the
force in the pole acts along its axis, write a script file to determine the forces in AO, AB,
and AC for equilibrium.
Page 36 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
magnitude of the position vectors: OA=[2 -1.5 6]; OB=[-4 1.5 0]; OC=[0 1.5 0];
̂ | = √22 + (−1.5)2 + 62 = 6.5 m
|𝑂𝐴 % cables
AB=OB-OA;
̂ | = √−62 + (3)2 + −62 = 9 m
|𝐴𝐵 AC=OC-OA;
% magnitude of the position vectors
̂ | = √−22 + (3)2 + −62 = 7 m
|𝐴𝐶 m_OA=sqrt(sum(OA.^2));
m_AB=sqrt(sum(AB.^2));
unit vectors: m_AC=sqrt(sum(AC.^2));
2 −1.5 6 %unit vectors
𝑢̂
𝑂𝐴 = [ ]
6.5 6.5 6.5 uOA=OA./m_OA; uAB=AB./m_AB;
uAC=AC./m_AC;
−6 3 −6 %weight
𝑢̂
𝐴𝐵 = [ ]
9 9 9
W=15*9.81;
−2 3 −6 %AX=B
𝑢̂
𝐴𝐶 = [ ]
7 7 7 B=[0;0;W];
A=[uOA(1) uAB(1) uAC(1)
2 −1.5 6
𝐹𝑂𝐴 = |𝐹𝑂𝐴 | [ ] uOA(2) uAB(2) uAC(2)
6.5 6.5 6.5
uOA(3) uAB(3) uAC(3)];
6 3 −6 X=A\B;
𝐹𝐴𝐵 = |𝐹𝐴𝐵 | [− ]
9 9 9 FOA=X(1), FAB=X(2), FAC=X(3)
−2 3 −6
𝐹𝐴𝐶 = |𝐹𝐴𝐶 | [ ]
7 7 7 Command Window
∑ 𝐹𝑥 = 0 FOA =
318.8250
2 6 2 FAB =
𝐹𝑂𝐴 − 𝐹𝐴𝐵 − 𝐹𝐴𝐶 = 0
6.5 9 7 110.3625
FAC =
∑ 𝐹𝑦 = 0 85.8375
−1.5 3 3
𝐹𝑂𝐴 + 𝐹𝐴𝐵 + 𝐹𝐴𝐶 = 0
6.5 9 7
∑ 𝐹𝑧 = 0
Page 37 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
6 6 6
𝐹𝑂𝐴 − 𝐹𝐴𝐵 − 𝐹𝐴𝐶 = 𝑊 = 15 ∗ 9.81
6.5 9 7
FOA = 318.8250
FAB = 110.3625
FAC = 85.8375
3) If θ=30° and T=6 kN, determine the magnitude of the resultant force acting on the
eyebolt and its direction measured clockwise from the positive x-axis.
Page 38 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
2) If the resultant force acting on the bracket is 𝑭𝑹 = {𝟑𝟎𝟎𝐢 + 𝟔𝟓𝟎𝐣 + 𝟐𝟓𝟎𝐤} N, write a
script file to determine the magnitude and coordinate direction angles of F. Begin by
expressing each force in the vector form in MATLAB.
Page 39 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
3) The cable AO exerts a force on the top of the pole of F={-120i-90j-80k} lb. Write a
MATLAB program to determine the height z of the pole and the location (x, y) of its
base, if the length of the cable is 34 ft.
Page 40 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
6) The electrical circuit shown consists of resistors and voltage sources. Write a MATLAB
program to determine the current in each resistor, using the mesh current method based
on Kirchoff’s voltage law. Express the equations in matrix form following the general
equation AX=B. Assume missing values here.
Page 41 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 42 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 5
Objective
Write down a script file to determine the pressure at different altitudes using array input/output
commands.
5.1. Methods to assign a value to variable
The assignment of a value to a variable can be done in 3 ways:
1) Defined and assigned a value in the script file
2) Defined and assigned a value in the command window
3) Defined in the script file but assigned a value in the command window using an input
command
In all these 3 ways, MATLAB stores the data in a common space that is shared by both the script
file and the command window. This space is called a workspace window.
5.2. The workspace window
The MATLAB workspace consists of the set of variables (named arrays) that are defined and
stored during a MATLAB session. It includes variables arranged in alphabetical order, as shown
in Figure 28 that have been defined in the Command Window and variables defined when script
files are executed. This means that the Command Window and script files share the same
memory zone within the computer. This implies that once a variable is in the workspace, it is
recognized and can be used, and it can be reassigned new values, in both the Command Window
and script files.
Page 43 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Figure 29 depicts the use of input command. To find average of any 2 numbers X1 and X2, the
programmer only defined the variables X1 and X2 in the script file, leaving the value for the user
to enter. When the input command is executed as the script file runs, the string is dis-played in
the Command Window. The string is a message prompting the user to enter a value that is
assigned to the variable. The user types the value and presses the Enter key. This assigns the
value to the variable. As with any variable, the variable and its assigned value will be displayed
in the Command Window unless a semicolon is typed at the very end of the input command.
Figure 29: Using input command to ask the user to enter a value.
In this example scalars are assigned to the variables. In general, however, vectors and arrays can
also be assigned. This is done by typing the array in the same way that it is usually assigned to a
variable (left bracket, then typing row by row, and a right bracket) as shown in Figure 30.
Page 44 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Where the‘s’ inside the command defines the characters that will be entered as a string. In this
case when the prompt message appears, the text is typed in without the single quotes, but it is
assigned to the variable as a string as shown in Figure 31.
Page 45 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Every time the disp command is executed, the display it generates, appears in a new line (without
its associated variable name). One example is shown in Figure 33.
Page 46 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Command disp can be used to display an empty line in the command window, which is done by
typing space within single quotation mark within the parentheses of the function disp as shown
in Figure 34. The disp can be used to display a text message along with the value of the variable
using the num2str function as shown in Figure 34. The function num2str converts the numeric
value of the variable to the string just for the sake of displaying it with the text message which is
a string. Otherwise, a string cannot be combined with the numeric number of data type double
using only the disp function.
Figure 34: Use of disp command to display an empty line and a text message with the value
of the variable.
The disp command is also very useful when tabulating results in the table form. Using disp can
add appropriate headers to each column of the table as shown in Figure 35. However, to ensure
the header fits right at top of its respective column, this is done adding spaces by trial and error.
Figure 35: Use of disp command to tabulate the results with headers
Page 47 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Figure 36: Additional line feed \n added to shift the command prompt to the next line
5.3.3.2. Intermixing text with numeric value of the variable
To display a mix of text and a number (value of a variable), the fprintf command has the form:
Page 48 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
The field width and precision (5.2 in the previous example) are optional. The first number (5 in
the example) is the field width, which specifies the mini- mum number of digits in the display. If
the number to be displayed is shorter than the field width, spaces or zeros are added in front of
the number. The precision is the second number (2 in the example). It specifies the number of
digits to be displayed to the right of the decimal point.
The last element in the formatting elements, which is required, is the conversion character, which
specifies the notation in which the number is displayed. Some of the common notations are:
e Exponential notation using lowercase e (e.g., 1.709098e+001).
E Exponential notation using uppercase E (e.g., 1.709098E+001).
F Fixed-point notation (e.g., 17.090980).
g The shorter of e or f notations.
G The shorter of E or f notations.
I or d Integer.
s String
5.5. Solved problems
1) The altitude, h, as a function of air pressure can be calculated by:
𝒑 𝟎.𝟏𝟗𝟎𝟐𝟖𝟗
𝒉 = 𝟏𝟒𝟓𝟑𝟔𝟔. 𝟒𝟓 [𝟏 − ( ) ]
𝟏𝟎𝟏𝟑. 𝟐𝟓
where h is in units of feet and the pressure p in units of millibars (mb). Write a MATLAB
program in a script file that calculates the h for a given p. For input the program asks the
user to enter the pressure in units of millibars. The program then calculates the altitude
rounded to the nearest integer. For output the program displays the message: “The
altitude is: XX ft.” where XX is the calculated value of h. Determine the altitude if the
pressure is 394 mb.
Page 49 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Script File
Command Window
Page 50 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Command Window
3) Write a MATLAB program in a script file that calculate the average, standard deviation,
and median of a list of grades as well as the number of grades on the list. The program
asks the user (input command) to enter the grades as elements of a vector. The program
then calculates the required quantities. The results are displayed in the Command
Window in the following format:
“There are XX grades.” where XX is the numerical value.
“The average grade is XX.” where XX is the numerical value.
“The standard deviation is XX.XX.” where XX is the numerical value.
“The median deviation is XX.XX” where XX.XX is the numerical value.
Execute the program and enter the following grades: 81, 65, 61, 78, 94, 80, 65, 76, 77,
95, 82, 49, and 75.
Script File
Page 51 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Command Window
Page 52 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
figure). As shown in the figure, there is a 2-in gap between the sides of the triagles.
Write a MATLAB program that determines the dimensions a and h such that overall area
of the sign will be as small as possible.
Begin by defining vector a with values ranging from 10 to 120 with increments of 0.1.
Use this vector for calculating the corresponding values of h and the overall area of the
sign. Then using MATLAB’s built-in function, find the dimensions of the smallest sign.
Page 53 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 54 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 6
Objective
To determine displacement for the vibrations of the body of a helicopter due to the periodic force
applied by the rotation of the rotor can be modeled by a frictionless spring-mass-damper system
subjected to an external periodic force. Also plot the curve between displacement and time.
6.1. Introduction
MATLAB can be used to create and format many types of two-dimensional plots. A typical
example of a graph created using MATLAB is shown in Figure 37. The figure contains two
curves that show the variation of light intensity with distance. One curve is constructed from data
points measured in an experiment, and the other curve shows the variation of light as predicted
by a theoretical model. The axes in the figure are both linear, and different types of lines (one
solid and one dashed) are used for the curves. The theoretical curve is shown with a solid line,
while the experimental points are connected with a dashed line. Each data point is marked with a
circular marker. The dashed line that connects the experimental points is actually red when the
plot is displayed in the Figure Window. Additionally, the plot is formatted to have a title, axis
titles, a legend, markers, and a boxed text label.
Page 55 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
The arguments x and y are each a vector (one-dimensional array). The two vectors must have the
same number of elements. When the plot command is executed, a figure is created in the Figure
Window. If not already open, the Figure Window opens automatically when the command is
executed. The figure has a single curve with the x values on the abscissa (horizontal axis) and the
y values on the ordinate (vertical axis). The curve is constructed of straight-line segments that
connect the points whose coordinates are defined by the elements of the vectors x and y. Each of
the vectors, of course, can have any name. The vector that is typed first in the plot command is
used for the horizontal axis, and the vector that is typed second is used for the vertical axis.
When the plot function is used such that only the vectors are defined as its input arguments, the
plot obtained has the following features as shown in Figure 38:
1) Blue colored line
2) Line without marker
3) Solid line
4) No added labels, titles, or legends
It should also be noted that before the plot command can be executed, the vectors x and y must
have assigned elements.
Figure 38: Plot function with minimum 2 input arguments defined only
Page 56 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
The plot command has additional, optional arguments that can be used to specify: the color and
style of the line the color and type of markers.
Page 57 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
• Marker type
plot(x,y,‘*’) The points are marked with * (no line between the points).
plot(x,y,‘g:d’) A green dotted line connects the points with diamond markers
6.2.2. Properties and their respective values
Properties are optional and can be used to specify the thickness of the line, the size of the marker
and the colors of the marker’s edge line and fill. The Property Name is typed as a string,
followed by a comma and a value for the property, all inside the plot command. Four properties
and their possible values are shown in Table 9:
Page 58 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
MarkerFaceColor (or Specifies the color of the Color specifiers from table
markerfacecolor) filling for filled markers above, typed as string
For example: to plot the function y with the interval of x from -3 to 3, fplot function would be
written in the form:
Page 59 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 60 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Additional graphs can be added with plot commands that are typed next. Each plot command
creates a graph that is added to that figure. The hold off command stops this process. It returns
MATLAB to the default mode, in which the plot command erases the previous plot and resets
the axis properties.
6.4.3. Using line command
With the line command additional graphs (lines) can be added to a plot that already exists. The
form of the line command is:
(Optional) Properties with values that can be used to specify the line style, color, and width,
marker type, size, and edge and fill colors. The format of the line command is almost the same as
the plot command (see Section 6.2). The line command does not have the line specifiers, but the
line style, color, and marker can be specified with the Property Name and property value
features. The properties are optional, and if none are entered MATLAB uses default properties
and values. For example, the command:
line(x,y,‘linestyle’,‘--’,‘color’,‘r’,‘marker’,‘o’) will add a dashed red line with circular markers
to a plot that already exists.
6.5. Formatting the plots
The formatting commands are entered after the plot or the fplot command. The various
formatting commands are:
6.5.1. The xlabel and ylabel commands:
Labels can be placed next to the axes with the xlabel and ylabel command which have the form:
Page 61 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
The text command places the text in the figure such that the first character is positioned at the
point with the coordinates x, y (according to the axes of the figure).
The gtext command places the text at a position specified by the user. When the command is
executed, the Figure Window opens and the user specifies the position with the mouse.
6.5.4. The legend command:
The legend command places a legend on the plot. The legend shows a sample of the line type of
each graph that is plotted, and places a label, specified by the user, beside the line sample. The
form of the command is:
The strings are the labels that are placed next to the line sample. Their order corresponds to the
order in which the graphs were created. The ‘Location’,‘pos’ are optional strings that specifies
where in the figure the legend is to be placed. Several options are:
B Places the legend inside the plot in a location that interferes the least with the graphs.
6.5.5. Formatting the text within the xlabel, ylabel, title, text and legend
commands:
The text in the string that is included in the command and is displayed when the command is
executed can be formatted. The formatting can be used to define the font, size, position
(superscript, subscript), style (italic, bold, etc.), and color of the characters, the color of the
background, and many other details of the display. Some of the more common formatting
possibilities are described below.
Page 62 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
The modifiers are characters that are inserted within the string. Some of the modifiers that can be
added are:
These modifiers affect the text from the point at which they are inserted until the end of the
string. It is also possible to have the modifiers applied to only a section of the string by typing
the modifier and the text to be affected inside braces { }.
6.5.6. Subscript and superscript:
A single character can be displayed as a subscript or a superscript by typing _ (the underscore
character) or ^ in front of the character, respectively. Several consecutive characters can be
displayed as a subscript or a superscript by typing the characters inside braces { } following the _
or the ^.
6.5.7. Greek characters:
Greek characters can be included in the text by typing \name of the letter within the string. To
display a lowercase Greek letter, the name of the letter should be typed in all lowercase English
characters. To display a capital Greek letter, the name of the letter should start with a capital
letter. Some examples are listed.
Page 63 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 64 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
2) The ideal gas law relates the pressure (P), volume (V), and temperature (T) of an ideal
gas:
𝑷𝑽 = 𝒏𝑹𝑻
where n is the number of moles and R = 8.3145 J/ (K. mol). Plots of pressure versus
volume at constant temperature are called isotherms. Plot the isotherms for one mole of
an ideal gas for volume ranging from 1 to 10 m3, at temperatures of T = 100, 200, 300,
and 400 K (four curves in one plot). Label the axes and display a legend. The units for
pressure are Pa.
Page 65 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
3) Plot the function y and its first and second derivatives, for −2 ≤ 𝑥 ≤ 4 all on the same
plot.
𝒚 = 𝟑𝒙𝟑 − 𝟐𝟔𝒙 + 𝟏𝟎
Page 66 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
2) The demand for water during a fire is often the most important factor in the design of
distribution storage tanks and pumps. For communities with populations less than
200,000, the demand Q (in gallons/min) can be calculated by:
𝑸 = 𝟏𝟎𝟐𝟎√𝑷(𝟏 − 𝟎. 𝟎𝟏√𝑷)
where P is the population in thousands. Plot the water demand Q as a function of the
population P (in thousands) for 0 ≤ 𝑃 ≤ 200. Label the axes and provide a title for the
plot.
Page 67 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 68 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 7
Objective
To determine the volume of the water in the tank with complex geometry from the position
(height h) of the float. The program asks the user to enter a value of h in m, and as output
displays the volume of the water in m3.
7.1. Introduction
A computer program is a sequence of computer commands. So far, simple programs have been
done with simple execution in which the order of the execution is the same in which they are
typed. However, there will be times, when execution of a set of commands will be conditional
and a decision would need to be made whether to execute it or skip it. Similarly, there will be
times, when a certain set of commands would be repeated several times within the program like
in iterative problem. Such programs are not simple.
Changing the flow of a program requires some kind of decision-making process within the
program; Decision to whether execute the next command or skip it. These decisions are based on
comparing values of variables. And the tools used to make such decisions are relational and
logical operators.
7.2. Decision Tools
7.2.1. Relation Operators
A relational operator compares two numbers by determining whether a comparison statement is
true (1) or false (0). These relational operators that MATLAB uses are tabulated in Table 10:
Table 10: Relational Operators
Relation Operator Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
~= Not equal to
Some examples of how these relational operators are used are shown in Figure 43. Caution must
be taken when using the relational operators that have double operators like less than or equal to,
the two operators do not have space in between, otherwise MATLAB gives an error.
Page 69 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 71 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 72 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 73 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 74 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 75 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 76 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 77 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
3) Body mass index (BMI) is a measure of obesity. In standard units, it is calculated by the
formula
𝑾
𝑩𝑴𝑰 = 𝟕𝟎𝟑
𝑯𝟐
where W is weight in pounds, and H is height in inches. The obesity classification is:
Page 78 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Write a program in a script file that calculates the BMI of a person. The program asks the
person to enter his or her weight (lb) and height (in.). The program displays the result in a
sentence that reads: “Your BMI value is XXX, which classifies you as SSSS,” where
XXX is the BMI value rounded to the nearest tenth, and SSSS is the corresponding
classification. Use the program for determining the obesity of the following two
individuals:
a) A person 6 ft 2 in. tall with a weight of 180 lb.
b) A person 5 ft 1 in. tall with a weight of 150 lb.
4) Write a program that determines the change given back to a customer in a self-service
checkout machine of a supermarket for purchases of up to $50. The program generates a
random number between 0.01 and 50.00 and displays the number as the amount to be
paid. The program then asks the user to enter payment, which can be one $1 bill, one $5
bill, one $10 bill, one $20 bill, or one $50 bill. If the payment is less than the amount to
be paid, an error message is displayed. If the payment is sufficient, the program
calculates the change and lists the bills and/or the coins that make up the change, which
has to be composed of the least number each of bills and coins. For example, if the
amount to be paid is $2.33 and a $10 bill is entered as payment, then the change is one $5
bill, two $1 bills, two quarters, one dime, one nickel, and two pennies. Execute the
program three times.
5) Write a program in a script file that converts a measure of pressure given in units of
either Pa, psi, atm. or torr to the equivalent quantity in different units specified by the
user. The program asks the user to enter the amount of pressure, its current units, and the
desired new units. The output is the specification of pressure in the new units. Use the
program to:
a) Convert 70 psi to Pa
b) Convert 120 torr to atm
c) Convert 8000 Pa to psi
Page 79 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
6) Write a program in a script file that calculates the cost of a telephone call according to the
following price schedule:
The program asks the user to enter the time the call is made (day, evening, or night) and
the duration of the call (a number that can have one digit to the right of the decimal
point). If the duration of the call is not an integer, the program rounds up the duration to
the next integer. The program then displays the cost of the call. Run the program three
times for the following calls:
a) 8.3 min at 1:32 P.M.
b) 34.5 min at 8:00 P.M.
c) 29.6 min at 1:00 A.M.
Page 80 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 81 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 8
Objective
Write a program that determines and plots the speed and altitude of the rocket as a function of
time during the flight.
8.1. Introduction
A loop is another method to alter the flow of a computer program. In a loop, the execution of a
command, or a group of commands, is repeated several times consecutively. Each round of
execution is called a pass. In each pass at least one variable, but usually more than one, or even
all the variables that are defined within the loop, are assigned new values. MATLAB has two
kinds of loops. In for-end Loops, the number of passes is specified when the loop starts. In
while-end loops the number of passes is not known ahead of time, and the looping process
continues until a specified condition is satisfied. Both kinds of loops can be terminated at any
time with the break command.
8.2. for-end loop
In for-end loops the execution of a command, or a group of commands, is repeated a
predetermined number of times. Figure 50 shows the structure of a for-end loop. In the first pass
𝒌 = 𝒇 and the computer execute the commands between the for and end commands. Then, the
program goes back to the for command for the second pass. k obtains a new value equal to 𝒌 =
𝒇 + 𝒔, and the commands between the for and end commands are executed with the new value of
𝒌. The process repeats itself until the last pass, where 𝒌 = 𝒕. Then the program does not go back
to the for, but continues with the commands that follow the end command. For example, if 𝒌 =
𝟏: 𝟐: 𝟗, there are five loops, and the corresponding values of k are 𝟏, 𝟑, 𝟓, 𝟕, 𝒂𝒏𝒅 𝟗.
Page 82 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 83 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 84 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 85 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 86 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
2) Write a program in a script file that determines 𝒆𝒙 by using the Taylor series
representation. The function 𝒆𝒙 can be represented in a Taylor series by
∞
𝒙
𝒙𝒏 𝒙𝟐 𝒙𝟑
𝒆 =∑ =𝟏+𝒙+ + +⋯
𝒏! 𝟐! 𝟑!
𝒏=𝟎
Use the program to calculate: 𝑒 2 . The program calculates 𝑒 2 by adding terms of the series
and stopping when the absolute value of the term that was added last is smaller than
0.0001. But limit the number of passes to 30. If in the 30th pass the value of the term that
is added is not smaller than 0.0001, the program stops and displays a message that more
than 30 terms are needed.
3) A Fibonacci sequence is a sequence of numbers beginning with 0 and 1, where the value
of each subsequent element is the sum of the previous two elements:
𝒂𝒊+𝟏 = 𝒂𝒊 + 𝒂𝒊−𝟏 , 𝒊. 𝒆. 𝟎, 𝟏, 𝟏, 𝟐, 𝟑, 𝟓, 𝟖, 𝟏𝟑, …
Related sequences can be constructed with other beginning numbers. Write a MATLAB
program in a script file that construct an 𝑛 × 𝑛 matrix such that the first row contains the
first n elements of a sequence, the second row contains the 𝑛 + 1 through 2𝑛𝑡ℎ elements
and so on. The first line of the script should show the order n of the matrix followed by
the values of the first two elements. These two elements can be any two integers, except
they cannot both be zero. A property of matrices thus constructed is that their
determinants are always zero. Run the program for 𝑛 = 4 and 𝑛 = 6 and for different
values of the first two elements. Verify that the determinant is zero in each case (use
MATLAB’s built-in function det).
4) Write a program (using a loop) that determines the expression:
𝒎
(−𝟏/𝟑)𝒏
√𝟏𝟐 ∑
𝟐𝒏 + 𝟏
𝒏=𝟎
Run the program with 𝑚 = 5, 𝑚 = 10, and 𝑚 = 20. Compare the result with π. (Use
format long.)
Page 87 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Run the program with m = 100, m = 100,000, and m = 1,0000,000. Compare the result
with π. (Use format long.)
6) The following is a list of 20 exam scores. Write a computer program that calculates the
average of the top 8 scores.
Exam scores: 73, 91, 37, 81, 63, 66, 50, 90, 75, 43, 88, 80, 79, 69, 26, 82, 89, 99, 71, 59
7) The Taylor series expansion for sin(𝑥) is,
∞
𝒙𝟑 𝒙𝟓 𝒙𝟕 (−𝟏)𝒏
𝐬𝐢𝐧(𝒙) = 𝒙 − + − + ⋯ = ∑ 𝒙𝟐𝒏+𝟏
𝟑! 𝟓! 𝟕! (𝟐𝒏 + 𝟏)!
𝒏=𝟎
where x is in radians. Write a MATLAB program that determines 𝐬𝐢𝐧(𝒙) using the
Taylor series expansion. The program asks the user to type a value for an angle in
degrees. Then the program uses a loop for adding the terms of the Taylor series. If 𝒂𝒏 is
the nth term in the series, then the sum 𝑺𝒏 of the n terms is 𝑺𝒏 = 𝑺𝒏−𝟏 + 𝒂𝒏 . In each pass
calculate the estimated error E given by,
𝑺𝒏 − 𝑺𝒏−𝟏
𝑬=| |
𝑺𝒏−𝟏
Stop adding terms when 𝑬 ≤ 𝟎. 𝟎𝟎𝟎𝟎𝟎𝟏. The program displays the value of 𝐬𝐢𝐧(𝒙). Use
the program for calculating:
a) 𝐬𝐢𝐧(𝟒𝟓°)
b) 𝐬𝐢𝐧(𝟏𝟗𝟓°)
Compare the values with those obtained by using a calculator.
Page 88 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 89 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 9
Objective
Create a function file that calculates the trajectory of a projectile. The inputs to the Y function
are the initial velocity and the angle at which the projectile is fired. The outputs from the
function are the maximum height and distance. In addition, the function generates a plot of the
trajectory.
9.1. Introduction
When a function expression is simple and needs to be calculated only once, it can be typed as
part of the program. However, when a function needs to be evaluated many times for different
values of arguments, it is convenient to create a “user-defined” function. Once a user-defined
function is created (saved) it can be used just like the built-in functions. The function can be a
simple single mathematical expression or a complicated and involved series of calculations. In
many cases it is actually a subprogram within a computer program. The main feature of a
function file is that it has an input and an out- put. This means that the calculations in the
function file are carried out using the input data, and the results of the calculations are transferred
out of the function file by the output. The input and the output can be one or several variables,
and each can be a scalar, a vector, or an array of any size. Schematically, a function file can be
illustrated by:
Page 90 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 91 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 92 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 93 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
highly recommended that the file be saved with a name that is identical to the function name in
the function definition line. In this way the function is called (used) by using the function name.
(If a function file is saved with a different name, the name it is saved under must be used when
the function is called.) Function files are saved with the extension .m.
9.5. Using a user-defined Function
A user-defined function is used in the same way as a built-in function. The function can be called
from the Command Window, from a script file, or from another function. To use the function
file, the folder where it is saved must either be in the current folder or be in the search path
9.6. Anonymous Functions
An anonymous function is a simple (one-line) user-defined function that is defined without
creating a separate function file (m-file). Anonymous functions can be constructed in the
Command Window, within a script file, or inside a regular user-defined function. An anonymous
function is created by typing the following command:
Page 94 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Solution
The motion of a projectile can be analyzed by considering the horizontal and vertical
components. The initial velocity v0 can be resolved into horizontal and vertical components.
𝒗𝒐𝒙 = 𝒗𝒐 𝐜𝐨𝐬(𝜽) 𝒂𝒏𝒅 𝒗𝒐𝒚 = 𝒗𝒐 𝐬𝐢𝐧(𝜽)
In the vertical direction the velocity and position of the projectile are given by:
𝟏
𝒗𝒚 = 𝒗𝒐𝒚 − 𝒈𝒕 𝒂𝒏𝒅 𝒚 = 𝒗𝒐𝒚 𝒕 − 𝒈𝒕𝟐
𝟐
The time it takes the projectile to reach the highest point (𝒗𝒚 = 𝟎) and the corresponding height
are given by:
𝒗𝒐𝒚 𝒗𝒐𝒚 𝟐
𝒕𝒉𝒎𝒂𝒙 = 𝒂𝒏𝒅 𝒉𝒎𝒂𝒙 =
𝒈 𝟐𝒈
The total flying time is twice the time it takes the projectile to reach the highest point, 𝑡𝑡𝑜𝑡 =
2𝑡ℎ𝑚𝑎𝑥 . In the horizontal direction the velocity is constant, and the position of the projectile is
given by:
𝒙 = 𝒗𝒐𝒙 𝒕
Page 95 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Page 96 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Write a user-defined MATLAB function that determines the principal stresses from the
stress components. For the function name and arguments use [Smax,Smin] =
princstress(Sxx,Syy,Sxy). The input arguments are the three stress components, and the
output arguments are the maximum and minimum stresses. Use the function to determine
the principal stresses for the following states of stress:
a) 𝜎𝑥𝑥 = −190 𝑀𝑃𝑎, 𝜎𝑦𝑦 = 145 𝑀𝑃𝑎, 𝑎𝑛𝑑 𝜏𝑥𝑦 = 110 𝑀𝑃𝑎
b) 𝜎𝑥𝑥 = 14 𝑘𝑠𝑖, 𝜎𝑦𝑦 = −15 𝑘𝑠𝑖, 𝑎𝑛𝑑 𝜏𝑥𝑦 = 8 𝑘𝑠𝑖
2) Write a user-defined function that plots an ellipse with axes that are parallel to the x and y
axes, given the coordinates of its center and the length of the axes. For the function name
and arguments use ellipseplot(xc,yc,a,b). The input arguments xc and yc are the
coordinates of the center, and a and b are half the lengths of the horizontal and vertical
Page 97 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
axes (see figure), respectively. This function has no output arguments. Use the function to
plot the following ellipses:
a) 𝑥𝑐 = 3.5, 𝑦𝑐 = 2.0, 𝑎 = 8.5, 𝑎𝑛𝑑 𝑏 = 3
b) 𝑥𝑐 = −5, 𝑦𝑐 = 1.5, 𝑎 = 4, 𝑎𝑛𝑑 𝑏 = 8
3) The heat index, HI (in degrees F), is an apparent temperature. For temperatures higher
than 80 F and humidity higher than 40% it is calculated by:
𝑯𝑰 = 𝑪𝟏 + 𝑪𝟐 𝑻 + 𝑪𝟑 𝑹 + 𝑪𝟒 𝑻𝑹 + 𝑪𝟓 𝑻𝟐 + 𝑪𝟔 𝑹𝟐 + 𝑪𝟕 𝑻𝟐 𝑹 + 𝑪𝟖 𝑻𝑹𝟐 + 𝑪𝟗 𝑹𝟐 𝑻𝟐
where T is temperature in degrees F, R is the relative humidity in percent, 𝑪𝟏 =
−𝟒𝟐. 𝟑𝟕𝟗, 𝑪𝟐 = 𝟐. 𝟎𝟒𝟗𝟎𝟏𝟓𝟐𝟑, 𝑪𝟑 = 𝟏𝟎. 𝟏𝟒𝟑𝟑𝟑𝟏𝟐𝟕, 𝑪𝟒 = −𝟎. 𝟐𝟐𝟒𝟕𝟓𝟓𝟒𝟏, 𝑪𝟓 =
−𝟔. 𝟖𝟑𝟕𝟖𝟑 × 𝟏𝟎−𝟑 , 𝑪𝟔 = −𝟓. 𝟒𝟖𝟏𝟕𝟏𝟕 × 𝟏𝟎−𝟐 , 𝑪𝟕 = 𝟏. 𝟐𝟐𝟖𝟕𝟒 × 𝟏𝟎−𝟑 , 𝑪𝟖 =
𝟖. 𝟓𝟐𝟖𝟐 × 𝟏𝟎−𝟒 , and 𝑪𝟗 = −𝟏. 𝟗𝟗 × 𝟏𝟎−𝟔. Write a user-defined function for
calculating HI for given T and R. For the function name and arguments use
HI=HeatIn(T,R). The input arguments are T in F and, R in %, and the output argument is
HI in F (rounded to the nearest integer). Use the function to determine the heat index for
the following conditions:
a) 𝑻 = 𝟗𝟓℉ 𝒂𝒏𝒅 𝑹 = 𝟖𝟎 %
b) 𝑻 = 𝟏𝟎𝟎℉ 𝒂𝒏𝒅 𝑹 = 𝟏𝟎𝟎 % (𝒄𝒐𝒏𝒅𝒊𝒕𝒊𝒐𝒏 𝒊𝒏 𝒂 𝒔𝒂𝒖𝒏𝒂)
4) The solution of the nonlinear equation 𝒙𝟓 − 𝑷 = 𝟎 gives the fifth root of the number P. A
numerical solution of the equation can be calculated with Newton’s method. The solution
process starts by choosing a value 𝑥1 as a first estimate of the solution. Using this value, a
𝒙𝟏 𝟓 −𝑷
second, more accurate solution 𝑥2 can be calculated with 𝒙𝟐 = 𝒙𝟏 − , which is then
𝟓𝒙𝟏 𝟒
used for calculating a third, still more accurate solution 𝑥3 , and so on. The general
equation for calculating the value of the solution 𝒙𝒊+𝟏 from the solution 𝑥𝑖 is 𝒙𝒊+𝟏 = 𝒙𝒊 −
Page 98 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
𝒙𝒊 𝟓 −𝑷
. Write a user defined function that calculates the fifth root of a number. For
𝟓𝒙𝒊 𝟒
function name and arguments use 𝒚 = 𝒇𝒊𝒇𝒕𝒉𝒓𝒐𝒐𝒕(𝑷), where the input argument P is the
5
number whose fifth root is to be determined, and the output argument y is the value √𝑃.
In the program use 𝑥 = 𝑃 for the first estimate of the solution. Then, by using the general
equation in a loop, calculate new, more accurate solutions. Stop the looping when the
𝑥𝑖+1 −𝑥𝑖
estimated relative error E defined by 𝐸 = | | is smaller than 0.00001. Use the
𝑥𝑖
function cubic to calculate:
5
a) √120
5
b) √16807
5
c) √−15
Page 99 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering
Lab Session 10
Objective
To determine the function of velocity, v(t), and acceleration, a(t), using a function for
displacement s(t). Plot the curves for displacement, velocity and acceleration with time.
10.1. Polynomial representation in MATLAB
In MATLAB, polynomials are represented by a row vector in which the elements are the
coefficients of the polynomial. The first element is the coefficient of the x with the highest
power. The vector has to include all the coefficients, including the ones that are equal to 0.
x can also be a vector or a matrix. In such a case the polynomial is calculated for each element
(element-by-element), and the answer is a vector, or a matrix, with the corresponding values of
the polynomial.
10.3. Determining roots of a polynomial
The roots of a polynomial are the values of the argument for which the value of the polynomial is
equal to zero. MATLAB has a function, called roots, that determines the root, or roots, of a
polynomial. The form of the function is:
10.5.2. Multiplication
Two polynomials can be multiplied using the MATLAB built-in function conv, which has the
form:
The function can be entered as a string expression, or as a function handle. Within a given
interval, the minimum of a function can either be at one of the end points of the interval or at a
point within the interval where the slope of the function is zero (local minimum). When the
fminbnd command is executed, MATLAB looks for a local minimum. If a local minimum is
found, its value is compared to the value of the function at the end points of the interval.
MATLAB returns the point with the actual minimum value for the interval.
For example, consider the function
𝒇(𝒙) = 𝒙𝟑 − 𝟏𝟐𝒙𝟐 + 𝟒𝟎. 𝟐𝟓𝒙 − 𝟑𝟔. 𝟓,
which is plotted in the interval 0 ≤ 𝑥 ≤ 8
in the figure. It can be observed that there
is a local minimum between 5 and 6, and
that the absolute minimum is at 𝑥 = 0.
Using the fminbnd command with the
interval 3 ≤ 𝑥 ≤ 8 to find the location of
the local minimum and the value of the
function at this point gives:
The fminbnd command can also be used to find the maximum of a function. This is done by
multiplying the function by –1 and finding the minimum.
2) Write a user-defined function that multiplies two polynomials. Name the function
p=polymult(p1,p2). The two input arguments p1 and p2 are vectors of the coefficients of
the two polynomials. The output argument p is the resulting polynomial. Use the function
4) The product of three integers with spacing of 5 between them (e.g., 9, 14, 19) is 10,098.
Using MATLAB's built-in function for operations with polynomials, determine the three
integers.
5) The product of four consecutive integers 13,440. Using MATLAB's built-in function for
operations with polynomials, determine the three integers.
Lab Session 11
Objective
To determine a function 𝒘 = 𝒇(𝒕) (t is the independent variable, w is the dependent variable) for
the given data set using curve fitting.
11.1. Introduction
Curve fitting, also called regression analysis, is a process of fitting a function to a set of data
points. The function can then be used as a mathematical model of the data.
11.2. Curve fitting with Polynomial
Curve fitting with polynomials is done in MATLAB with the polyfit function, which uses the
least squares method. The basic form of the polyfit function is:
For the same set of m points, the polyfit function can be used to fit polynomials of any order up
to 𝒎 − 𝟏. If 𝑛 = 1 the polynomial is a straight line, if 𝑛 = 2 the polynomial is a parabola, and
so on. Polynomials with higher order, do not necessarily give a better fit overall.
11.3. Curve fitting with functions other than polynomials
For given data it is possible to estimate, to some extent, which of the functions has the potential
for providing a good fit. This is done by plotting the data using different combinations of linear
and logarithmic axes. If the data points in one of the plots appear to fit a straight line, the
corresponding function can provide a good fit. Table 14 tabulates the linear representation of the
polynomial form of the different functions. Table 15 shows how to obtain the coefficients m and
b of the function from the elements obtained from the polyfit function.
1 1
Reciprocal 𝑦= = 𝑚𝑥 + 𝑏 𝒑 = 𝒑𝒐𝒍𝒚𝒇𝒊𝒕(𝒙, 𝟏./𝒚. 𝟏)
𝑚𝑥 + 𝑏 𝑦
𝒎 = 𝒑(𝟏)
Power 𝑙𝑛𝑦 = 𝑚𝑙𝑛𝑥 + 𝑙𝑛𝑏 𝑝 = 𝑝𝑜𝑙𝑦𝑓𝑖𝑡(𝑙𝑜𝑔(𝑥), 𝑙𝑜𝑔(𝑦).1)
𝒃 = 𝒆𝒙𝒑(𝒑(𝟐))
1 𝒎 = 𝒑(𝟏)
Reciprocal = 𝑚𝑥 + 𝑏 𝑝 = 𝑝𝑜𝑙𝑦𝑓𝑖𝑡(𝑥, 1./𝑦. 1)
𝑦 𝒃 = 𝒑(𝟐)
t 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
w 6.00 4.83 3.70 3.15 2.41 1.83 1.49 1.21 0.96 0.73 0.64
Solution
Step 1: Plotting w vs t from the points given in the question.
Exponential 𝑡 𝑙𝑜𝑔(𝑤)
Reciprocal 𝑡 1./𝑤
The data points appear to line up along a straight line in exponential function hence chosen.
Step 4: Curve fitting to determine the coefficients of the linear form of the exponential function
𝝁 (𝑵𝒔𝒎𝟐 )
4 0.38 0.095 0.032 0.015 0.0078 0.0045 0.0032
(× 𝟏𝟎−𝟓 )
2) The boiling temperature of water (𝑇) at various altitudes (ℎ) is given in the following
table.
a) Determine a linear equation in the form 𝑻 = 𝒎𝒉 + 𝒃 that best fits the data.
b) Use the equation for calculating the boiling temperature at 5,000 m.
c) Make a plot of the points and the equation.
3) The number of bacteria (𝑵𝑩 ) measured at different times t is given in the following table.
a) Determine an exponential function in the form 𝑁𝐵 = 𝑁𝑒 𝛼𝑡 that best fits the data.
b) Use the equation to estimate the number of bacteria after 5 h.
c) Make a plot of the actual data points and the equation on a single graph.
𝒕 (𝒉) 0 1 3 4 6 7 9