0% found this document useful (0 votes)
6 views122 pages

LAB MAnual CPA

The document is a practical workbook for the Computer Programming and Applications course (ME-214) at NED University of Engineering & Technology, detailing laboratory work and assessments. It includes a certification section for students' completion of practical coursework, a summary of marks obtained, and a table of contents outlining various MATLAB experiments. The workbook is prepared by lecturers Mr. Talha Bin Nadeem and Ms. Bushra Fatima and consists of 118 pages.
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)
6 views122 pages

LAB MAnual CPA

The document is a practical workbook for the Computer Programming and Applications course (ME-214) at NED University of Engineering & Technology, detailing laboratory work and assessments. It includes a certification section for students' completion of practical coursework, a summary of marks obtained, and a table of contents outlining various MATLAB experiments. The workbook is prepared by lecturers Mr. Talha Bin Nadeem and Ms. Bushra Fatima and consists of 118 pages.
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/ 122

Computer Programming and Applications

(ME–214)

Name : ____________________________________
Year : ____________________________________
Batch : ____________________________________
Roll No : ____________________________________
Department : ____________________________________

Department of Mechanical Engineering

NED University of Engineering & Technology,


Karachi – 75270, Pakistan
Practical Workbook

ME-214 Computer Programming and Applications

Prepared by: Mr. Talha Bin Nadeem


(Lecturer)
Ms. Bushra Fatima
(Lecturer)

This is certified that this practical book contains 118 pages.

Chairman

Department of Mechanical Engineering

NED University of Engineering & Technology,


Karachi – 75270, Pakistan
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Certificate for Completion of Laboratory Work


This is to certify that Mr./Ms. __________________________________ student of F.E.
(Mechanical) bearing Roll No. __________ has completed his/her practical course work in the
subject of Computer Programming and Applications Lab (ME-214) as prescribed and approved
by the Board of Studies of the Department of Mechanical Engineering.
The overall performance of the student has been assessed as Excellent/Very Good/ Good/
Satisfactory/Unsatisfactory.

Checked/Verified By:

Name: _______________________

Signature: ____________________

Date: ________________________

Summary of Marks Obtained


Sr. No. Components Max. Marks Marks Obtained
Rubric Based Practical Nos (P3):
1 13
Rubric Based Practical Marks
2 Open Ended Lab 7
Total Marks 20

Marks Awarding Scheme:


𝑀𝑎𝑟𝑘𝑠 𝑓𝑜𝑟 𝑂𝐵𝐸 𝑏𝑎𝑠𝑒𝑑 𝑝𝑟𝑎𝑐𝑡𝑖𝑐𝑎𝑙 (𝑃3)
𝑆𝑢𝑚 𝑜𝑓 𝑚𝑎𝑟𝑘𝑠 𝑜𝑏𝑡𝑎𝑖𝑛𝑒𝑑 𝑓𝑟𝑜𝑚 𝑟𝑢𝑏𝑟𝑖𝑐 𝑓𝑜𝑟𝑚
= × 13
𝑀𝑎𝑥. 𝑚𝑎𝑟𝑘𝑠 𝑓𝑟𝑜𝑚 𝑟𝑢𝑏𝑟𝑖𝑐 𝑓𝑜𝑟𝑚
ME-214 Computer Programming and Applications Department of Mechanical Engineering

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.

Figure 1: The default view of MATLAB desktop


The layout has a Tool strip at the top, and three windows underneath. At the top of the Tool strip
there are three tabs: HOME, PLOTS, and APPS. Clicking on the tabs changes the icons in the
Tool strip. Commonly, MATLAB is used with the HOME tab selected. The associated icons are
used for executing various commands. The PLOTS tab can be used to create plots, and the APPS
tab can be used for opening additional applications and Toolboxes of MATLAB.
1.2. The default layout
The default layout in MATLAB R2018b consists of the following three windows that are
displayed under the Tool strip: the Command Window, the Current Folder Window, and the
Workspace Window. A list of several MATLAB windows and their purposes is given in Table 1.

Page 1 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Table 1: MATLAB Windows

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..

Figure 2: Command Window: Executing commands one at a time

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.

1.4. The Command History Window


This window does not appear in the default layout. To see the window, go to Home tab →
Environment panel → Layout’s drop down menu → Command history → Docked as shown in
Error! Reference source not found..

Page 3 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Figure 3: Accessing the Command history Window


The Command History Window lists the commands that have been entered in the Command
Window. This includes commands from previous sessions. A command in the Command History
Window can be used again in the Command Window in two ways:
1) By double-clicking on the command, the command is reentered in the Command
Window and is directly executed.
2) By dragging and dropping the command to the Command Window. This action permits
changes to be made in the command if required. Pressing Enter would then execute the
command.
The list in the Command History Window can be cleared by selecting the lines to be deleted and
then right-clicking the mouse and selecting Delete Selection. The whole history can be deleted
by right-clicking the mouse and selecting Clear Command History in the menu that opens.
1.5. Arithmetic operations with scalars with their order of precedence
Table 4 shows the arithmetic operators that can be used with scalar numbers that can be used in
arithmetic calculations directly (as with a calculator) or they can be assigned to variables, which
can subsequently be used in calculations. The operators of arithmetic operations are tabulated in
Table 4:
Table 4. Arithmetic operators with scalar numbers
Precedence Operation Operator Command Window Step by step operations
First Parentheses () >> (7+8)/2 1. 7 + 8 →15
ans = 7.5000 2. 15 / 2 → 7.5

Second Exponentiat ^ >> 27^(1/3)+32^0.2 1. 271/3 → 3


ion. 2. 320.2 →2
ans = 5
3. 3 + 2 → 5

Page 4 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Third Multiplicati *, /, \ >> 25^3/1*2*3 1. 253 → 15625


on, Right 2. 15625/1→15625
ans =
division, 3. 15625 * 2 →31250
Left division 93750 4. 31250 * 3 → 93750
(Equal
Precedence)

Fourth Addition +, - >> 4+5/3+2 1. 5/3 →1.6667


and 2. 4 + 1.6667 →
subtraction ans = 7.6667
5.6667
3. 5.6667+2 → 7.6667

Fifth Assignment = A=27^(1/3)+32*0.2/6- 1. 271/3 → 3


Operator 1 2. 32*0.2→6.400
(assigns a
A= 3. 6.4000/6→ 1.0667
value to a
variable 4. 3+1.0667 → 4.0667
3.0667
name placed 5. 4.0667 – 1 → 3.067
to the left 6. A = 3.067
side of =)
It should be pointed out here that all the operators except the left division are the same as in most
calculators. For scalars, the left division is the inverse of the right division with the positions of
the numerator and denominator swapped.
In an expression that has several operations; higher-precedence operations are executed before
lower-precedence operations. If two or more operations have the same precedence, the
expression is executed from left to right.
1.6. Display Formats
The user can control the format in which MATLAB displays the output on the screen. The
format can be changed with the format command. Once the format command is entered, all the
outputs that follow are displayed in the specified format. Several of the available formats are
listed in the Error! Reference source not found.. The format in which numbers are displayed d
oes not affect how MATLAB computes and saves numbers.
Table 5: Display Formats

Command Description Command Window

Fixed-point with 4 decimal >> 290/7


format short digits for: 0.001 ≤ number ≤ ans =
1000 Otherwise display

Page 5 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

format short e. 41.4286

Fixed-point with 15 decimal >> 290/7


digits for: 0.001 ≤ number ≤ ans =
format long
1000 Otherwise display
format long e. 41.428571428571431

>> 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

Eliminates blank lines to allow more lines with information


format compact
displayed on the screen.

format loose Adds blank lines (opposite of compact).

1.7. MATLAB built-in Functions


In addition to basic arithmetic operations, expressions in MATLAB can include functions.
MATLAB has a very large library of built-in functions, some of which are listed in Table 7. A
function has a name and an argument in parentheses.
The inverse trigonometric functions are 𝑎𝑠𝑖𝑛(𝑥), 𝑎𝑐𝑜𝑠(𝑥), 𝑎𝑡𝑎𝑛(𝑥), 𝑎𝑐𝑜𝑡(𝑥) for the angle in
radians; and 𝑎𝑠𝑖𝑛𝑑(𝑥), 𝑎𝑐𝑜𝑠𝑑(𝑥), 𝑎𝑡𝑎𝑛𝑑(𝑥), 𝑎𝑐𝑜𝑡𝑑(𝑥) for the angle in degrees. The hyperbolic
trigonometric functions are 𝑠𝑖𝑛ℎ(𝑥), 𝑐𝑜𝑠ℎ(𝑥), 𝑡𝑎𝑛ℎ(𝑥), 𝑎𝑛𝑑 𝑐𝑜𝑡ℎ(𝑥).

1.8. Variable naming rules

Page 6 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

A variable can be named according to the following rules:


➢ Must begin with a letter.
➢ Can be up to 63 characters long.
➢ Can contain letters, digits, and the underscore character.
➢ Cannot contain punctuation characters (e.g., period, comma, semicolon).
➢ MATLAB is case-sensitive: it distinguishes between uppercase and lowercase letters. For
example, AA, Aa, aA, and aa are the names of four different variables.
➢ No spaces are allowed between characters (use the underscore where a space is desired).
➢ Avoid using the name of a built-in function for a variable (i.e., avoid using cos, sin, exp,
sqrt, etc.). Once a function name is used to for a variable name, the function cannot be
used.
There are 20 words, called keywords that are reserved by MATLAB for various purposes and
cannot be used as variable names. When typed, these words appear in blue. An error message is
displayed if the user tries to use a keyword as a variable name. These words are:
break, case, catch, classdef, continue, else, elseif, end, for, function, global, if, otherwise,
for, persistent, return, spmd, switch, try, while
A number of frequently used variables already defined in MATLAB are listed in Table 6:
Table 6. Predefined MATLAB variables

Variable Description

MATLAB automatically stores the value of last expression in ans if


ans
the user does not assign a specific variable.

eps The smallest difference between two numbers.

i, j Defined as √−1, which is: 0 + 1.0000i.

inf Infinity.

NaN Not a number. e.g., 0/0

pi The number π.

Table 7. MATLAB Built-in Functions

Category Syntax Description Example


>>sqrt(81)
sqrt(x) Square root. ans =
Math 9
Real nth root of a real number >> nthroot(80,5)
nthroot(x,n)

Page 7 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

x. (If x is negative n must be an odd ans =


integer.) 2.4022
>>exp(5)
exp(x) Exponential ex ans =
148.4132
>> abs(-24)
abs(x) Absolute value. ans =
24
>> log(1000)
Natural logarithm. Base e
log(x) ans =
logarithm (ln).
6.9078
>>log10(1000)
log10(x) Base 10 logarithm. ans =
3.0000
>>factorial(5)
The factorial function x!
factorial(x) ans =
(x must be a positive integer.)
120
Sine of angle x (x in >> sin(pi/6)
sin(x) radians). ans =
sind(x) Sine of angle x (x in 0.5000
degrees).
Cosine of angle x (x in >> cosd(30)
cos(x) radians). ans =
Trigonometri cosd(x) Cosine of angle x (x in 0.8660
c degrees).
Tangent of angle x (x in radians). >> tan(pi/6)
tan(x)
Tangent of angle x (x in ans =
tand(x)
degrees). 0.5774
Cotangent of angle x (x in >> cotd(30)
cot(x)
radians). Cotangent of angle x ans =
cotd(x) (x in degrees). 1.7321
>> round(17/5)
round(x) Round to the nearest integer. ans =
3
>> fix(13/5)
Rounding fix(x) Round toward zero. ans =
2
>> ceil(11/5)
ceil(x) Round toward infinity. ans =
3

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

1.9. Solved Problems


𝜋
1. By defining 𝑥 = in the command window, prove that the RHS = LHS
5
𝑥 tan 𝑥 + sin 𝑥
cos2 =
2 2 tan 𝑥

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

1.10. Review problems

1) Suppose that 𝑢 = 1 and 𝑣 = 3, evaluate the following expressions using MATLAB

(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.)

3) Two trigonometric identities are given by:

(a) (sin 𝑥 + cos 𝑥)2 = 1 + 2 sin 𝑥 cos 𝑥

(b) 1 − 2 cos 𝑥 − 3 cos2 𝑥 1 − 3 cos 𝑥


=
sin2 𝑥 1 − cos 𝑥
For each part verify that the identity is correct by calculating the values of the left and right
sides of the equation, substituting two values of x ; (1) x=20° and (2) x= 𝜋⁄10.

Page 10 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _01_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

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.

2.2. Script Files


Script File is a sequence of MATLAB commands; also called a program that can be created,
saved and run such that the commands are executed in the order they are written. Unlike the
command window, script files can be edited, saved, retrieved some other time and run again.
However, the outputs of the commands written in the script file without the semicolon at the end
are displayed in the command window. Script file is also called m-file because the extension .m
is used when it is saved. It is also called Editor because of its editable capability.
2.2.1. Creating and saving script file
To create a script file, follow any of the following:
1) Go to Home tab → File Panel →New drop-down menu → Select New script from the list
as shown in Figure 4.
2) Go to Home tab → File Panel → Click on New script option
3) Press Ctrl + N

Figure 4: Creating a script file


2.2.2. Working in a script file

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 5: Script file with its associated toolstrip tabs


2.2.3. Saving and naming a script file
Before a script file can be executed it has to be saved. This is done by clicking Save in the
Toolstrip and selecting Save As from the menu that opens. When saved, MATLAB adds the
extension .m to the name.
The rules for naming a script file are:
1) Follow the rules of naming a variable (must begin with a letter, can include digits and
underscore, no spaces, and can be up to 63 characters long).
2) The names of user-defined variables, predefined variables, and MATLAB commands
or functions should not be used as names of script files
2.2.4. Running a script file
To execute a script file that has been saved already, any of the three methods mentioned below
can be followed:

1) Click on the Run icon under the editor tab


2) Press the keyboard shortcut key F5 (but make sure that the editor window is selected
when you do it)
3) Type the file name in the Command Window and then pressing the Enter key
2.3. Current Folder Window
It is worth noting that the file will be executed if the folder where the file is saved is the same as
the current folder mentioned in the current folder field as shown in Figure 6.
Page 13 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Figure 6: Current folder field


If an attempt is made to execute a script file by clicking on the Run icon when the current folder
is not the folder where the script file is saved, then the prompt shown in Figure 7. The user can
then change the current folder to the folder where the script file is saved or add it to the search
path.

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

Manual Solution MATLAB Solution


Law of Cosines (figure b): Script File
𝐹𝑅 = √62 + 82 − 2(6)(8) cos 75 = 8.67 kN clear, clc
T=6; F=8; %forces
Law of Sines: theta=75; %angle between 2 forces
sin 𝛼 sin 75 % resultant force: Law of cosines
=
8 𝐹𝑅 Fr= sqrt(T^2+F^2-2*T*F*cosd(theta))
𝛼 = 63.05° measured from the force 6 kN. % angle of Fr: Law of sines
alpha=asind((8/Fr)*sind(75))
Angle measured from +ve x-axis: (Figure a) % angle CW from +ve x-axis
𝜙 = 63.05 − 60 = 3.05° phi=alpha-60
Command Window
Fr =
8.6691
alpha =
63.0463
phi =
3.0463

2) Electric power is to be generated by installing a hydraulic turbine–generator at a site 120 m


below the free surface of a large water reservoir that can supply water at a rate of 1500 kg/s
steadily. Write a script file to determine the power generation potential.
Script file
clear, clc
m_dot=1500; %kg/s

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

4) In a triangle, shown in figure a=27 in., b=43 in., and c=57


in. Define a, b, and 𝛾 as variables, and then:
a) Calculate the angles 𝛼, 𝛽, and 𝛾 by substituting the
variables in the law of cosines. (Law of cosines:
𝑐 2 = 𝑎2 + 𝑏 2 − 2𝑎𝑏 cos 𝛾).
b) Verify the law of tangents by substituting the results
into the right and left sides of:
𝟏
𝒃 + 𝒄 𝐭𝐚𝐧 [𝟐 (𝜷 − 𝜸)]
𝑳𝒂𝒘 𝒐𝒇 𝑻𝒂𝒏𝒈𝒆𝒏𝒕𝒔: =
𝒃 − 𝒄 𝐭𝐚𝐧 [𝟏 (𝜷 + 𝜸)]
𝟐

Page 17 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _02_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

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.

3.1.1. Creating vectors with elements without constant spacing


The Vectors with elements that do not observe any arithmetic progression (i.e., two consecutive
elements do not have constant spacing between them) are entered one by one explicitly within
the square brackets.
Row vector: elements typed within the square brackets, separated by either a comma or space
Column vector: Elements typed within the square brackets, separated by either a semi-colon or
enter
Table 8 illustrates two ways of creating row and column vectors.
Table 8: Creating row and column vectors
Creating a row vector Creating a column vector

3.1.2. Creating vectors with elements with constant spacing


In order to create vectors with elements observing arithmetic progression, either a colon operator

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.

Figure 9: Using colon operator and linspace function


Default MATLAB setting when using colon and linspace functions.
1) If the constant spacing is 1, one may skip mentioning the constant spacing when using a
colon operator. Example:
>>a=1:5
a=
1 2 3 4 5
>> %or
>> a=1:1:5
a=
1 2 3 4 5

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.

Figure 10: A 3 x 6 matrix created in MATLAB.


3.2. Transpose operator
The transpose operator (‘) when applied to a vector, switches a row vector to a column vector
and vice-versa. When applied to a matrix, it switches the rows to columns. The transpose
operator is applied by typing a single quote’ following the variable to be transposed.
3.3. Array Addressing
Elements in an array (either vector or matrix) can be addressed individually or in subgroups. This
is useful when there is a need to redefine only some of the elements, when specific elements are
to be used in calculations, or when a subgroup of the elements is used to define a new variable.
3.3.1. Addressing elements in a vector
The address of an element in a vector is its position in the row (or column). Figure 11 shows how
the elements in the vector are addressed to address one element only and how these elements can
be used in mathematical expressions.

Page 21 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Figure 11: Addressing elements in a vector


3.3.2. Addressing elements in a matrix
The address of an element in a matrix is its position, defined by the row number and the column
number where it is located. For a matrix assigned to a variable MAT, MAT (k,p) refers to the
element in row k and column p. The element addressing can be used to reassign a value of one of
the elements in the matrix as shown in Figure 12.

Figure 12: Addressing elements in a matrix


3.3.3. Using a colon operator: for array addressing
A colon can be used to address a range of elements in a vector or a matrix. For a vector:
1) va(:) Refers to all the elements of the vector va (either a row or a column vector).
2) va(m:n) Refers to elements m through n of the vector va. Example:

Page 22 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Figure 13. Addressing multiple elements in a vector


For a matrix:
A(:,n) Refers to the elements in all the rows of column n of the matrix A.
A(n,:) Refers to the elements in all the columns of row n of the matrix A.
A(:,m:n) Refers to the elements in all the rows between columns m and n of the matrix A.
A(m:n,:) Refers to the elements in all the columns between rows m and n of the matrix A.
A(m:n,p:q) Refers to the elements in rows m through n and columns p through q of the matrix A

Page 23 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

3.4. Adding elements to an existing array


3.4.1. Adding elements to an existing vector
To add elements in the vector already defined, essentially array addressing is used as shown in
Figure 14.

Figure 14: Adding elements to an existing vector


3.4.2. Adding elements to an existing matrix
Adding elements to an already defined matrix is also done using the array addressing technique
as illustrated in Figure 15.

Figure 15: Adding elements to an existing matrix

Page 24 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

3.5. Deleting elements from an existing array


To delete the elements, array addressing techniques are employed to address the elements to be
deleted, which are reassigned a null value using empty set of square brackets.
3.5.1. Deleting elements from an existing vector

Figure 16: Use of a null vector to delete elements in a vector


3.5.2. Deleting elements from an existing matrix
To delete elements from a matrix, it is important to note that the matrix dimensions should not be
disturbed. In order to ensure that, either an entire column will be deleted (meaning all rows of
that column) or an entire row will be deleted (meaning all columns of that row). Figure 17
illustrates the deletion of an entire 3rd column (all rows).

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.

3.8. Review problems


1) Using array addressing and a single line commend:
a) Define a vector by the name of anine that contains 9 elements with all elements equal
to 9.
b) Define a matrix by the name of MA of the order 4 x 3, with all elements equal to 12.
c) Create the matrix E.

Page 26 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _03_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

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.

Figure 18: Adding/subtracting the two vectors of same size

Figure 19: Adding/subtracting a scalar value to/from a vector

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.

Figure 20: Order of precedence of the colon operator


4.2. Array multiplication
The multiplication operation (*) is executed by MATLAB according to the rules of linear
algebra. This means that if A and B are two matrices, the operation A*B can be carried out only
if the number of columns in matrix A is equal to the number of rows in matrix B. The result is a
matrix that has the same number of rows as A and the same number of columns as B.
Multiplication of the matrices is not commutative i.e. A*B ≠ B*A.
4.2.1. Dot product of 2 vectors
To obtain the dot or scalar product of 2 vectors, the following should be considered:
1) Element size in both vectors is same
2) The first vector should be a row vector and the second vector a column vector.
This is illustrated in Figure 21.

Figure 21: Dot/Scalar product of 2 vectors


If the positions of the row and column vector are swapped, then the product is no longer a dot
product as shown in Figure 22.

Page 29 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Figure 22: Vector multiplication (column x row vector)


4.2.2. Dot product of 2 vectors
When a scalar value is being multiplied with an array, it by default multiplies with each and
every element of the array. Such a multiplication observes commutative property as shown in
Figure 23.

Figure 23: Scalar multiplication with an array


4.3. Array division
MATLAB has two types of array division, right division, and left division.
4.3.1. Left Division (\)
Left division is used to solve the matrix equation AX=B. In this equation X and B are column
vectors. This equation can be solved by multiplying, on the left, both sides by the inverse of A:
𝑨−𝟏 𝑨𝑿 = 𝑨−𝟏 𝑩
The left-hand side of this equation is X, since
𝑨−𝟏 𝑨𝑿 = 𝑰𝑿 = 𝑿
So, the solution of 𝑨𝑿 = 𝑩 is,
𝑿 = 𝑨−𝟏 𝑩
In MATLAB the last equation can be written by using the left division character:
𝑿 = 𝑨/𝑩

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)

Figure 24: Left division


Page 31 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Figure 25: Right division


4.5. Element wise operations
In the regular operators for multiplication and division (* and /) with arrays, the mathematical
operations follow the rules of linear algebra. There are, however, many situations that require
element-by-element operations. These operations are carried out on each of the elements of the
array (or arrays). Addition and subtraction are by definition already element-by-element
operations. Element-by-element operations can be done only with arrays of the same size.
Element-by-element multiplication, division, or exponentiation of two vectors or matrices is
entered in MATLAB by typing a period (.) in front of the arithmetic operator. If a and b are the
vectors of the same order, then enforcing element wise operations including multiplication, right
division, left division and exponentiation would be done as follows:

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.

Figure 26: Formula vectorization


4.6. MATLAB’s built-in functions for analyzing arrays

Function Description Example

length(A) Returns the number of elements in the >> A=[5 9 2 4];


vector A. >> length(A)
ans =
4
size(A) Returns a row vector [m,n], where m and n >> A=[6 1 4 0 12; 5 19 6 8 2]
are the size (row and column) of the array >> size(A)
A. ans =
2 5

mean(A) If A is a vector, returns the mean value of >> A=[5 9 2 4];


the elements of the vector. >> mean(A)
ans =
5

Page 33 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Function Description Example

C=max(A) If A is a vector, C is the largest element in >> A=[5 9 2 4 11 6 11 1];


A. If A is a matrix, C is a row vector >> C=max(A)
containing the largest element of each C =
column of A. 11

[d,n]=max(A) If A is a vector, d is the largest element in >> [d,n]=max(A)


A, and n is the position of the element (the d =
first if several have the max value). 11
n=
5
min(A) The same as max(A), but for the smallest >> A=[5 9 2 4];
element. >> min(A)
The same as [d,n]= max(A), but for the ans =
[d,n]=min(A) 2
smallest element.
sum(A) If A is a vector, returns the sum of the >> A=[5 9 2 4];
elements of the vector. >> sum(A)
ans =
20
sort(A) If A is a vector, arranges the elements of >> A=[5 9 2 4];
the vector in ascending order. >> sort(A)
ans =
2 4 5 9
median(A) If A is a vector, returns the median value >> A=[5 9 2 4];
of the elements of the vector. >> median(A)
ans =
4.5000
std(A) If A is a vector, returns the standard >> A=[5 9 2 4];
deviation of the elements of the vector. >> std(A)
ans =
2.9439
det(A) Returns the determinant of a square matrix >> A=[2 4; 3 5];
A. >> det(A)
ans =
-2
dot(a,b) Calculates the scalar (dot) product of two >> a=[1 2 3];
vectors a and b. The vectors can each be >> b=[3 4 5];
row or column vec- tors. >> dot(a,b)
ans =
26

Page 34 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Function Description Example

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

Script file of solution

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.

Figure 27: The lamp

Manual Solution MATLAB Solution


OA=[2 -1.5 6], OB=[-4 1.5 0], OC=[0 1.5 0] Script File
AB=OB - OA = [-6 3 -6] m, clear, clc
AC=OC - OA=[-2 3 -6] m %position vectors

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.

Manual Solution MATLAB Solution


𝑇 = 6[sin 30 cos 30] kN Script File
clear, clc
𝐹 = 8[cos 45 − sin 45] kN T=6; theta=30;
T=T*[sind(theta) cosd(theta)];
𝐹𝑅 = 𝑇 + 𝐹 =
F=8*[cosd(45) -sind(45)];
[6 sin 30 + 8 cos 45 6 cos 30 − 8 sin 45] kN Fr=T+F % vector form
m_Fr=sqrt(sum(Fr.^2))
|𝐹𝑅 | =
theta=atand(Fr(2)/Fr(1))
√(6 sin 30 + 8 cos 45)2 + (6 cos 30 − Command Window
8 sin 45)2 =8.67 kN
Fr =
8.6569 -0.4607
−1
6 cos 30 − 8 sin 45
𝜃 = tan = −3.05° m_Fr =
6 sin 30 + 8 cos 45
8.6691
theta =
-3.0463

Page 38 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

4.8. Review problems


1) By creating F1 and F2 as vectors, write a script file to determine the resultant force acting
on the pipe assembly.

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.

4) By defining F1 in a Cartesian vector, write a MATLAB program to determine the


magnitude of the moment produced by F1 about point 0. Use MATLAB’S built-in
function cross. [𝑀𝑜 = 𝑟0𝐴 x 𝐹𝐴 ].

Page 40 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

5) The center of mass (𝑥̅ + 𝑦̅ + 𝑧̅), of n particles can be calculated by:


∑𝑖=𝑛
𝑖=1 𝑚𝑖 𝑥𝑖 ∑𝑖=𝑛
𝑖=1 𝑚𝑖 𝑦𝑖 ∑𝑖=𝑛
𝑖=1 𝑚𝑖 𝑧𝑖
𝑥̅ = , 𝑦̅ = , 𝑧̅ =
∑𝑖=𝑛
𝑖=1 𝑚𝑖 ∑𝑖=𝑛
𝑖=1 𝑚𝑖 ∑𝑖=𝑛
𝑖=1 𝑚𝑖

Where 𝑥𝑖 , 𝑦𝑖 and 𝑧𝑖 and 𝑚𝑖 are the coordinates and


the mass of particle i, respectively. The
coordinates and mass of 6 particles are listed in
the following table. Write a script file in
MATLAB to calculate the center of mass of the
particles.
x coordinate y coordinate z coordinate
Particle Mass (kg)
(mm) (mm) (mm)
A 0.5 -10 8 32
B 0.8 -18 6 19
C 0.2 -7 11 2
D 1.1 5 12 -9
E 0.4 0 -8 -6
F 0.9 25 -20 8

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

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _04_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

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.

Figure 28: Workspace Window

Page 43 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

5.3. Input command


In cases when the variable’s values are not definite and are to be entered by the user, the
programmer only defines the variable name in the script file and lets the user enter his/her
desired value. This is done using the input command.

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

Figure 30: Inputting arrays


The input command can also be used to assign a string to a variable. This can be done in one of
two ways. One way is to use the command in the same form as shown above, and when the
prompt message appears the string is typed between two single quotes in the same way that a
string is assigned to a variable without the input command. The second way is to use an option in
the input command that defines the characters that are entered as a string. The form of the
command is:

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.

Figure 31: Assigning a string using the input command

Page 45 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

5.4. Output commands


5.3.1. Automatic display
In MATLAB, all the commands without the suppressor at the end of the statement are
automatically displayed. In an automatic display, the display includes the variable name (if not
defined, ans is used), assignment operator and the value as shown in Figure 32.

Figure 32: Automatic display


5.3.2. The ‘disp’ command
The disp command is used to display the elements of a variable without displaying the name of
the variable, and to display text. The format of the disp command is:

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.

Figure 33: Use of dip command

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

5.3.3. fprintf function


The syntax of the fprintf statement is much more flexible (and therefore more complicated!) than
disp command. The function fprintf can be used:
1) To display output (text and data) on the screen.
2) to control the format of the output (unlike with the disp command)
3) To display the text and numerical values of variables in the same line without using the
num2str function.
5.3.3.1. line feed
It is worth noting that unlike the disp command, fprintf does not shift the command prompt to the
next line after displaying its output. So, to ensure the command prompt (and hence the next
command) shifts to the next line, a line feed \n is added in the text message as shown in Figure
36.

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 formatting elements are;

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

2) A 300-lb garage door is being opened by


pulling on the cable as shown. As the door is
lifted the force, F, in the cable, as a function
of the angle, is given by:
𝟑𝟎𝟎 × 𝟒. 𝟓 𝐬𝐢𝐧 𝜽
𝑭=
𝟑 𝐜𝐨𝐬(𝜶 − 𝜽)
where,
𝟏 + 𝟑 𝐜𝐨𝐬 𝜽
𝐬𝐢𝐧 𝜶 =
√(𝟏 + 𝟑 𝐜𝐨𝐬 𝜽)𝟐 + (𝟑 − 𝟑 𝐬𝐢𝐧 𝜽)𝟐
Calculate F for 𝜃 = 0° through 90° with
increments of 10°. Display the results in a
two-column table.
Script File

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

5.6. Review Problems


1) A person at point A spots a
child in trouble at point B
across the river. The person
can run at a speed of 8.6 ft/s
and can swim at a speed of 3.9
ft/s. in order to reach the child
in the shortest time, the person
runs to point C and then
swims to point B as shown in
figure.
Write a MATLAB program
that determines the distance x to point C that
minimizes the time the person can reach the
child. In the program, define a vector x with
values ranging from 0 to 5000 with increments of
12 use this vector to calculate the corresponding
valyes of t. Then, find the value of x that
corresponds to the shortest time. [Hint: use the
built-in function min]

2) An isosceles triangle sign is desiged to have a


triangular prited area of 600 in2 (shaded area
with a base length of a and height h in the

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.

3) Two projectiles, A and B, are shot at the


same instant from the same spot. Projectile A
is shot at a speed of 560 m/s at an angle of
43° and projectile B is shot at a speed of 680
m/s at an angle of 50°. Determine which
projectile will hit the ground first. Then take
the flying time (𝒕𝒇 ) of that projectile and
divide it into ten increments by creating a
vector t with 11 equally spaced elements (the
first element is 0, the last is 𝒕𝒇 ). At each time
t calculate the position vector (𝒓𝑨𝑩 ) between
the two projectiles. Display the results in a three-column matrix where the first column is
t and the second and third columns are the corresponding x and y components of 𝒓𝑨𝑩 .

4) A ball that is dropped on the floor bounces back up


many times, reaching a lower height after each
bounce. When the ball impacts the floor, its
rebound velocity is 0.85 times the impact velocity.
The velocity (𝑣) with which a ball hits the floor
after being dropped from a height (ℎ) is given by
𝑣 = √2𝑔ℎ, where 𝑔 = 9.81 𝑚/𝑠 2 . The time
between successive bounces is given by 𝑡 = 𝑣⁄𝑔,
where 𝑣 is the upward velocity after the last impact.
Consider a ball that is dropped from a height of 2
m. Determine the times at which the ball hits the
floor for the first eight bounces. Set 𝑡 = 0, when the
ball hits the floor for the first time. (Calculate the
velocity of the ball when it hits the floor for the first time. Derive a formula for the time
of the following hits as a function of the bounce number. Then create a vector 𝑛 =
1, 2, 3, … , 8 and use the formula (use element-by element operations) to calculate a vector
with the values of t for each n.) Display the results in a two-column table where the
values of n and t are displayed in the first and second columns, respectively.

Page 53 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _05_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

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.

Figure 37: A formatted 2D plot created in MATLAB

Page 55 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

6.2. The plot command


The plot command is used to create two-dimensional plots. The simplest form of the command
is:

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.

6.2.1. Line specifiers


The specifiers are typed inside the plot command as ‘strings’. They specify the color of the line,
the marker type and the type of the line, typed in any order. The specifiers are optional. This
means that none, one, two, or all three types can be included in a command.
• Line style

Figure 39: Symbols to denote different Line style


• Color of the line

Figure 40: Characters to signify different Line Color

Page 57 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

• Marker type

Figure 41: Characters to opt for specific Marker type


Some examples:
plot(x,y) A blue solid line connects the points with no markers (default).

plot(x,y,‘r’) A red solid line connects the points.

plot(x,y,‘--y’) A yellow dashed line connects the points.

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

Table 9: Properties of lines and markers

Property Name Description Possible Property Values

A number of units of points


LineWidth (or linewidth) Specifies the width of the line
(default 0.5)

Specifies the size of the


MarkerSize (or markersize) A number of units of points
marker

Specifies the color of the


MarkerEdgeColor (or Color specifiers from the table
marker, or the color of the
markeredgecolor) above, types as string
edge line for filled markers

MarkerFaceColor (or Specifies the color of the Color specifiers from table
markerfacecolor) filling for filled markers above, typed as string

Miscellaneous example of a plot:


plot(x,y,‘-mo’,‘LineWidth’,2,‘markersize’,12, ‘MarkerEdgeColor’,‘g’,‘markerfacecolor’,‘y’)
This creates a plot that connects the points with a:
• magenta solid line and circles as markers at the points.
• the line width is 2 points and
• the size of the circle markers is 12 points.
• *The markers have a green edge line and yellow filling./*
6.3. Plot of function using fplot function
The fplot command plots a function with the form between specified limits. The command has
the form

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

Figure 42: Graph obtained using fplot


The function should be typed using element-by-element operations and can include previously
defined variables. The function to be plotted can be typed as a function of any letter. For
example, the function 8𝑥 2 + 5 cos 𝑥 can be typed as
@ (t) 8*t.^2+5*cos(t) or
@ (z) 8*z.^2+5*cos(z)
limits: The limits argument is a vector with two elements that specify the domain of x
[xmin,xmax]
line specifiers: The line specifiers are the same as in the plot command.
6.4. Plotting multiple graphs on the same plot
6.4.1. Using plot command
The command plot(x,y,u,v,t,h) creates three graphs—y vs. x, v vs. u, and h vs. t—all in the same
plot. The vectors of each pair must be of the same length. MATLAB automatically plots the
graphs in different colors so that they can be identified. It is also possible to add line specifiers
following each pair. For example the command plot(x,y,‘-b’,u,v,‘--r’,t,h,‘g:’)
6.4.2. Using hold on and hold off commands
To plot several graphs using the hold on and hold off commands, one graph is plotted first with
the plot command. Then the hold on command is typed. This keeps the Figure Window with the
first plot open, including the axis properties and formatting.

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:

6.5.2. The title command:


A title can be added to the plot with the command:

Page 61 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

6.5.3. The text command:


A text label can be placed in the plot with the text or gtext commands:

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:

NE Places the legend at the upper-right corner of the plot (default).

NW Places the legend at the upper-left corner of the plot.

SE Places the legend at the lower-right corner of the plot.

SW Places the legend at the lower-left corner of the plot.

B Places the legend inside the plot in a location that interferes the least with the graphs.

BO Places the legend in a least unused space outside the plot.

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

6.6. Solved problems


1) 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. The
position 𝑥(𝑡) of the mass is given by the equation:
𝟐𝒇𝒐 𝝎𝒏 − 𝝎 𝝎𝒏 + 𝝎
𝒙(𝒕) = 𝟐 𝟐
𝐬𝐢𝐧 ( 𝒕) 𝐬𝐢𝐧 ( 𝒕)
𝝎𝒏 − 𝝎 𝟐 𝟐
𝐹
Where 𝐹(𝑡) = 𝐹𝑜 sin(𝜔𝑡), and 𝑓𝑜 = 𝑜⁄𝑚, 𝜔 is the frequency of the applied force, and
𝜔𝑛 is the natural frequency of the helicopter. When the value of m is close to the value of
𝜔𝑛 , the vibration consists of fast oscillation with slowly changing amplitude called beat.
𝐹
Use 𝑜⁄𝑚 = 12 𝑁/𝑘𝑔, 𝜔𝑛 = 10 𝑟𝑎𝑑/𝑠, and 𝜔 = 12 𝑟𝑎𝑑/𝑠 to plot 𝑥(𝑡) as a function of
𝑡 for 0 ≤ 𝑡 ≤ 10 𝑠.

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

6.7. Review problems


1) A railroad bumper is designed to
slow down a rapidly moving
railroad car. After a 20,000-kg
railroad car traveling at 20 m/s
engages the bumper, its
displacement x (in meters) and
velocity v (in m/s) as a function of
time t (in seconds) is given by:
𝒙(𝒕) = 𝟒. 𝟐𝟏𝟗(𝒆−𝟏.𝟓𝟖𝒕 − 𝒆−𝟔.𝟑𝟐𝒕 )
𝒗(𝒕) = 𝟐𝟔. 𝟔𝟕𝒆−𝟔.𝟑𝟐𝒕 − 𝟔. 𝟔𝟕𝒆−𝟏.𝟓𝟖𝒕
Plot the displacement and the velocity as a function of time for 0 ≤ 𝑡 ≤ 4 s. Make two
plots on one page.

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

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _06_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

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

Figure 43: Relational Operations


7.2.1.1. Array Comparison
If two scalars are compared, the result is a scalar 1 or 0. But if two arrays are compared (only
arrays of the same size can be compared), the comparison is done element-by-element, and the
result is a logical array of the same size with 1s and 0s according to the outcome of the
comparison at each address as shown in Figure 44.

Figure 44: Array Comparison


7.2.1.2. Scalar Comparison with Array
If a scalar is compared with an array, the scalar is compared with every element of the array, and
the result is a logical array with 1s and 0s according to the outcome of the comparison of each
element as shown in Figure 45.
Page 70 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Figure 45: Scalar comparison with array


7.2.2. Logical Operators
A logical operator examines true/false statements and produces a result that is true (1) or false (0)
according to the specific operator. Logical operations have numbers as operands. Any nonzero
number is true, and a zero number is false. The relational operators used in MATLAB are
tabulated in Table 11.
Table 11: Logical Operators

Logical Operators Name Description

Operates on two operands (A


& and B). If both are true, the
AND
Example: A&B result is true (1); otherwise,
the result is false (0).

Operates on two operands (A


| and B). If either one, or both,
OR are true, the result is true (1);
Example: A|B otherwise (both are false) the
result is false (0).

Operates on one operand (A).


~ Gives the opposite of the
NOT operand; true (1) if the
Example: ~A operand is false, and false (0)
if the operand is true.

Page 71 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

7.2.3. Order of Precedence


Logical operators and relational operators are used as:
• Arithmetic operators within a mathematical expression.
• The result can be used in other mathematical operations, in addressing arrays, and
together with other MATLAB commands (e.g., if) to control the flow of a program.
When used in arithmetic operations, the order of operations depends on the order of precedence
which is listed in Table 12.
Table 12: Order of precedence
Precedence Operation
1 (highest) Parentheses (if nested parentheses exist, inner ones have precedence)
2 Exponentiation
3 Logical NOT (~)
4 Multiplication, division
5 Addition, subtraction
6 Relational operators (>, <, >=, <=, = =, ~=)
7 Logical AND (&)
8 (lowest) Logical OR ( | )
7.2.4. Order of Precedence
Other built-in functions used in MATLAB are listed in Table 13.
Table 13: Built-in MATLAB functions
Function Description Example
>> xor(7,0)
ans =
Exclusive or. Returns true (1) if one 1
xor(a,b)
operand is true and the other is false. >> xor(7,-5)
ans =
0
>> A = [6 2 15 9 7 11];
Returns 1 (true) if all elements in a vector >> all(A)
A are true (nonzero). Returns 0 (false) if ans =
one or more elements are false (zero). 1
all(A)
If A is a matrix, treats columns of A as >> B = [6 2 15 9 0 11];
vectors, and returns a vector with 1s and >> all(B)
0s. ans =
0

Page 72 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Table 13: Built-in MATLAB functions (continued)


Function Description Example
>> A = [6 0 15 0 0 11];
Returns 1 (true) if any element in a vector >> any(A)
A is true (nonzero). Returns 0 (false) if all ans =
elements are false (zero). 1
any(A)
If A is a matrix, treats columns of A as >> B = [0 0 0 0 0 0];
vectors, and returns a vector with 1s and >> any(B)
0s. ans =
0
find(A) If A is a vector, returns the indices of the >> A=[0 9 4 3 7 0 0 1 8];
nonzero elements. >> find(A)
ans =
234
589

find(A>d) If A is a vector, returns the address of the >> find(A>4)


elements that are larger than d (any ans =
relational operator can be used). 259
7.3. Conditional Statements
A command that allows MATLAB to make a decision of whether to execute a group of
commands that follow the conditional statement, or to skip these commands. In a conditional
statement, a conditional expression is stated. If the expression is true, a group of commands that
follow the statement are executed. If the expression is false, the computer skips the group.
7.3.1. if-end structure

Figure 46: if-end structure

Page 73 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

7.3.2. if-else-end structure

Figure 47: if-else-end structure


7.3.3. if-elseif-else-end structure

Figure 48: if-elseif-end structure

Page 74 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

7.4. Switch-case Statement


The value of the switch expression in the switch command is compared with the values that are
next to each of the case statements. If a match is found the group of commands that follow the
case statement with the match are executed.

Figure 49: Switch case structure

Page 75 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

7.5. Solved Problems


The tank in a water tower has the geometry shown
in the figure (the lower part is a cylinder and the
upper part is an inverted frustum of a cone). Inside
the tank there is a float that indicates the level of
the water. Write a MATLAB program that
determines the volume of the water in the tank
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 .
Solution
For 𝟎 ≤ 𝒉 ≤ 𝟏𝟗 m, the volume of the water is given by the volume of a cylinder with height h:
𝑽 = 𝝅𝟏𝟐. 𝟓𝟐 𝒉.
For 𝟏𝟗 ≤ 𝒉 ≤ 𝟑𝟑 m, the volume of the water is given by adding the volume of a cylinder with
𝒉 = 𝟏𝟗 𝒎, and the volume of the water in the cone:
𝟏
𝑽 = 𝝅𝟏𝟐. 𝟓𝟐 𝒉 + 𝝅(𝒉 − 𝟏𝟗)(𝟏𝟐. 𝟓𝟐 + 𝟏𝟐. 𝟓𝒓𝒉 + 𝒓𝒉 𝟐 )
𝟑
where,
𝟏𝟎. 𝟓
𝒓𝒉 = 𝟏𝟐. 𝟓 + (𝒉 − 𝟏𝟗)
𝟏𝟒

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

7.6. Review Problems


1) Write a program in a script file that determines the real roots of a quadratic equation
𝒂𝒙𝟐 + 𝒃𝒙 + 𝒄 = 𝟎. Name the file quadroots. When the file runs, it asks the user to enter
the values of constants a, b, and c. To calculate the roots of the equation the program
calculates the discriminant (D), given by,
𝑫 = 𝒃𝟐 − 𝟒𝒂𝒄
If 𝑫 > 𝟎, the program displays the message “The equation has two roots.”, and the
roots are displayed in the next line.
If 𝑫 = 𝟎, the program displays the message “The equation has one roots.”, and the root
are displayed in the next line.
If 𝑫 < 𝟎, the program displays the message “The equation has no real roots.”
Run the script file in the command window three times to obtain solutions to the
following three equations:
a) 𝟐𝒙𝟐 + 𝟖𝒙 + 𝟖 = 𝟎
b) −𝟓𝒙𝟐 + 𝟑𝒙 + 𝟒 = 𝟎
c) −𝟐𝒙𝟐 + 𝟕𝒙 + 𝟒 = 𝟎
2) The following are formulas for calculating the training heart rate (THR) for men and
women:
For men (Karvonen formula): 𝑻𝑯𝑹 = [(𝟐𝟐𝟎 − 𝑨𝑮𝑬) − 𝑹𝑯𝑹] × 𝑰𝑵𝑻𝑬𝑵 + 𝑹𝑯𝑹
For women: 𝑻𝑯𝑹 = [(𝟐𝟎𝟔 − 𝟎. 𝟖𝟖 × 𝑨𝑮𝑬) − 𝑹𝑯𝑹] × 𝑰𝑵𝑻𝑬𝑵 + 𝑹𝑯𝑹
where AGE is the person's age, RHR the resting heart rate, and INTEN the fitness level
(0.55 for low, 0.65 for medium, and 0.8 for high fitness). Write a program in a script file
that determines the THR. The program asks users to enter their gender (male or female),
age (number), resting heart rate (number), and fitness level (low, medium, or high). The
program then displays the training heart rate. Use the program for determining the
training heart rate for the following two individuals:
a) A 21-year -old male, resting heart rate of 62, and low fitness level.
b) A 19-year-old female, resting heart rate of 67, and high fitness level.

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

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _07_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

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 𝟏, 𝟑, 𝟓, 𝟕, 𝒂𝒏𝒅 𝟗.

Figure 50: Structure of a for-end loop


The value of k should not be redefined within the loop. Each for command in a program must
have an end command. The value of the loop index variable (k) is not displayed automatically. It
is possible to display the value in each pass (which is sometimes useful for debugging) by typing
k as one of the commands in the loop.

Page 82 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

8.3. while-end loop


while-end loops are used in situations when looping is needed but the number of passes is not
known in advance. In while-end loops the number of passes is not specified when the looping
process starts. Instead, the looping process continues until a stated condition is satisfied. Figure
51 shows the structure of a while-end loop.

Figure 51: Structure of a while-end loop


The first line is a while statement that includes a conditional expression. When the program
reaches this line the conditional expression is checked. If it is false (0), MATLAB skips to the
end statement and continues with the program. If the conditional expression is true (1),
MATLAB executes the group of commands that follow between the while and end commands.
Then MATLAB jumps back to the while command and checks the conditional expression. This
looping process continues until the conditional expression is false.
For a while-end loop to execute properly:
1) The conditional expression in the while command must include at least one variable.
2) The variables in the conditional expression must have assigned values when MATLAB
executes the while command for the first time.
3) At least one of the variables in the conditional expression must be assigned a new value
in the commands that are between the while and the end. Otherwise, once the looping
starts it will never stop since the conditional expression will remain true.
8.4. Nested loop
Loops and conditional statements can be nested within other loops or conditional statements.
This means that a loop and/or a conditional statement can start (and end) within another loop or
conditional statement. There is no limit to the number of loops and conditional statements that
can be nested. It must be remembered, however, that each if, case, for, and while statement must
have a corresponding end statement. Figure 52 shows the structure of the nested loop.

Page 83 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Figure 52: Structure of nested loop


8.5. The break and continue commands
8.5.1. The break command
The break command terminates the execution (for & while) of the loop (the whole loop, not just
the last pass). When the break command appears in a loop, MATLAB jumps to the end
command of the loop and continues with the next command (it does not go back to the for
command of that loop). If the break command is inside a nested loop, only the nested loop is
terminated. When a break command appears outside a loop in a script or function file, it
terminates the execution of the file.
8.5.2. The continue command
The continue command can be used inside a loop (for or while) to stop the present pass and start
the next pass in the looping process. The continue command is usually a part of a conditional
statement. When MATLAB reaches the continue command, it does not execute the remaining
commands in the loop, but skips to the end command of the loop and then starts a new pass.

8.6. Solved Problems


The flight of a model rocket can be modeled as follows. During the first
0.15s the rocket is propelled upward by the rocket engine with a force of
16 N. The rocket then flies up while slowing down under the force of
gravity. After it reaches the apex, the rocket starts to fall back down.
When its downward velocity reaches 20 m/s a parachute opens
(assumed to open instantly), and the rocket continues to drop at a
constant speed of 20 m/s until it hits the ground. Write a program that
calculates and plots the speed and altitude of the rocket as a function of
time during the flight.
Solution

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

8.7. Review Problems


1) A vector is given by
𝑽 = [𝟓, 𝟏𝟕, – 𝟑, 𝟖, 𝟎, – 𝟕, 𝟏𝟐, 𝟏𝟓, 𝟐𝟎, – 𝟔, 𝟔, 𝟒, – 𝟕, 𝟏𝟔]
Write a program as a script file that:
a) doubles the elements that are positive and are divisible by 3 or 5, and
b) Raises to the power of 3 the elements that are negative but greater than –5.

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

5) Write a program (using a loop) that determines the expression:


𝒎
(𝟐𝒏)𝟐 𝟒 𝟏𝟔 𝟑𝟔
𝟐∏ 𝟐
= 𝟐( . . .…)
(𝟐𝒏) − 𝟏 𝟑 𝟏𝟓 𝟑𝟓
𝒏=𝟏

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

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _08_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

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:

9.2. Creating a Function file


Function files are created and edited, like script files, in the Editor/Debugger Window. This
window is opened from the Command Window. In the Toolstrip select New, then select
Function.

Page 90 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

Figure 53: Creating a function file


9.3. Structure a Function file
The structure of a typical complete function file is shown in Figure 54.

Figure 54: Structure of a function


The various parts of the function file are described in detail in the following sections.

Page 91 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

9.3.1. Function Definition Line


The first executable line in a function file must be the function definition line. Otherwise, the file
is considered a script file. The function definition line:
• Defines the file as a function file: The word “function,” typed in lowercase letters, must
be the first word
• Defines the name of the function: The name can be made up of letters, digits, and the
underscore character (the name cannot include a space). The rules for the name are the
same as the rules for naming variables It is good practice to avoid names of built-in
functions and names of variables already defined by the user or predefined by MAT-
LAB.
• Defines the number and order of the input and output arguments The form of the function
definition line is

9.3.2. Input and Output Arguments


The input and output arguments are used to transfer data into and out of the function. The input
arguments are listed inside parentheses following the function name. Usually, there is at least one
input argument, although it is possible to have a function that has no input arguments. If there are
more than one, the input arguments are separated with commas. The computer code that
performs the calculations within the function file is written in terms of the input arguments and
assumes that the arguments have assigned numerical values. This means that the mathematical
expressions in the function file must be written according to the dimensions of the arguments,
since the arguments can be scalars, vectors, or arrays.
The output arguments, which are listed inside brackets on the left side of the assignment operator
in the function definition line, transfer the output from the function file. Function files can have
zero, one, or several output arguments. If there are more than one, the output arguments are
separated with commas. If there is only one output argument, it can be typed without brackets.
For the function file to work, the output arguments must be assigned values in the computer
program that is in the function body.
The following are examples of function definition lines with different combinations of input and
output arguments.

Page 92 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

9.3.3. The H1 line and help text lines


The H1 line and help text lines are comment lines following the function definition line. They
are optional but are frequently used to provide information about the function. The H1 line is the
first comment line and usually contains the name and a short definition of the function. When a
user types (in the Command Window) lookfor a_word, MATLAB searches for a_word in the H1
lines of all the functions, and if a match is found, the H1 line that contains the match is
displayed.
The help text lines are comment lines that follow the H1 line. These lines contain an explanation
of the function and any instructions related to the input and output arguments. The comment
lines that are typed between the function definition line and the first non-comment line (the H1
line and the help text) are displayed when the user types help function_name in the Command
window.
A function file can include additional comment lines in the function body. These lines are
ignored by the help command.
9.3.4. Function body
The function body contains the computer program (code) that actually performs the
computations. The code can use all MATLAB programming features. This includes calculations,
assignments, any built-in or user-defined functions, flow control (conditional statements and
loops), comments, blank lines, and interactive input and output.
Each function file has its own local variables, which are not shared with other functions or with
the workspace of the Command Window and the script files.
9.4. Saving a Function file
A function file must be saved before it can be used. This is done, as with a script file, by
choosing Save as . . . from the File menu, selecting a location and entering the file name. It is

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

9.7. Solved Problem


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. Use the function X to calculate the trajectory of a projectile that is fired at a velocity
of 230 m/s at an angle of 39°.

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

9.8. Review Problems


1) A two-dimensional state of stress at a point in a loaded
material is defined by three components of stress
𝝈𝒙𝒙 , 𝝈𝒚𝒚 , 𝑎𝑛𝑑 𝝉𝒙𝒚 . The maximum and minimum normal
stresses (principal stresses) at the point, 𝝈𝒎𝒂𝒙 and 𝝈𝒎𝒊𝒏 , are
calculated from the stress components by:

𝝈𝒙𝒙 + 𝝈𝒚𝒚 𝝈𝒙𝒙 − 𝝈𝒚𝒚 𝟐


𝝈𝒎𝒂𝒙 = ± √( ) + 𝝉𝒙𝒚 𝟐
𝟐 𝟐

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

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _09_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

Page 100 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.

10.2. Determining a value of the polynomial


The value of a polynomial at a point x can be calculated with the function polyval that has the
form:

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:

Page 101 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

10.4. Finding polynomial using its roots


When the roots of a polynomial are known, the poly command can be used for determining the
coefficients of the polynomial. The form of the poly command is:

10.5. Mathematical operations with polynomials


10.5.1. Addition and Subtraction
Two polynomials can be added (or subtracted) by adding (subtracting) the vectors of the
coefficients. If the polynomials are not of the same order (which means that the vectors of the
coefficients are not of the same length), the shorter vector has to be modified to be of the same
length as the longer vector by adding zeros (called padding) in front.
For example, the polynomials that are to be added together are:
𝒇𝟏 (𝒙) = 𝟑𝒙𝟔 + 𝟏𝟓𝒙𝟓 − 𝟏𝟎𝒙𝟑 − 𝟑𝒙𝟐 + 𝟏𝟓𝒙 − 𝟒𝟎
𝒇𝟐 (𝒙) = 𝟑𝒙𝟑 − 𝟐𝒙 − 𝟔
The polynomial representation of first and second function in MATLAB is written as p1 and p2
respectively. Before addition, however, p2 will be padded in order to make the number of
elements in p1 and p2 same.

10.5.2. Multiplication
Two polynomials can be multiplied using the MATLAB built-in function conv, which has the
form:

Page 102 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

• The two polynomials do not have to be of the same order.


• Multiplication of three or more polynomials is done by using the conv function
repeatedly.
10.5.3. Division
A polynomial can be divided by another polynomial with the MATLAB built-in function
deconv, which has the form:

10.5.4. Derivatives of Polynomial


The built-in function polyder can be used to calculate the derivative of a single polynomial, a
product of two polynomials, or a quotient of two polynomials, as shown in the following three
commands.
Derivative of a single polynomial. p is a vector with the coefficients of
k = polyder(p) the polynomial. k is a vector with the coefficients of the polynomial that
is the derivative.
Derivative of a product of two polynomials. a and b are vectors with the
k = polyder(a,b) coefficients of the polynomials that are multiplied. k is a vector with the
coefficients of the polynomial that is the derivative of the product
Derivative of a quotient of two polynomials. u and v are vectors with the
coefficients of the numerator and denominator polynomials. n and d are
[n, d] = polyder(u,v)
vectors with the coefficients of the numerator and denominator
polynomials in the quotient that is the derivative.
The only difference between the last two commands is the number of output arguments. With
two output arguments MATLAB calculates the derivative of the quotient of two polynomials.
With one output argument, the derivative is of the product.

Page 103 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

10.6. Finding Minima and Maxima of a Function


In many applications there is a need to determine the local minimum or maximum of a function
of the form 𝑦 = 𝑓(𝑥). In calculus the value of x that corresponds to a local minimum or
maximum is determined by finding the zero of the derivatives of the function. The value of y is
determined by substituting the x into the function. In MATLAB the value of x where a one-
variable function 𝑓(𝑥) with the interval 𝑥1 ≤ 𝑥 ≤ 𝑥2 has a minimum can be determined with the
fminbnd command 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.

Page 104 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

10.7. Solved Problem


One fine day on an unused airport runway, a high-end sports car conducted a performance test. A
car's position is described by the following polynomial for 0 to 10 s.
𝒔 = 𝒕𝟑 − 𝟏𝟓𝒕𝟐 + 𝟓𝟒𝒕
where s is in meters, t is in seconds, and positive is forward. Determine the following using
MATLAB.
a) Make a displacement vs time curve
b) The car's velocity as a function of time and make a velocity vs time curve
c) The car's acceleration as a function of time and make a acceleration vs time curve
d) The car's minimum velocity
e) The car's maximum velocity

Page 105 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

Page 106 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

10.8. Review Problems


1) Write a user-defined function that adds or subtracts two polynomials of any order. Name
the function p=polyadd(p1,p2,operation). The first two input arguments p1 and p2 are
the vectors of the coefficients of the two polynomials. (If the two polynomials are not of
the same order, the function adds the necessary zero elements to the shorter vector.) The
third input argument operation is a string that can be either ‘add’ or ‘sub’, for adding or
subtracting the polynomials, respectively, and the output argument is the resulting
polynomial. Use the function to add and subtract the following polynomials: 𝒇𝟏 (𝒙) =
𝟖𝒙𝟔 + 𝟏𝟎𝒙𝟓 − 𝟓𝒙𝟑 + 𝟏𝟑𝒙𝟐 − 𝟒𝒙 − 𝟐 and 𝒇𝟐 (𝒙) = 𝟒𝒙𝟒 + 𝟕𝒙𝟐 + 𝟔.

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

Page 107 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

to multiply the following polynomials: 𝒇𝟏 (𝒙) = −𝟐𝒙𝟔 + 𝟑𝒙𝟒 + 𝟒𝒙𝟑 − 𝟕𝒙 + 𝟖 and


𝒇𝟐 (𝒙) = 𝟓𝒙𝟒 − 𝟒𝒙𝟐 + 𝟑𝒙 − 𝟓. Check the answer with MATLAB’s built-in function
conv.

3) A cone with base radius (r) and vertex in contact


with the surface of a sphere is constructed inside
a sphere, as shown in the figure. The radius of
the sphere is 𝑅 = 9 𝑖𝑛.
a) Create a polynomial expression for the
volume (V) of the cone in terms of h.
b) Make a plot of V versus h for 𝟗 ≤ 𝒉 ≤
−𝟗.
c) Using the roots command determine h if
the volume of the cone is 500 in3.
d) Determine the value of h that
corresponds to the cone with the largest
possible volume, and determine that
volume.

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.

Page 108 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _10_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

Page 109 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

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.

Page 110 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

Table 14: Polynomial representation of different functions in the linear form

Function General Equation Linear Form polyfit function form

Power 𝑦 = 𝑏𝑥 𝑚 𝑙𝑛𝑦 = 𝑚𝑙𝑛𝑥 + 𝑙𝑛𝑏 𝒑 = 𝒑𝒐𝒍𝒚𝒇𝒊𝒕(𝒍𝒐𝒈(𝒙), 𝒍𝒐𝒈(𝒚). 𝟏)

𝑦 = 𝑏𝑒 𝑚𝑥 𝑙𝑛𝑦 = 𝑚𝑥 + 𝑙𝑛𝑏 𝒑 = 𝒑𝒐𝒍𝒚𝒇𝒊𝒕(𝒙, 𝒍𝒐𝒈(𝒚). 𝟏)


Exponential 𝑚𝑥
𝑦 = 𝑏10 𝑙𝑜𝑔𝑦 = 𝑚𝑥 + 𝑙𝑜𝑔𝑏 𝒑 = 𝒑𝒐𝒍𝒚𝒇𝒊𝒕(𝒙, 𝒍𝒐𝒈𝟏𝟎(𝒚). 𝟏)

𝑦 = 𝑚𝑙𝑛𝑥 + 𝑏 𝑦 = 𝑚𝑙𝑛𝑥 + 𝑏 𝒑 = 𝒑𝒐𝒍𝒚𝒇𝒊𝒕(𝒍𝒐𝒈(𝒙), 𝒚. 𝟏)


Logarithmic
𝑦 = 𝑚𝑙𝑜𝑔𝑥 + 𝑏 𝑦 = 𝑚𝑙𝑜𝑔𝑥 + 𝑏 𝒑 = 𝒑𝒐𝒍𝒚𝒇𝒊𝒕(𝒍𝒐𝒈𝟏𝟎(𝒙), 𝒚. 𝟏)

1 1
Reciprocal 𝑦= = 𝑚𝑥 + 𝑏 𝒑 = 𝒑𝒐𝒍𝒚𝒇𝒊𝒕(𝒙, 𝟏./𝒚. 𝟏)
𝑚𝑥 + 𝑏 𝑦

Table 15: Coefficients m and b for functions other than polynomial

Function Linear Form polyfit function form Coefficients

𝒎 = 𝒑(𝟏)
Power 𝑙𝑛𝑦 = 𝑚𝑙𝑛𝑥 + 𝑙𝑛𝑏 𝑝 = 𝑝𝑜𝑙𝑦𝑓𝑖𝑡(𝑙𝑜𝑔(𝑥), 𝑙𝑜𝑔(𝑦).1)
𝒃 = 𝒆𝒙𝒑(𝒑(𝟐))

𝑙𝑛𝑦 = 𝑚𝑥 + 𝑙𝑛𝑏 𝑝 = 𝑝𝑜𝑙𝑦𝑓𝑖𝑡(𝑥, 𝑙𝑜𝑔(𝑦).1) 𝒎 = 𝒑(𝟏)


Exponential
𝑙𝑜𝑔𝑦 = 𝑚𝑥 + 𝑙𝑜𝑔𝑏 𝑝 = 𝑝𝑜𝑙𝑦𝑓𝑖𝑡(𝑥, 𝑙𝑜𝑔10(𝑦).1) 𝒃 = 𝒆𝒙𝒑(𝒑(𝟐))

𝑦 = 𝑚𝑙𝑛𝑥 + 𝑏 𝑝 = 𝑝𝑜𝑙𝑦𝑓𝑖𝑡(𝑙𝑜𝑔(𝑥), 𝑦. 1) 𝒎 = 𝒑(𝟏)


Logarithmic
𝑦 = 𝑚𝑙𝑜𝑔𝑥 + 𝑏 𝑝 = 𝑝𝑜𝑙𝑦𝑓𝑖𝑡(𝑙𝑜𝑔10(𝑥), 𝑦. 1) 𝒃 = 𝒑(𝟐)

1 𝒎 = 𝒑(𝟏)
Reciprocal = 𝑚𝑥 + 𝑏 𝑝 = 𝑝𝑜𝑙𝑦𝑓𝑖𝑡(𝑥, 1./𝑦. 1)
𝑦 𝒃 = 𝒑(𝟐)

Considerations in choosing a function that best fits the data:


• Exponential functions cannot pass through the origin.
• Exponential functions can fit only data with all positive y’s or all negative y’s.
• Logarithmic functions cannot model x = 0 or negative values of x.
• For the power function y = 0 when x = 0.
• The reciprocal equation cannot model y = 0.

Page 111 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

11.4. Solved Problem


The following data points are given. Determine a function 𝒘 = 𝒇(𝒕) (t is the independent
variable, w is the dependent variable).

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.

Step 2: Choose a suitable function


• Linear function: w vs t does not seem to be linear, hence linear function will not be
considered.
• Since Logarithmic functions cannot model x = 0, logarithmic function is disregarded.
• For the power function, y = 0 when x = 0, so power function is also disregarded.
Functions that are considered
• Exponential function:
➢ Because the w vs t graph does not pass through the origin.
➢ Data contains all positive y’s.
• Reciprocal equation

Page 112 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

Step 3: plotting of linear forms of the selected function

Functions x-axis y-axis

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

Step 5: Determining the coefficients m and b to determine the function 𝒘 = 𝒇(𝒕)

Page 113 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

Thus, the determined function is,


𝑦 = 𝑏𝑒 𝑚𝑥
𝒚 = 𝟓. 𝟗𝟖𝟖𝟗𝒆−𝟎.𝟒𝟓𝟖𝒙
Step 6: Plotting the scatter plot (of the points given in the question) + equation of the curve
obtained in step 5

Page 114 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

Page 115 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

11.5. Review Problems


1) Viscosity (𝜇) is a property of gases and fluids that characterizes their resistance to flow.
For most materials, viscosity is highly sensitive to temperature. Below is a table that
gives the viscosity of SAE 10W oil at different temperatures (data from B.R. Munson,
D.F. Young, and T.H. Okiishi, Fundamentals of Fluid Mechanics, 4th ed., John Wiley
and Sons, 2002).
a) Determine an equation that can be fitted to the data on 𝐥𝐧(𝒚) = 𝒂𝑻𝟐 + 𝒃𝑻 + 𝒄
b) Use the equation to estimate the viscosity at 150 ℃.
c) Make a plot of the actual data points and the equation on a single graph.

𝑻 (℃) -20 0 20 40 60 80 100 120

𝝁 (𝑵𝒔𝒎𝟐 )
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.

𝒉 (𝒇𝒕) -1000 0 3000 8000 15000 22000 28000

𝑻 (℉) 213.9 212 206.2 196.2 184.4 172.6 163.1

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

𝑵𝑩 500 600 1000 1400 2100 2700 4100

4) Measurements of the concentration, C, of a substance during a chemical reaction at


different times t are shown in the table. Suppose that the data can be modeled with an
equation in the form:
𝟏
𝑪=
𝒂𝟐 𝒕𝟐 + 𝒂𝟏 𝒕 + 𝒂𝒐
Page 116 of 118
ME-214 Computer Programming and Applications Department of Mechanical Engineering

The data is given in table below.


t (h) 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0
C (g/L) 1.7 3.1 5.7 9.1 6.4 3.7 2.8 1.6 1.2 0.8 0.7 0.6
a) Determine the coefficients 𝑎0 , 𝑎1 , and 𝑎2 such that the equation best fits the data.
b) Once the coefficients 𝑎0 , 𝑎1 , and 𝑎2 are determined, write an equation for C.
c) Use the equation to estimate the concentration at 𝑡 = 2ℎ.
d) Make a plot of the data points and the equation.

Page 117 of 118


ME-214 Computer Programming and Applications Department of Mechanical Engineering

Course Code: ME-214 Course Title: Computer Programming and Applications


Practical No. _11_
Assessment Rubric for Lab Performance (P3)
S. Skill Performance Level
No.
Excellent (4) Good (3) Fair (2) Poor (0)
1 Identification and Uses software Often uses Rarely uses software Cannot use
usage of correct of menus correctly software menus menus correctly. software menus
software menus and effectively. correctly. correctly.
2 Readiness to Displays high Displays Follows the practical Unable to
assimilate the degree of motivation to procedures, but understand and
procedures required motivation to follow the displays deviations act upon the
to conduct the
follow the practical occasionally. requisite
practical.
practical procedures, most practical
procedures. of the times. procedures.
3 Skills to use basic and Exhibits full use Uses advanced Uses basic command Not able to use
advanced commands of all commands. commands and not able to use any commands.
without help. advanced commands.
4 Identify required Very good Good command to Few aspects are taken Not aware of
variables command to identify variable. but left important what necessary
identify each variables. parameters are
variable and its required
contribution in
load calculations.
5 Group activity. Active Participation with Participation but Lacks team work
participation and good team work requires instruction do skills.
strong team work skills. engage in team work.
skills.

Marks: ___________ Instructor’s Signature: ___________________ Date: _______________

Page 118 of 118

You might also like