Chapter 1: Introduction
– A Simple Mathematical Model
– Conservation Laws
– MATLAB Fundamentals
– Computer Programming
– Programming with Matlab
A simple Mathematical Model
Problem of a falling object in air:
cd v 2
Fg= Force of gravity
v(t)= Velocity of the object
cd= Drag coefficient
Newton’s 2nd law:
mg cd v 2
(Equation of motion)
v v(t )
An Ordinary Differential Equation
Need to solve for v(t)
Initial condition: The object is initially at rest
t 0 ; v 0
Reformulate the problem so that it can be solved by arithmetic operations
v(ti 1 ) v(ti )
ti 1 ti
v(ti 1 ) v(ti )
ti 1 ti
v(ti ) 2
Finite Difference Approximation
(Since t is finite, we put
in the equation)
ti= initial time
v(ti)= velocity at initial time
ti+1= later time
v(ti+1)= velocity at later time
t=difference in time
v=difference in velocity
v(ti 1 )
v(ti ) 2 ti
ODE transformed into an algebraic equation.
can find new v(ti+1) at ti+1 from old v(ti) at ti using arithmetic operations.
still need to have initial conditions from the physics of the problem
(t=0 ; v=0) (given).
(for t=2 s)
Consider a quantity (E) in a system (E: energy, mass, current,...)
Change = E= E(final state) – E(initial state)
If E=0 (no change)
E(final state) = E(initial state)
E is conserved.
For example: Consider a current junction in a circuit:
Current in and out must be constant.
(conservation of charge)
I1+ I2 = I3 + I4
Can be applied to mass, flow, energy etc.
Conservation Laws in Engineering:
Conservation of Energy (All)
Conservation of Mass (Chemical, Mechanical, etc.)
Conservation of Momentum (Civil; Mechanical, etc.)
Conservation of Charge (Electrical, etc.)
We will employ these
conservation laws as
constraints in our
numerical solutions to
the problems .
Command window: to enter commands and data.
Graphics window: to plot graphics.
Edit window: create and edit M-files.
Can be operated just like a calculator
Define a scalar value
Assignments can be suppressed by semicolon (;)
(just stored in memory w/o displaying)
Can type several commands on the same line by seperating them with
comas or semicolons. If you use semicolon, they are not displayed.
>> a=4, A=6; x=1;
(MATLAB treats names case-sensitive , i.e. a is not same as A in above
Can assign complex values as MATLAB handles complex arithmetic
2.0000 + 4.0000i
If you desire more precision
>> format long
To return to four decimal version
>> format short
Arrays, vectors, matrices:
An array is a collection of values represented by a single variable name.
Matrcies are two-dimensional arrays.
In MATLAB every value is a matrix:
a scalar: 1x1 matrix
a row vector: 1xn matrix
A column vector: nx1 matrix
Square brackets ( [ ] ) are used to define an array in command mode.
>> a= [ 1 2 3 4 5]
is a 1x5 row vector.
In practive, a vector is usually meant to be a column vector. So, column vectors
are more practical. We can define them by the transpose operator (‘)
>> b = [ 2 4 6 8 10]’
A matrix of values can be assigned as follows:
>> A = [1 2 3 ; 4 5 6; 7 8 9]
Alternatively “Enter” key can be used at the end of each row to define A:
>> A =[ 1 2 3
4 5 6
7 8 9 ];
(strike Enter key after 3 and 6)
To see the list of all variables at any session:
Your variables are:
If you want more detail:
is 21 elements using 176 bytes
To see an individual element in an array:
Some predefined matrices are very useful.
>> E= zeros(2,3)
Colon (:) operator is very useful to generating arrays:
If you want increment other than 1, then you type:
>> t= 1:0.5:3
Negative increments can also be defined:
>> t= 10: -1: 5
Colon (:) can also be used to select individual rows:
>> A (2,:)
returns the second row of the matrix.
We can also use colon (:) to extract a series of elements from an array
Second through fourth elements are returned.
The common operators, in order of priority
Multiplication and Division
Left division (in matrix algebra)
Addition and Subtraction
>> y = pi/4;
>> y ^ 2.45
To override the priorities use paranthesis:
(-4) ^ 2
The real superiority of MATLAB comes in to carry out vector/matrix operations.
Inner product (dot product) of two vectors:
Multiply vector with matrices
>> a = [ 1 2 3];
A^2 will return the same result.
If the inner dimensions are not matched, you get an error message:
??? Error using ==> mtimes
Inner matrix dimensions must agree.
MATLAB normall treat simple arithmetic operations in vector/matrix
operations. You can also do an element-by-element operation. To do that you
put a dot (.) in front of the arithmetic operator.
>> A .^ 2
MATLAB is very rich in predefined functions (e.g., sqrt, abs, sin,
cos, acos, round, ceil, floor, sum, sort, min, max,
For a list of elementary functions:
>> help elfun
They operate directly on matrix quantities.
>> log (A)
Consider plotting time-versus-velocity for the falling object in air. The
solution to the problem was:
First need to define the time array:
This will define time (t) as 0,2,4..20. Total number of elements:
Assign values to the parameters:
>> g = 9.81 ; m = 68.1
Now calculate (v):
>> v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
To plot t versus t:
A graph appears in a graphics window.
You can add many properties to the graph. For example
>> title (‘A falling object in air’)
>> xlabel (t in second)
>> ylabel (v in meter per second)
If you want to see data points on the plot:
>> plot (t,v,’o’)
If you want to see both lines and points on the same plot
>> hold on
>> plot (t,v,’o’)
>> hold off
A simple addition algorithm
using natural language
Step 1: Start the calculation
Step 2: Input a value for A
Step 3: Input a value for B
Step 4: Add A to B and call the
Step 5: Output the value for C
Step 6: End the calculation
The same algorithm using a flowchart
Add A and B
Call the result C
A flowchart is a type of diagram that represents an algorithm.
Steps are shown by boxes of various kinds.
The order of the flow is shown by arrows.
Start and End of a program
Flow of the logic
Calculations or data manıpulations
Input or output of data and information
Comparison, question, or decision that
determines alternative paths to be
marks where the flow ends at one spot
on a page and continues at another spot.
Marks where the algorithms ends on one
page and continues at another
It is the comprehensive process of
(problem algorithm coding executables)
An algorithm is the step-by-step procedure for calculations.
It is a finite list of well-defined instruction for calculting a function.
Can be expressed in many ways: natural languages, pseudocodes,
Natural languages are usually ambigous and not a preferred way and
rarely used for comlex algorithms.
Programming lanuguages express algorithms so that they can be
executed by a computer.
Flowchart example for calculating factorial N (N!)
Pseudocode is a higher-level method for describing an algorithm.
It uses the structural convention of a programming language but is
intended for human reading rather than machine reading.
It is easier for people to understand than a programming code.
It is environment-independent description of the key principles of an
It omits the details not essential for human understanding of the algorithm
(such as variable declarations).
It can also advantage of natural language.
It is commonly used in textbooks and scientific publications.
No standard for pseudocode syntax exists.
It is an aim of improving the clarity, quality, and development time of a
computer program by making extensive use of subroutines, block
structures, for and while loops.
Use of “goto” statements is discouraged, which could lead to a “spaghetti
code” (which is often hard to follow and maintain).
Programs are composed of simple, hierarchical flow structures.
Many languages support and encourage structural programming.
A kind of structural programming that the act of designing and writing
programs (modules) as interactions among functions that each perform a
single-well defined function.
Coupling among modules are minimal.
Programming with Matlab
We use the editor window to generate M-files.
M-files contain a series of statements that can be run all at once.
Files are stored with extension .m
M-files can be script files or function files.
merely a series of Matlab commands that are saved on a file.
They can be executed by typing the filename in the command window.
Consider plotting the v(t) of the falling object problem. A script file can be
typed in the editor window as follows:
g = 9.81 ; m = 68.1 ;
v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
title (‘A falling object in air’)
xlabel (t in second)
ylabel (v in meter per second)
This script can be saved as an .m file and be executed at once in command
M-files that start with the word function.
Unlike script files they can accept input arguments and return outputs.
They must be stored as “functionname.m”.
Consider writing a function freefall.m for the falling body problem:
function v = freefall(t,m,cd)
% t(nx1) = time (nx1) in second
% m = mass of the object (kg)
% cd = drag coefficient (kg/m)
% v(nx1) = downward velocity (m/s)
g = 9.81 ; % acceleration of gravity
v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
Simplest M-file instructions are performed sequentially. Program
statements are executed line by line at the top of the file and moving
down to the end. To allow nonsequential paths we use
- Decisions (for branching of flow)
- if structure
- if…else structure
- if…elseif structure
- switch structure
- Loops (repetitions)
- for … end structure
- while structure
- while … break structure
Less than or equal to
Greater than or equal to