0% found this document useful (0 votes)
14 views139 pages

Mech 251 Slides

Uploaded by

willfri2001
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)
14 views139 pages

Mech 251 Slides

Uploaded by

willfri2001
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/ 139

MECH 251: INTRODUCTION TO ENGINEERING

COMPUTATIONS

D. M. Ashigbi

Mechanical and Manufacturing Engineering Department


University of Energy and Natural Resources, Sunyani

January 28, 2025

1 / 139
Course Objective
To introduce students to available computational tools and equip them
with computer programming skills for engineering problem solving.

Principal Learning Outcomes


On completion of this course, students should be able to:
1 Solve a given computational problem within Octave/MATLAB®
environments and/or with Microsoft Excel spreadsheet.
2 Understand and apply computer program flow control and data
structures to construct simple programs.
3 Apply testing and debugging techniques to identify and correct errors
in programs.

2 / 139
Content
Introduction to computers, programming language and associated
problem-solving skills; The elements of a computer programming language
including variable types, assignment statements, library functions, control
structures, functions and procedures, arrays and formatting; Introduction
to using Excel for engineering computations: fitting curves to experimental
measurements, creating publication-quality graphs, solving equations,
Excel and user-defined functions, selected topics on programming Excel for
numerical analysis and statistics; Introduction to forms, controls and basic
elements of a Graphics User Interface; Basic MATLAB commands, Arrays:
one-dimensional and multi-dimensional, Flow control, Selective execution,
Repetitive execution and iterations, Input and Output, Modular
Programming: Functions, Plotting, and Advanced data types.

3 / 139
Prerequisites
None

Assessment
Assignments - 13%, MATLAB Onramp - 13%
Mid-Semester Examination, Quizzes - 14%
Final Examination - 60%

References
S. Attaway, MATLAB a practical introduction to programming and problem
solving, 5th ed. Butterworth-Heinemann, 2019.
J. C. Musto, W. E. Howard, and R. R. Williams, Engineering computations :
An Introduction Using MATLAB and excel, McGraw-Hill Higher Education,
2009.
William Palm, MATLAB for Engineering Applications, 4th ed. McGraw-Hill
Higher Education, 2019.

4 / 139
Policies
All submissions will be identified and credited to index number(s).
Donot write your names.
The penalty for late submission is a reduction by 10% of the
maximum mark applicable for the assignment, for each university
business day or part business day that the assignment is late.
Saturdays, Sundays and holidays are excluded from the reckoning.
You may collaborate on assignments, but you are expected to write
your own work. Two or more exact submissions will not be accepted.

Note
Acquiring suffiecient knowledge and usage of computer programming
concepts takes time and effort. There is nothing clever about it.
Determination, hard-work and consistent hands-on practice is the only
way; as in most things.

5 / 139
OUTLINE

1 Introduction

2 Working with MATLAB/Octave


Environment and Commands Overview
Numeric Arrays
Plotting
Program flow control structures
Functions
Add-on packages and toolboxes

3 Working with Excel

4 Engineering Problem Solving

6 / 139
Introduction

Engineering profession is a discipline devoted to problem solving,


applying principles of mathematics and science to develop solutions to
practical problems
Software Helps Engineers Do Their Jobs
I Design:
I Compute and visualize:
F Spreadsheets: MS excel2 , LibreOffice Calc1
F Computational tools: GNU Octave1 , MATLAB2 , Scilab1 ,
Mathematica2 etc.
I Report: MS word2 , LibreOffice Writer1 , Latex1
I Present information: MS powerpoint2 , LibreOffice Impress1
Computer programming:
I Useful for repetitive calculations
I Implementing your own solution to problems and accessing a hardware
I Programming languages such as C/C++, python, Java etc.

1 Free and open-source software


2 Propriety software
7 / 139
Introduction

Computational tools

For this course we will focus mainly on:


I MATLAB (a portmanteau of matrix laboratory)
F Product of MathWorks, Inc.
F Widely used by engineers and scientists
F Combines a calculator-type interactive mode and powerful
programming tools
I GNU Octave: free and open-source alternative to MATLAB.
F 99% similar to MATLAB (syntax and function compatibility)
I Microsoft Excel:
F Spreadsheet application of Microsoft Office
F Contains many commands and features that are useful for engineering
computations
F A limited free version can be access online with a microsoft account

8 / 139
Introduction

Programming Language Background


Abstraction: expressing a quality apart from a particular
implementation. We use the concept of abstraction in everyday
conversation without thinking about it:
I “To convert from degrees Celsius to Kelvin, you add 273 to the
temperature .
I “He drove home from the office.
Data abstraction: “The temperature could mean a single reading
from the thermometer hanging outside this room or a table of
temperature readings for the month of January. The specifics are
unimportant; the phrase captures all you need to know.
Procedural abstraction: To a person taking the same route home
every night, “drive home is all that is required to understand the idea.
To a competent driver unfamiliar with the route, the next level of
abstraction might be necessary turn right out of the parking lot, left
onto Main Street, and so on.

9 / 139
Introduction

... Programming Language Background


For instructions to guide a self-driving vehicle, an incredibly
fine-grained level of abstraction will be required.
I start the engine, accelerate the vehicle, look out for traffic, keep in the
lane, find the turn, steer the vehicle, control the speed, observe and
obey all signs, and so on.
Algorithms: a well-defined step-by-step solution or a series of
instructions to solve a problem. The solution to a problem or
solutions to each sub-problem would be expressed at lower and lower
levels of abstraction until the description is sufficient to write
programs that solve the problem, thereby contributing the pieces that,
when assembled, solve the whole problem.
An algorithm must clearly show the order in which instructions are
carried out and where decisions are made or sections repeated.
A computer program is an implementation of an algorithm - an
algorithm is not a computer program!
10 / 139
Introduction

Problem-Solving Skills and algorithm creation

If we think about a computer program as a logical component that


consumes data in one form (as inputs) and produces data in another
(as output), we can think about problem solving as the process of
designing a collection of solutions to sub-problems.

Algorithms can be created using flowcharts, pseudo-code or


program code.

11 / 139
Introduction

... Problem-Solving Skills and algorithm creation

Pseudo-code is a textual representation of an algorithm.


A flowchart is a graphical representation of an algorithm. It can be
followed from top to bottom, making decisions as appropriate.
Program code is code that is written in a high-level language.
A flowchart may use any of the following symbols:

12 / 139
Introduction

.. Problem-Solving Skills and algorithm creation


As an example, the algorithm in the flowchart and pseudo-code below
will decide whether a positive number entered is odd or even using
repeated subtraction.

13 / 139
Working with MATLAB/Octave Environment and Commands Overview

MATLAB Desktop default windows

14 / 139
Working with MATLAB/Octave Environment and Commands Overview

MATLAB Mobile windows

15 / 139
Working with MATLAB/Octave Environment and Commands Overview

GNU Octave Desktop Default window

16 / 139
Working with MATLAB/Octave Environment and Commands Overview

Octave Online

17 / 139
Working with MATLAB/Octave Environment and Commands Overview

Entering Commands and Expressions (command window)

Use the up/down arrow keys to scroll through the previous commands.
Use the left/right arrow keys to position cursor for editing

18 / 139
Working with MATLAB/Octave Environment and Commands Overview

Naming variables & assigning values

MATLAB variable name must start with a letter and contain only
letters, numbers, and underscores
I To create a variable, assign a value to a name (using =)
I Example: y1 = 2
MATLAB variables are case sensitive.
I x1 is different from X1
I x_1 is different from X_1
Builtin variables and constants

I i , j: used to indicate complex number −1
I pi: the number π, has the value 3.1415...
I ans: stores the result of the last unassigned value
I Inf: infinity
I eps: Specifies the accuracy of floating point precision.
I NaN: ”Not a Number”, indicates an undefine numerical results

19 / 139
Working with MATLAB/Octave Environment and Commands Overview

... Naming variables & assigning values

>> x = 2
x = 2
>> strg = "Octave"
>> x_1 = 5
strg = Octave
x_1 = 5
>> C = 'Hello, world'
>> X_1 = 5
C = Hello, world
X_1 = 5
>> y = 33;

Take note of the attributes of


the variables in the workspace
I Value
I Class (type of data stored in
the variable, i.e. data type)
I Size (i.e. dimension)

20 / 139
Working with MATLAB/Octave Environment and Commands Overview

Data Types (Classes)

MATLAB/Octave refers to the type of data in a variable as its class,


and the value contained in the variable at any time as an object, an
instance of that class.
double is the default numeric data type (class)
I When a real number is entered as the value of a variable,
MATLAB/Octave automatically sets the variable to be real (double).
char and string are sequence of characters. A typical use is to store a
short piece of text.
Several other data types will be shown later

21 / 139
Working with MATLAB/Octave Environment and Commands Overview

Scalar arithmetic operations

22 / 139
Working with MATLAB/Octave Environment and Commands Overview

Order of precedence

23 / 139
Working with MATLAB/Octave Environment and Commands Overview

Examples of scalar operations

Mathematical expression MATLAB expression

1 − dc x+2 1-d*c^(x+2)

dc x + 2 d*c^x+2 or 2+d*c^x
 
2
c x+2 (2/d)*c^(x+2) or 2/d*c^(x+2) or 2*c^(x+2)
d
dc x + 2
(d*c^x+2)/g^2.7
g 2.7

dc x + 2 sqrt(d*c^x+2) or (d*c^x+2)^0.5

24 / 139
Working with MATLAB/Octave Environment and Commands Overview

MATLAB SESSION

>> 8 + 3*5 >> 3*4^2 + 5


ans = ans =
23 53
>> 8 + (3*5) >>(3*4)^2 + 5
ans = ans =
23 149
>>(8 + 3)*5 >>27^(1/3) + 32^(0.2)
ans = ans =
55 5
>>4^2128/4*2 >>27^(1/3) + 32^0.2
ans = ans =
0 5
>>4^212 8/(4*2) >>27^1/3 + 32^0.2
ans = ans =
3 11
25 / 139
Working with MATLAB/Octave Environment and Commands Overview

Commands for managing the work session

26 / 139
Working with MATLAB/Octave Environment and Commands Overview

Example 1
The volume of a circular cylinder of height h and radius r is given by
V = πr 2 h. Aparticular cylindrical tank is 15 m tall and has a radius of 8
m. We want to construct another cylindrical tank with a volume 20
percent greater but having the same height. How large must its radius be?
Solution r
V
r=
πh

>>r = 8;
>>h = 15;
>>V = pi*r^2*h;
>>V = V + 0.2*V;
>>r = sqrt(V/(pi*h))
r =
8.7636
27 / 139
Working with MATLAB/Octave Environment and Commands Overview

Complex Number Operations


The number c1 = 1 − 2i is entered as follows: c1 = 1 - 2i
An asterisk is not needed between i or j and a number, although it is
required with a variable, such as c2 = 5i*c1
Caution! The expressions
y = 7/2*i
and
x = 7/2i
give two different results:

>> y = (7/2)*i
y =
0.0000 + 3.5000i
>> x = 7/(2i)
x =
0.0000 - 3.5000i

28 / 139
Working with MATLAB/Octave Environment and Commands Overview

... Complex Number Operations

29 / 139
Working with MATLAB/Octave Environment and Commands Overview

Output Formatting Commands

30 / 139
Working with MATLAB/Octave Environment and Commands Overview

Mathematical Functions

31 / 139
Working with MATLAB/Octave Environment and Commands Overview

Trigonometric and Hyperbolic Functions

32 / 139
Working with MATLAB/Octave Environment and Commands Overview

Exercise
1 Suppose that x = 2 and y = −1. Evaluate the following expressions
using Octave/MATLAB to 16 significant digits

4
a
p 2x 3
4
b 2y 3
2 In an open channel of circular cross-section shown below, the flow
rate Q in m3 /s is given by:
5/2 √
23/2 Dc g (θ − 0.5 sin(2θ ))3/2
Q= √
8 sin θ (1 − cos θ )5/2

Where g = 9.8 m/s 2 is the gravitational constant and Dc is given by


d
Dc = (1 − cos θ )
2
°
Assuming d = 2 m and θ = 60 = π3 , calculate the flow rate Q

33 / 139
Working with MATLAB/Octave Environment and Commands Overview

Getting help

Type doc followed by a function name in the Command Window


Search command/function-name/keyword in documentation; offline
or online
Type help followed by a function name in the Command Window

34 / 139
Working with MATLAB/Octave Environment and Commands Overview

Script Files

Interactive mode, in which all commands are entered directly in the


Command window
In addition running a MATLAB program stored in script file with .m
extension
allows the user to create his/her own customized m-files for specific
applications or problems.
This type of file contains MATLAB commands, so running it is
equivalent to typing all the commands—one at a time—at the
Command window prompt.
All of the pre-built commands that you use in MATLAB are script files

35 / 139
Working with MATLAB/Octave Environment and Commands Overview

Script file: Procedure

Type a set of executable commands in the editor window.


Save the file in an appropriate folder. When you pick a name for the
file you must follow the same rules that MATLAB has for naming
variables.
Set the current directory in MATLAB to the same place where you
saved the script file.
To run the script file: Hit the Green Run Arrow in the Editor window
or simply type the name of the file (without the .m extension) at the
command prompt in the MATLAB command window.

36 / 139
Working with MATLAB/Octave Environment and Commands Overview

Example 2
Convertion of example 1 into a script file
1 On home menu tab, new −− > Script, then save
OR
2 At command terminal type edit filename
A new script file opens and named ”filename”.m and save at
ccurrent working directory. Type in it

1 r = 8;
2 h = 15;
3 V = pi*r^2*h;
4 V = V + 0.2*V;
5 r = sqrt(V/(pi*h))

3 On the editor menu tab, −− > run

37 / 139
Working with MATLAB/Octave Environment and Commands Overview

Octave/MATLAB search path

MATLAB has a search path that it uses to find M-files


these directories of M-files are provided along with MATLAB, and
users may add others.
If a user enters a name at the MATLAB prompt, the MATLAB
interpreter attempts to
I First looks for the name as a variable
I It checks to see if the name is an M-file in the current directory, when
I It checks to see if the name is an M-file in any directory in the search
path.
so if you define a variable with the same name as a MATLAB
function or command, that function or command becomes
inaccessible

38 / 139
Working with MATLAB/Octave Numeric Arrays

Arrays
All MATLAB variables are multidimensional arrays, no matter what
type of data
I MATLAB is designed to operate primarily on whole arrays.
I Most programming languages mostly work with numbers one at a time
A matrix is a two-dimensional array.
We create an array with four elements in a single row as:

1 2 3 4

We create a matrix that has multiple rows and colums as:

1 3 5

2 4 6

7 8 10

39 / 139
Working with MATLAB/Octave Numeric Arrays

Fundamental MATLAB Classes

There are several classes (data types) in MATLAB. Each of them is in the
form of a matrix or array. With the exception of function handles.

40 / 139
Working with MATLAB/Octave Numeric Arrays

Creating Numeric Arrays

>>p = [3,7,9]
p =
To create a row vector, 3 7 9
separate the elements with
either a comma or a space. >>g = [3;7;9]
Use square brackets. g =
3
Create a column vector by
7
separating the elements by
9
semicolons
Also create a column vector >>p = [3,7,9]'
by using the transpose p =
notation (’), on a row vector 3
7
9
41 / 139
Working with MATLAB/Octave Numeric Arrays

>> r = [2,4,20]
r =
You can create vectors by
”appending” one vector to 2 4 20
another
For example, to create the >> w = [9,-6,3]
row vector u whose first three w =
columns contain the values of
r = [2,4,20] and whose fourth, 9 -6 3
fifth, and sixth columns
contain the values of w = >> u = [r,w]
[9,-6,3] u =

2 4 20 9 -6

42 / 139
Working with MATLAB/Octave Numeric Arrays

The colon operator (:)


generates a large vector of
regularly spaced elements.
Parentheses are not needed >> x = 0:2:8
but can be used for clarity. x =
Do not use square brackets.
Typing x = m:q:n 0 2 4 6 8
or
x = (m:q:n) >> x = 0:2:7
x =
Creates a vector x of values
with a spacing q. The first
0 2 4 6
value is m. The last value is n
if m - n is an integer multiple
of q. If not, the last value is
less than n.

43 / 139
Working with MATLAB/Octave Numeric Arrays

>> z = 5:0.1:8
z =

Columns 1 through 10:


To create a row vector z 5.0000 5.1000 5.2
consisting of the values from Columns 11 through 20:
5 to 8 in steps of 0.1, type 6.0000 6.1000 6.2
z = 5:0.1:8 Columns 21 through 30:
If the increment q is omitted, 7.0000 7.1000 7.2
it is presumed to be 1. Thus Column 31:
typing y = -3:2 produces 8.0000
the vector y = [-3,-2,-1,0,1,2]
>> y = -3:2
y =

-3 -2 -1 0 1 2

44 / 139
Working with MATLAB/Octave Numeric Arrays

The linspace command also >> linspace(5,8,31)


creates a linearly spaced row ans =
vector
The syntax is Columns 1 through 11:
linspace(x1,x2,n), where 5.0000 5.1000 5.2000 5
x1 and x2 are the lower and Columns 12 through 22:
upper limits and n is the 6.1000 6.2000 6.3000 6
number of points. Columns 23 through 31:
For example, linspace(5,8,31) 7.2000 7.3000 7.4000 7
is equivalent to 5:0.1:8
>> linspace(-3,2,6)
If n is omitted, generates
ans =
returns a row vector of 100
evenly spaced points between
-3 -2 -1 0 1 2
x1 and x2.

45 / 139
Working with MATLAB/Octave Numeric Arrays

The logspace command


creates an array of
logarithmically spaced
elements. >> x = logspace(-1,1,4)
x =
Its syntax is logspace(a,b,n),
where n is the number of
0.1000 0.4642 2.1
points between 10a and 10b .
If n is omitted, the number of
points defaults to 50.

46 / 139
Working with MATLAB/Octave Numeric Arrays

Magnitude, Length, and Absolute Value of a Vector

>> x = [2,-4,5]
x =
The length command gives
2 -4 5
the number of elements in the
vector
>> length(x)
The magnitude of a vector is ans = 3
a scalar, and is the same as
the vector’s geometric length >> M = sqrt(sum(x.*x))
The absolute value of a vector M = 6.7082
x is a vector whose elements
are the absolute values of the >> abs(x)
elements of x. ans =

2 4 5
47 / 139
Working with MATLAB/Octave Numeric Arrays

Matrices

A matrix (2D array) has multiple rows and columns


Example:  
 2 4 10 
 
 16 3 7 
 
M =



 8 4 9 
 
 
3 12 15

This matrix has four rows and three columns


In general, we can say Vectors are special cases of matrices having
one row or one column.

48 / 139
Working with MATLAB/Octave Numeric Arrays

Creating Matrices

To create the matrix: >> M = [2,4,10;16,3,7;8,4,9;3,12,15]


  M =
 2 4 10 
  2 4 10
 16 3 7 
 
16 3 7
M = 

 8 4 9
 8 4 9 



 3 12 15
3 12 15
>> M=[2 4 10; 16 3 7; 8 4 9; 3 12 15]
spaces or commas M =
separate elements in
different columns, 2 4 10
whereas semicolons 16 3 7
separate elements in 8 4 9
different rows. 3 12 15
49 / 139
Working with MATLAB/Octave Numeric Arrays

Creating Matrices from Vectors

Suppose
>> c = [a b]
>> a = [1,3,5] c =
a =
1 3 5 7 9 11
1 3 5
>> D = [a;b]
>> b = [7,9,11] D =
b =
1 3 5
7 9 11 7 9 11

50 / 139
Working with MATLAB/Octave Numeric Arrays

The Indexing expression


A(m,n)
returns the mth row, nth column element of matrix A

>> M = [2,4,10;16,3,7;8,4,9;3,12,15]
M =

2 4 10
16 3 7
8 4 9
3 12 15

>> M(2,3)
ans = 7
>> M(3,2)
ans = 4

51 / 139
Working with MATLAB/Octave Numeric Arrays

Linear indexing expression

>> A = [12 36 91; 45 29 48; 33 25 11]


A =
12 36 91
45 29 48
Uses only a single 33 25 11
index, regardless of
the size or dimensions >> A(1)
of the array ans = 12
A(m) >> A(3)
returns the mth ans = 33
element >> A(4)
Indexing starts from 1 ans = 36
>> A(7)
ans = 91
>> A(9)
ans = 11 52 / 139
Working with MATLAB/Octave Numeric Arrays

Using a colon as a subscript in the indexing expression


A(:,n) is the nth column of
matrix A. >> A(:,1)
A(m,:) is the mth row of ans =
matrix A. 0.5575
0.5474
A(:) reshapes all elements of
A into a single column vector.
>> A(1,:)
This has no effect if A is
ans =
already a column vector.
0.5575 0.7448
Suppose,
>> A(:)
>> A = rand(2,2) ans =
A = 0.5575
0.5474
0.5575 0.7448 0.7448
0.5474 0.3309 0.3309
53 / 139
Working with MATLAB/Octave Numeric Arrays

Using a colon as a subscript in the indexing expression


A(:,:) reshapes all
>> A = [12 36 91; 45 29 48; 33 25 11]
elements of A into a
A =
two-dimensional matrix.
12 36 91
This has no effect if A is
45 29 48
already a matrix or
33 25 11
vector.
A(j:k) uses the vector j:k >> A(1:7)
to index into A and is ans =
therefore equivalent to 12 45 33 36 29 25 91
the vector [A(j), A(j+1),
..., A(k)]. >> A(:,1:2)
A(:,j:k) includes all ans =
subscripts in the first 12 36
dimension but uses the 45 29
vector j:k to index in the 33 25
second dimension. 54 / 139
Working with MATLAB/Octave Numeric Arrays

Amending arrays

>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
>> A(2,2) = -11
A =
A(end,:) denotes the last row 1 2 3
in A, and A(:,end) denotes 4 -11 6
the last column. 7 8 9
Assigning elements >> A(end,:)
ans =
7 8 9
>> A(:,end)
ans =
3 55 / 139
Working with MATLAB/Octave Numeric Arrays

Multidimensional Arrays

A multidimensional array in MATLAB ® is an array with more than


two dimensions.
an extension of 2-D matrices and use additional subscripts for
indexing.
The first two are just like a matrix, but the third dimension represents
pages or sheets of elements.

Figure: A 3D array with two pages

56 / 139
Working with MATLAB/Octave Numeric Arrays

Creating Multidimensional Arrays

>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
Create a 2-D matrix first, and 7 8 9
then extend it.
>> A(:,:,2) = [10 11 12; 13 14
To do this, assign another
A =
matrix to the index value 2 in
ans(:,:,1) =
the third dimension.
1 2 3
Note its dimension in the 4 5 6
workspace 7 8 9
ans(:,:,2) =
10 11 12
13 14 15
16 17 18 57 / 139
Working with MATLAB/Octave Numeric Arrays

Accessing Elements

The cat function can be a >> B = cat(3,A,[3 2 1; 0 9 8; 5


useful tool for building B =
multidimensional arrays. ans(:,:,1) =
1 2 3
4 5 6
cat(dim,
7 8 9
,→ array1,, arrayN)
ans(:,:,2) =
10 11 12
For example, create a new 13 14 15
3-D array B by concatenating 16 17 18
A with a third page. ans(:,:,3) =
The first argument 3 2 1
indicates which dimension to 0 9 8
concatenate along. 5 3 7

58 / 139
Working with MATLAB/Octave Numeric Arrays

Array Functions

59 / 139
Working with MATLAB/Octave Numeric Arrays

... Array Functions

60 / 139
Working with MATLAB/Octave Numeric Arrays

Array Vs. matrix Operations

MATLAB has two forms of arithmetic operations on arrays,


I Array or element-by-element operations.
I matrix operations (as used in linear algebra)
Each form has its own applications.

61 / 139
Working with MATLAB/Octave Numeric Arrays

Element-by-element operations

Array or Element-by-element operation is defined only for arrays


having the same size
The array operations are performed between the elements in
corresponding locations in the arrays.

62 / 139
Working with MATLAB/Octave Numeric Arrays

Array Addition and Subtraction


For example,
     
 6 −2   9 8   15 6 
 + = 
10 3 −12 14 −2 17

>> A = [6,-2;10,3];
>> B = [9,8;-12,14];
>> A+B
ans =
15 6
-2 17

Array subtraction is performed in a similar way


63 / 139
Working with MATLAB/Octave Numeric Arrays

Array Multiplication with scalar


Multiplication: Multiplying a matrix A by a scalar w produces a
matrix whose elements are the elements of A multiplied by w.
For example,    
 2 9   6 27 
3 = 
5 −7 15 −21

>> A = [2, 9; 5,-7];


>> 3*A
ans =

6 27
15 -21

64 / 139
Working with MATLAB/Octave Numeric Arrays

For eample,    
 11 5   −7 8 
A=  B = 
−9 4 6 2
then C = A.*B gives this result:
   
 11(−7) 5(8)   −77 40 
C = = 
−9(6) 4(2) −54 8

>> A = [11, 5; -9, 4];


>> B = [-7, 8; 6, 2];
>> C = A.*B
C =

-77 40
-54 8
65 / 139
Working with MATLAB/Octave Numeric Arrays

Vectorized functions: built-in


MATLAB functions
>> x = [4, 16, 25];
automatically operate on
>> y = sqrt(x)
array arguments to produce
y =
an array result the same size
as the array argument
2 4 5
However, when multiplying or
dividing these functions, or >> z = exp(y).*sin(x).*(cos(x))
when raising them to a power, z =
you must use
element-by-element -2.3892 -14.4161 -19.2987
operations if the arguments
are arrays

66 / 139
Working with MATLAB/Octave Numeric Arrays

The code snippet below computes the sine of 1,001 values ranging
from 0 to 10

1 t = 0:.01:10;
2 y = sin(t);

>> x = [3, 5, 8];


>> x.^3
MATLAB enables us not only ans =
to raise arrays to powers but 27 125 512
also to raise scalars and arrays
to array powers >> 2.^x
ans =
8 32 256

67 / 139
Working with MATLAB/Octave Numeric Arrays

Remember that .^ is a single symbol.


The dot in 3.^p is not a decimal point associated with the number 3.
The following operations, with the value of p = [2,4,5], are
equivalent and give the correct answer:
I 3.^p
I 3.0.^p
I 3..^p
I (3).^p
I 3.^[2,4,5]

68 / 139
Working with MATLAB/Octave Numeric Arrays

Matrix operation
matrix operations follow the normal rules of linear algebra
Example matrix Multiplication:
   
 6 −2   (6)(9) + (−2)(−5) (6)(8) + (−2)(12)
 
 9 8  

 
 10
 3 
 =  (10)(9) + (3)(−5) (10)(8) + (3)(12)


  −5 12  
4 7 (4)(9) + (7)(−5) (4)(8) + (7)(12)
 
 64 24 
 
= 75 116 

 
1 116

>> A = [6,-2;10,3;4,7]; B = [9,8;-5,12];


>> A*B
ans = 69 / 139
Working with MATLAB/Octave Numeric Arrays

Summary: ARRAY AND MATRIX OPERATIONS

70 / 139
Working with MATLAB/Octave Numeric Arrays

Function Description

det() Determinant of a square matrix

dot() Dot product of two vectors


cross() Cross product of two vectors
eig() Eigenvalues and eigenvectors of special matrix equations
eye() Creates the identity matrix
inv() Inverse of a square matrix
linsolve() Solves a linear system of equations
size() Order (size) of an array
ones() Creates an array whose elements equal 1
zeros() Creates an array whose elements equal 0
71 / 139
Working with MATLAB/Octave Numeric Arrays

Significance of matrix left division


A 3 × 3 set of simultaneous linear equations takes the form

a11 x1 + a12 x2 + a13 x3 = b1


a21 x1 + a22 x2 + a23 x3 = b2
a31 x1 + a32 x2 + a33 x3 = b3

which can be expressed as Ax = B


     
 a11 a12 a13   b1  x
 1 
     
where A =  a21 a22 a23 
 , B =  b
 2
 , and x =  x  .
  2 
     
a31 a32 a33 b3 x3

We can solved for x using linear algebra, x = A−1 B


Since the left division operator A\B is defined to be inv(A) * B,
the left division operator solves a system of simultaneous equations.
72 / 139
Working with MATLAB/Octave Numeric Arrays

Example 3

>> c = [4 -1 0 0 0 -1;...
-1 4 -1 0 -1 0; ...
0 -1 4 -1 0 0; ...
Solve the following system of 0 0 -1 4 -1 0; ...
equations 0 -1 0 -1 4 -1; ...
-1 0 0 0 -1 4];
4T1 − T2 − T6 = 200
>> d = [200, 80, 140, 140,
−T1 + 4T2 − T3 − T5 = 80 ,→ 80, 200];
−T2 + 4T3 − T4 = 140 >> T = linsolve(c, d')
−T3 + 4T4 − T5 = 140 T =
−T2 − T4 + 4T5 − T6 = 80 94.286
82.857
−T1 − T5 + 4T6 = 200
74.286
74.286
82.857
94.286 73 / 139
Working with MATLAB/Octave Numeric Arrays

Finding eigenvalues and eigenvectors


The ever present and tedious eigenvalue problem in engineering
computation shows up as
Av = λ v , where λ is a scalar
The problem is to find λ and v for a given A so that the equation is
satisfied.

>> A = [5 -3 2; -3 8 4; 4 2 -9];
>> [v,d] = eig(A)
v =
0.172542 0.870606 -0.537542
0.238228 0.377390 0.842875
-0.955760 0.315629 -0.024708
d =
-10.2206 0 0
0 4.4246 0
0 0 9.7960
74 / 139
Working with MATLAB/Octave Plotting

Plotting a data set

To plot a data set, just create two vectors containing the x and y
values to be plotted, and use the plot function.

1 x = 0:1:10;
2 y = x.^2 - 10.*x + 15;
3 plot(x,y);

75 / 139
Working with MATLAB/Octave Plotting

Adding title, labels and grid

1 x = 0:1:10;
2 y = x.^2 - 10.*x + 15;
3 plot(x,y);
4 title ('Plot of y = x.^2
,→ - 10.*x + 15');
5 xlabel ('x');
6 ylabel ('y');
7 grid on;

76 / 139
Working with MATLAB/Octave Plotting

Multiple plots
Including more than one set of (x, y ) values in the plot function.

1 x = 0:pi/100:2*pi;
2 y1 = sin(2*x);
3 y2 = 2*cos(2*x);
4 plot(x,y1,x,y2);

1 x = -pi:pi/20:pi;
2 y1 = sin(x);
3 y2 = cos(x);
4 plot(x,y1);
5 hold on;
6 plot(x,y2);
7 hold off; 77 / 139
Working with MATLAB/Octave Plotting

Line Color, Line Style, Marker Style, and Legends


Syntax: plot(x,y,LineSpec)
Syntax: legend('string1','string2',...,'Location',pos)

78 / 139
Working with MATLAB/Octave Plotting

x = 0:pi/30:2*pi;
y1 = sin(2*x);
y2 = 2*cos(2*x);
plot(x,y1,'bx-',x,y2,'go--');
title ('Plot of f(x) = sin(2x)
,→ and its derivative');
xlabel ('x');
ylabel ('y');
legend ('f(x)','d/dx
,→ f(x)','Location','southeast')
grid on;

79 / 139
Working with MATLAB/Octave Plotting

Creating multiple figures


Syntax: subplot(m,n,p)
This command divides the Figure window into an array of rectangular
panes with m rows and n columns. The variable p tells MATLAB to
place the output of the plot command in the p th pane
Example 4

1 x = 0:0.01:5;
2 y = exp(-1.2*x).*sin(10*x+5);
3 subplot(1,2,1)
4 plot(x,y);xlabel('x');ylabel('y');axis([0 5 -1 1])
5 x = -6:0.01:6;
6 y = abs(x.^3-100);
7 subplot(1,2,2)
8 plot(x,y);xlabel('x');ylabel('y');axis([-6 6 0 350])

80 / 139
Working with MATLAB/Octave Plotting

Example 5
The script above plots the function:

y = e −1.2x sin(10x + 5) for 0≤x ≤5


3
y = |x − 100| for −6 ≤ x ≤ 6

81 / 139
Working with MATLAB/Octave Plotting

Annotating and Saving Plots


View menu −− > Plot Edit Toolbar menu item. This toolbar allows a
user to add lines, arrows, text, rectangles, and ellipses to annotate
and explain a plot.

82 / 139
Working with MATLAB/Octave Program flow control structures

Relational and logical operators

output is 1 if the relational and logical operations are true and 0 if


they are false.

83 / 139
Working with MATLAB/Octave Program flow control structures

Control of program flow

Program flow control is performed by branching or looping.


The branching is done with the if and switch statements
Looping with either the for or the while statements.

84 / 139
Working with MATLAB/Octave Program flow control structures

Branching If Statement
Branches to different parts of its structure depending on the satisfaction of
conditional expressions.

Syntax: Example 6
In English, we could specify this
if logical expression procedure as follows: If x is
greater than or equal to zero,
statements √
end compute y from y = x
The statement implements this
procedure as:
For example Suppose that,
x is a scalar and that we want 1 if x >= 0

to compute y = x only if 2 y = sqrt(x)
x ≥ 0. 3 end

85 / 139
Working with MATLAB/Octave Program flow control structures

How will the below be evaluated for scalar x and y values?

1 z = 0;w = 0;
2 if (x >= 0)&(y >= 0)
3 z = sqrt(x) + sqrt(y)
4 w = sqrt(x*y)
5 end

86 / 139
Working with MATLAB/Octave Program flow control structures

Branching- if / elseif / else statement

The else statement must come after the elseif statement to take care
of all conditions that might be unaccounted for.
The statements elseif and else are optional.
Also, there can be more than one elseif statement.

1 if logical expression 1
2 statement group 1
3 elseif logical expression 2
4 statement group 2
5 else
6 statement group 3
7 end

87 / 139
Working with MATLAB/Octave Program flow control structures

Branching - Nested if statement

Note how the indenting of the expressions inside the various nested
structures makes the code more readable.

88 / 139
Working with MATLAB/Octave Program flow control structures

Branching Switch Statement


The switch structure is essentially an alternative to using a series of
if-elseif- else-ends structures.
The switch block tests each case
switch switch_expression until one of the case expressions is
case case_expression #1 true. A case is true when:
statements #1 I For numbers,
case_expression == switch_exp
case case_expression #2 I For character, case-expression is
statements #2 the same as switch-expression
. . . I For a cell array, at least one of the
case case_expression #n elements of the cell array matches
statements #n switch-expression
otherwise When a case expression is true, the
statements #n+1 corresponding statements is
end executed and the switch block is
exited
89 / 139
Working with MATLAB/Octave Program flow control structures

Example 7

1 % Display different text conditionally, depending on a


,→ value entered at the command prompt
2

3 n = input('Enter a number: ');


4 switch n
5 case -1
6 disp('negative one')
7 case 0
8 disp('zero')
9 case 1
10 disp('positive one')
11 otherwise
12 disp('other value')
13 end

90 / 139
Working with MATLAB/Octave Program flow control structures

Example 8
Suppose the quantity k has been assigned a value or had its value
computed prior to encountering this structure.

91 / 139
Working with MATLAB/Octave Program flow control structures

for loop
A for loop repeats a series of statements a specific number of times.
I Each repetition of the loop is a pass
I the number of passes is known ahead of time
Its general form is:

for loop_variable = expression


statements
end

A typical structure of a for loop is

for loop_variable = m:s:n


statements
end

92 / 139
Working with MATLAB/Octave Program flow control structures

Example 9

for k = 5:10:35
x = k^2
end

1 The loop variable k is initially


assigned the value 5
2 x is calculated from x = k 2 .
3 In each successive pass, the loop
increments k by 10 and calculates x
until k exceeds 35.
4 The program then continues to
execute any statements following
Figure: Flowchart of a for loop
the end statement.
93 / 139
Working with MATLAB/Octave Program flow control structures

Example 10

% This script iterate through the array g and uses the if


,→ logical statement to find the greatest value element

g = [2,4,6,7,8,2,10,45,75,4,88,98,4,1,5,7];
gr8t = g(1);
for n = 1:length(g)
if g(n) >= gr8t
gr8t = g(n);
end
end
disp(gr8t)

94 / 139
Working with MATLAB/Octave Program flow control structures

while loop
The while loop repeats one or more statements an indefinite number
of times, leaving the loop only when a specified condition has been
satisfied.
I thus the number of passes is not known in advance
Its general form is

while logical_expression
statements
end

I A loop variable must be included in the logical expression


I The loop variable must have a value before the while statement is
executed.
I The loop variable must be changed somehow by the statements.

95 / 139
Working with MATLAB/Octave Program flow control structures

Example 11

x = 5;
while x < 25
disp(x)
x = 2*x - 1; The loop variable x is initially
end assigned the value 5.
The value then changes to 9,
after x = 2*x - 1;
Before each pass through the
loop, x is checked to see
whether its value is less than 25.
If so, the pass is made.
If not, the loop is skipped and
the program continues to
execute any statements
following the end statement. 96 / 139
Working with MATLAB/Octave Program flow control structures

The break and continue Statements


Terminate execution of for or while loop
Statements in the loop after the break statement do not execute. In
nested loops, break exits only from the loop in which it occurs.

1 % Sum a sequence of random numbers until the next random


,→ number is greater than an upper limit.
2 limit = 0.8;
3 s = 0;
4 while 1
5 tmp = rand;
6 if tmp > limit
7 break
8 end
9 s = s + tmp;
10 end

97 / 139
Working with MATLAB/Octave Program flow control structures

... The break and continue Statements


The break statement exits a for or while loop completely. To skip the
rest of the instructions in the loop and begin the next iteration, use a
continue statement.

1 % Display the multiples of 7 from 1 through 50. If a


,→ number is not divisible by 7, use continue to skip
,→ the disp statement and pass control to the next
,→ iteration of the for loop.
2 for n = 1:50
3 if mod(n,7)
4 continue
5 end
6 disp(['Divisible by 7: ' num2str(n)])
7 end

98 / 139
Working with MATLAB/Octave Program flow control structures

Infinite loops

A loop that never ends. Avoid it!


Example:

1 x = 8;
2 while x ~= 0
3 x = x - 3;
4 end

Within the loop the variable x takes on the values 5, 2, 1, 4, . . . ,


and the condition x ~= 0 is always satisfied, so the loop never stops.
Use Ctrl + C to stop it

99 / 139
Working with MATLAB/Octave Program flow control structures

Debugging

As you work in the Editor Octave/MATLAB debugger automatically


identifies syntax errors and potential coding problems.
I Read and investigate them prior to running the program
I Read and investigate error messages from command window after a
failed run
Diagnose problems yourself using these debugging methods.
I Editing the code and removing semicolons.If you want to determine
whether a line of code produces the expected result or not, examining
values is useful.
I Setting a breakpoint at a particular line and stepping through code
from there. You can view the value of any variable currently in the
workspace at each line

100 / 139
Working with MATLAB/Octave Functions

Input/output functions

Function Description

disp(A) Displays the value of the A, but not the name

disp('text') Displays the text in quotes.

x=input('text') Displays the text in quotes, waits for user


input from the keyboard, and stores the value
in x.

x=input('text','s') Displays the text in quotes, waits for user


input from the keyboard, and stores the input
as a string in x.

101 / 139
Working with MATLAB/Octave Functions

... Input/output functions

Example 12
Upon execution,

>> in1 = input('Enter data: ');


Enter data: 1.23

stores the numeric value 1.23 into in1, where the value 1.23 was
entered by the user.

>>in2 = input('Enter data: ','s');


Enter data: 1.23

stores the character array ’1.23’ into in2

102 / 139
Working with MATLAB/Octave Functions

Formatted Input/output functions


To format data to a file or for an output display
I applies the formatSpec to elements of arrays A1,...An in column order

fprintf(fileID,formatSpec,A1,...,An)

I formats data and displays the results on the screen.

fprintf(formatSpec,A1,...,An)

Example 13

1 A1 = [0.9, 900];
2 A2 = [0.8, 0.7 ; 800, 700]; X is 0.90 km or 900.0 m
3 formatSpec = 'X is %4.2f km or X is 0.80 km or 800.0 m
,→ %5.1f m\n'; X is 0.70 km or 700.0 m
4 fprintf(formatSpec,A1,A2)

103 / 139
Working with MATLAB/Octave Functions

... Formatted Input/output functions


Example 13
%4.2f in the formatSpec input specifies that the first value in each line
of output is a floating-point number with a field width of four digits,
including two digits after the decimal point. %5.1f in the formatSpec
input specifies that the second value in each line of output is a
floating-point number with a field width of five digits, including three digits
after the decimal point. \n is a control character that starts a new line.

The structure of a typical formatSpec

104 / 139
Working with MATLAB/Octave Functions

... Formatted Input/output functions


Conversion Description

%d integer (it stands for decimal integer)

%f float (real number)

%c character (one character)

%s string of characters

Escape Sequences Description

\n New line.

\t Horizontal tab.

105 / 139
Working with MATLAB/Octave Functions

Useful functions for your Linear algebra coursework

Function Description

lu LU matrix factorization

chol Cholesky factorization

qr QR decomposition

tril Lower triangular part of matrix

triu Upper triangular part of matrix

rank Rank of matrix

rref Reduced row echelon form (Gauss-Jordan elimination)

Use doc FunctionName for documentation and examples


106 / 139
Working with MATLAB/Octave Functions

User-define Functions

All of the M-files that we have seen so far have been script files.
Script files are just collections of MATLAB statements that are stored
in a file.
Another type of M-file is a function file.
Create by selecting New under the HOME tab on the Toolstrip, but
instead of selecting Script, select Function.
The first line in a function file begins with a function definition line
that has a list of inputs and outputs, i.e. function header
Or create a script and begin its first executable line with a function
definition
This line distinguishes a function M-file from a script M-file.

107 / 139
Working with MATLAB/Octave Functions

... User-define Functions

Function Syntax:

1 function [outarg1, outarg2, ...] =


,→ FunctionName(inarg1, inarg2, ...)
2 % Comment describing the function
3 ExecutableStatements;
4 end

Function file name must be the same as the function name


Call this function with its input argument:
FunctionName(inarg1, inarg2, ...)

108 / 139
Working with MATLAB/Octave Functions

Example 14

1 function [dist,vel] = drop(g,v0,t)


2 % Computes the distance travelled and the velocity of a
,→ dropped object, as functions of gravity g, the
,→ initial velocity v0, and the time t.
3 vel = g*t + v0;
4 dist = 0.5*g*t.^2 + v0*t;
5 end

>> [a,b] = drop(9.81,3,2)


a =
25.6200
b =
22.6200
109 / 139
Working with MATLAB/Octave Functions

Example 14

1 %This script file uses our drop function


2

3 disp('Calculate the distance between two points:');


4 g = input('Enter the value of gravity: ');
5 v0 = input('Enter the velocity: ');
6 t = input('Enter the time: ');
7

8 % Evaluate function
9 [dist,vel] = drop(g,v0,t);
10

11 % Write out result.


12 fprintf('\nThe distance travel is %f\n',dist);
13 fprintf('The velocity is %f\n',vel);
14

110 / 139
Working with MATLAB/Octave Functions

Adding functions to scripts


Local functions: are useful if you want to reuse code within a script.

1 % The script calculates the permutation of (3,2)


2 x = 3;
3 y = 2;
4 z = perm(x,y)
5

6 function p = perm(n,r)
7 % perm Local Function that calculates the permutation
8 p = fact(n)/fact(n-r);
9 end
10

11 function f = fact(n)
12 % fact Local Function that calculates the factorial
13 f = prod(1:n);
14 end
111 / 139
Working with MATLAB/Octave Functions

Function handles
A function handle is an Octave/MATLAB data type that stores an
association to a function.
To create a handle for a function, precede the function name with an
@ sign.
Once we create the function handle, we can pass input arguments to
the function handle or pass the handle to another function
For example, consider the following user-defined function, which
computes: y = x + 2e −x − 3
To create a handle to this
function and name the handle
fh1;
1 function y = f1(x)
2 y = x + 2*exp(-x) - 3; >> fh1 = @f1;
3 end >> fh1(2)
ans = -0.7293

112 / 139
Working with MATLAB/Octave Functions

Anonymous Functions
A function that is not stored in a program file, but is associated with
a variable whose data type is function handle.
Anonymous functions can accept multiple inputs and return one
output. They can contain only a single executable statement.
For example,
f (x) = 5 sin(x) − x 2 + 3
g (y , z) = 25 − y 2 − z 2

>> f = @(x) 5*sin(x) - x.^2 + 3;

>> g = @(y,z) (25 - y.^2 - z.^2);

113 / 139
Working with MATLAB/Octave Functions

f (x) = 2x 2 + 3 , g (x) = 2xf (x − 3) + 5x

>> f = @(x) 2*x.^2 + 3;


>> g = @(x,f) 2*x.*f(x-3) + 5*x;

Use function handles like any other function


I pass input argument; scalars, arrays
I plotting

114 / 139
Working with MATLAB/Octave Functions

fplot function

fplot(FN,interval)

Plots the function FN over the specified interval. Specify the interval as a
two-element vector of the form [tmin tmax].

>> fplot(@(x) 2*cos(3*x),[-3 3])

115 / 139
Working with MATLAB/Octave Functions

The fzero() function (Root of nonlinear function)

tries to find a point x where FN(x) = 0. This solution is where FN(x)


changes sign—fzero cannot find a root of a function such as x 2 .

x = fzero(FN,x0)

Examples:

fun = @sin; % function fun = @cos; % function


x0 = 3; % initial point x0 = [1 2]; % initial interval
x = fzero(fun,x0) x = fzero(fun,x0)

116 / 139
Working with MATLAB/Octave Functions

fsolve() function

Solve system of nonlinear equations

x = fsolve(fun,x0)

Solves a problem specified by F (x) = 0 for x, where F (x) is a


function that returns a vector value. x is a vector or a matrix
This example shows how to solve two nonlinear equations in two
variables.
−(x1 −x2 )
e −e = x2 1 + x12


1
x1 cos (x2 ) + x2 sin (x1 ) =
2

117 / 139
Working with MATLAB/Octave Functions

... fsolve() function


Convert the equations to the form F (x) = 0.
−(x1 +x2 )
e −e − x2 1 + x12 = 0


1
x1 cos (x2 ) + x2 sin (x1 ) − = 0
2
Write a function that computes the left-hand side of these two equations

1 function F = root2D(x)
2 F(1) = exp(-exp(-(x(1)+x(2)))) - x(2)*(1+x(1)^2);
3 F(2) = x(1)*cos(x(2)) + x(2)*sin(x(1)) - 0.5;
4 end

Solve the system of equations starting at the point [0,0]

fun = @root2D;
x0 = [0,0]; %Initial guess
x = fsolve(fun,x0) 118 / 139
Working with MATLAB/Octave Functions

Exercise

Find the intersection of an ellipse,

g (x, y ) = x 2 /4 + y 2 − 1

with the parabola,


f (x, y ) = y − 4x 2 + 3

119 / 139
Working with MATLAB/Octave Functions

The roots() function

Polynomial roots: returns the roots of the polynomial represented by


p as a column vector.

r = roots(p)

Example: Solve the equation x 2 − 2x − 4 = 0

1 p = [1 -2 -4];
2 r = roots(p)

120 / 139
Working with MATLAB/Octave Functions

The linsolve() function

Solve linear system of equations, refer to example ...

121 / 139
Working with MATLAB/Octave Functions

Numerical differentiation and integration

122 / 139
Working with MATLAB/Octave Functions

Importing and Exporting Data files

File content Extension Import Export


Function function

MATLAB MAT load() save()


formatted data

Text .csv .txt csvread() csvwrite()


readmatrix()1 writematrix()1

Spreadsheet .xls .xlsx xlsread() xlswrite()


readmatrix()1 writematrix()1

1 MATLAB only
123 / 139
Working with MATLAB/Octave Functions

Interpolation and Curve fitting

Interpolation is to estimate a data point between two known points


Consider a set of x–y data collected during an experiment. By using
an interpolation technique, we can estimate the value of y at values
of x where we didn’t take a measurement
Curve fitting is the process of constructing a curve or mathematical
function that has the best fit to a series of data points.
Fitted curves can be used to infer values of a function where no data
are available and to summarize the relationships among two or more
variables.

124 / 139
Working with MATLAB/Octave Functions

1-D data interpolation

vq = interp1(x,v,xq,method)

Returns interpolated values of a 1-D function at specific query points.


Vector x contains the sample points, and v contains the corresponding
values, v(x). Vector xq contains the coordinates of the query points.
The interpolation method: ’linear’, ’nearest’, ’cubic’, or ’spline’. The
default method is ’linear’
1 x = 0:5;
2 y = [15, 10, 9, 6, 2, 0];
3 new_x = 0:0.2:5;
4 new_y = interp1(x,y,new_x)
5 plot(x,y,'-o',new_x,new_y,'x')
6 legend('Original
,→ data','Interpolated data')

125 / 139
Working with MATLAB/Octave Functions

... 1-D data interpolation


Example 15
Thermodynamics makes extensive use of steam tables. Commonly, many
experiments are performed at atmospheric pressure, so you may regularly

° °
need to use the table below, which is just a portion of the steam tables.
Notice that the table is spaced first at 50 C intervals and then at 100 C
intervals. Suppose you have a project that requires you to use this table
and you prefer not toperform a linear interpolation every time you use it.

°
Use Octave/MATLAB to create a table, employing linear interpolation,
with a temperature spacing of 25 C.

126 / 139
Working with MATLAB/Octave Functions

Example 15

1 clear, clc
2 T = [100, 150, 200, 250, 300, 400, 500]';
3 v = [1.6958, 1.9364, 2.172, 2.406, 2.639, 3.103, 3.565]';
4 u = [2506.7, 2582.8, 2658.1, 2733.7, 2810.4, 2967.9,
,→ 3131.6]';
5 h = [2676.2, 2776.4, 2875.3, 2974.3, 3074.3, 3278.2,
,→ 3488.1]';
6 props = [v,u,h];
7 newT = [100:25:500]';
8 newprop = interp1(T,props,newT);
9 disp('Steam Properties at 0.1 MPa')
10 disp('Temp Specific Volume Internal Energy Enthalpy')
11 disp(' C m^3/kg kJ/kg kJ/kg')
12 fprintf('%6.0f %10.4f %8.1f %8.1f
,→ \n',[newT,newprop]')
127 / 139
Working with MATLAB/Octave Functions

Example 15

128 / 139
Working with MATLAB/Octave Functions

Polynomial curve fitting

[p,S] = polyfit(x,y,n)

returns the coefficients for a polynomial p(x) of degree n that is a best fit
(in a least-squares sense) for the data in y. The coefficients in p are in
descending powers, and the length of p is n+1

p(x) = p1 x n + p2 x n−1 + . . . + pn x + pn+1

And a structure S that can be used as an input to polyval to obtain error


estimates.

129 / 139
Working with MATLAB/Octave Functions

Example 16
Fit Polynomial to Trigonometric Function

1 % Generate 10 points equally spaced along a sine curve in


,→ the interval [0,4*pi].
2 x = linspace(0,4*pi,10);
3 y = sin(x);
4 % Use polyfit to fit a 7th-degree polynomial to the
,→ points, Evaluate the polynomial on a finer grid
5 p = polyfit(x,y,7)
6 x1 = linspace(0,4*pi);
7 y1 = polyval(p,x1);
8 plot(x,y,'o',x1,y1)

130 / 139
Working with MATLAB/Octave Functions

Example 16

131 / 139
Working with MATLAB/Octave Functions

Example 17
Determining how much water will flow through a culvert is not as easy as
it might first seem. The channel could have a non-uniform shape,
obstructions might influence the flow, friction is important, and so on. A
numerical approach allows us to fold all those concerns into a model of
how the water actually behaves.
Compute a best-fit linear, quadratic, and cubic equation for the data, and
plot them on the same graph. Which model best represents the data?
(Linear is first order, quadratic is second order, and cubic is third order.)

132 / 139
Working with MATLAB/Octave Functions

Example 17

1 % Water in a Culvert
2 height = [1.7, 1.95, 2.6, 2.92, 4.04, 5.24];
3 flow = [2.6, 3.6, 4.03, 6.45, 11.22, 30.61];
4 new_height = 0:0.5:6;
5 newf1 = polyval(polyfit(height,flow,1),new_height);
6 newf2 = polyval(polyfit(height,flow,2),new_height);
7 newf3 = polyval(polyfit(height,flow,3),new_height);
8 plot(height,flow,'o',new_height,newf1,new_height,newf2,
9 new_height,newf3)
10 title('Fit of Water Flow')
11 xlabel('Water Height, ft')
12 ylabel('Flow Rate, CFS')
13 legend('Data','Linear Fit','Quadratic Fit', 'Cubic Fit')

133 / 139
Working with MATLAB/Octave Functions

Example 17

134 / 139
Working with MATLAB/Octave Add-on packages and toolboxes

Symbolic Computations

Using Octave’s Symbolic package or MATLAB’s Symbolic toolbox:


I Differentiate Symbolic Expressions
F Derivatives of single-variable expressions
F Partial derivatives
F Second and higher order derivatives
F Mixed derivatives
I Integrate Symbolic Expressions
F Indefinite and definite integration
F Integration of multivariable expressions
I Solve Equations
F Algebraic equations with one or several symbolic variable
F Systems of algebraic equations
I Simplify Symbolic Expressions
I Substitutions in Symbolic Expressions

135 / 139
Working with MATLAB/Octave Add-on packages and toolboxes

... Symbolic Computations

Example functions

136 / 139
Working with MATLAB/Octave Add-on packages and toolboxes

Several other packages and toolboxes for subject-specific areas exist.


May make your life a little more easier! Explore!

137 / 139
Working with Excel

138 / 139
Engineering Problem Solving

139 / 139

You might also like