SlideShare una empresa de Scribd logo
1 de 36
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

FD

Fg= Force of gravity
FD=Drag force
m=mass
v(t)= Velocity of the object
cd= Drag coefficient

m

Fg

mg

FD

ma m

Newton’s 2nd law:

Fnet

Fg

mg cd v 2
dv
dt

g

cd 2
v
m

m

dv
dt

dv
dt

(Equation of motion)

v v(t )
An Ordinary Differential Equation
(ODE)
Need to solve for v(t)
Analytical Solution:

dv
dt

g

cd 2
v
m

Initial condition: The object is initially at rest
(using Calculus)

v

v(t )

gm
tanh
cd

t 0 ; v 0
gcd
t
m

Terminal velocity

t (s)

v (m/s)

0

0

2

18.7292

4

33.1118

6

42.0762

8

46.9575

10

49.4214

12

50.6175
51.6938

t
Numerical Solution:

dv
dt

g

cd 2
v
m

Reformulate the problem so that it can be solved by arithmetic operations

dv
dt
dv
dt

lim

v
t

v(ti 1 ) v(ti )
ti 1 ti

v(ti 1 ) v(ti )
ti 1 ti

t

0

g

v
t

cd
v(ti ) 2
m

Finite Difference Approximation

(from Calculus)
(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
(rearrange)

v(ti 1 )

v(ti )

g

cd
v(ti ) 2 ti
m

1

ti

Recursion
relation

 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).
t (s)

v (m/s)

0

0

2

19.6200

4

36.4137

6

46.2983

8

50.1802

10

51.3123

12

v

51.6008

Terminal velocity
(numerical solution)

(analytical solution)

51.6938

(for t=2 s)

t
Conservation Laws
 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=const

E is conserved.
For example: Consider a current junction in a circuit:
I1

 Current in and out must be constant.
junction

(conservation of charge)

I2

I1+ I2 = I3 + I4

I3

 Can be applied to mass, flow, energy etc.

I4
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 .
Matlab Fundamentals
 Command window: to enter commands and data.
 Graphics window: to plot graphics.
 Edit window: create and edit M-files.

Command window:
 Can be operated just like a calculator
>> 55-16
ans=
39
 Define a scalar value
>> a=4
a=
4

 Assignments can be suppressed by semicolon (;)
>> a=4;
(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;
a=
4

(MATLAB treats names case-sensitive , i.e. a is not same as A in above
example)
 Can assign complex values as MATLAB handles complex arithmetic
automatically:
>> x=2+i*4
x=
2.0000 + 4.0000i
 Predefined variables:

>> pi
ans=
3.1416
If you desire more precision

>> format long
>> pi
ans=
3.14159265358979
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]
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]’
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]
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:
>> who
Your variables are:
A

a

ans

b

x
 If you want more detail:
>> whos
Name Size
A
3x3
a
1x5
ans
1x1
b
5x1
x
1x1
(complex)
Grand total

Bytes
72
40
8
40
16

Class
double
double
double
double
double

array
array
array
array
array

is 21 elements using 176 bytes

 To see an individual element in an array:
>> b(4)
ans=
8
>> A(2,3)
ans=
6
 Some predefined matrices are very useful.
>> E= zeros(2,3)
E=
0
0
0
0
>> u=ones(1,3)

0
0

u=
1

1

1

 Colon (:) operator is very useful to generating arrays:
>> t=1:5
t=
1

2

3

4

5

If you want increment other than 1, then you type:
>> t= 1:0.5:3
t=
1.0000

1.5000

2.000 2.500

3.0000
 Negative increments can also be defined:
>> t= 10: -1: 5
t=
10
9

8

7

6

5

 Colon (:) can also be used to select individual rows:
>> A (2,:)
ans=
4

5

6

returns the second row of the matrix.
 We can also use colon (:) to extract a series of elements from an array
>> t(2:4)
ans=
9

8

7

Second through fourth elements are returned.
Mathematical Operations:
 The common operators, in order of priority
^

Exponentiation

-

Negation

* /

Multiplication and Division



Left division (in matrix algebra)

+ -

Addition and Subtraction

>> y = pi/4;
>> y ^ 2.45
ans=
0.5533
 To override the priorities use paranthesis:
>> y

=

y =

16

(-4) ^ 2
 The real superiority of MATLAB comes in to carry out vector/matrix operations.
Inner product (dot product) of two vectors:
>> a*b
ans=
110
Multiply vector with matrices
>> a = [ 1 2 3];
>> a*A
ans=
30
36
42
Multiply matrices
>> A*A
ans=
30
36
66
81
102
126

42
96
150

A^2 will return the same result.
 If the inner dimensions are not matched, you get an error message:
>> A*a
??? 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
ans=
1
16
49

4
25
64

9
36
81
Built-in Functions:
 MATLAB is very rich in predefined functions (e.g., sqrt, abs, sin,
cos, acos, round, ceil, floor, sum, sort, min, max,

mean,…)
For a list of elementary functions:
>> help elfun
 They operate directly on matrix quantities.
>> log (A)
ans=
0
1.3863
1.9456

0.6931
1.6094
2.0794

1.0986
1.7918
2.1972
Graphics:

 Consider plotting time-versus-velocity for the falling object in air. The
solution to the problem was:
v(t )

gm
tanh
cd

gcd
t
m

 First need to define the time array:
>> t=[0:2:20]’;
This will define time (t) as 0,2,4..20. Total number of elements:
>> length(t)
ans=
11
 Assign values to the parameters:

>> g = 9.81 ; m = 68.1

;

cd=0.25 ;

 Now calculate (v):
>> v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
 To plot t versus t:
>> plot(t,v)
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)
>> grid
 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
>> plot(t,v)
>> 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

answer C
 Step 5: Output the value for C
 Step 6: End the calculation

The same algorithm using a flowchart
Start

Input
A
Input
B
Add A and B
Call the result C
Output
C
end
Flowcharts:
 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.

Monopoly flowchart
Flowchart Symbols
Terminal

Start and End of a program

Flowlines

Flow of the logic

Process

Calculations or data manıpulations

Input/Output

Input or output of data and information

Decision

Comparison, question, or decision that
determines alternative paths to be
followed.

On-page
connector

marks where the flow ends at one spot
on a page and continues at another spot.

Off-page
connector

Marks where the algorithms ends on one
page and continues at another
Computer Programming

 It is the comprehensive process of
(problem  algorithm  coding executables)

Algorithms:
 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,

flowcharts, etc.
 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!)
Pseudocodes:
 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
algorithm.

 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.
Example 1:

Example 2:
Flowchart

Pseudocode
Structured programming:
 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.
Modular 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.
 Top-down design.
 Coupling among modules are minimal.
Programming with Matlab
M-files:

 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.
Script 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:
t=[0:2:20]’;
g = 9.81 ; m = 68.1 ;
cd=0.25 ;
v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
plot(t,v)
title (‘A falling object in air’)
xlabel (t in second)
ylabel (v in meter per second)
grid
This script can be saved as an .m file and be executed at once in command
window.
Function files:

 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)
% Inputs
% t(nx1) = time (nx1) in second
% m = mass of the object (kg)
% cd = drag coefficient (kg/m)
% Output
% v(nx1) = downward velocity (m/s)
g = 9.81 ; % acceleration of gravity
v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
return
Structured programming:
 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
Relational Operators
==

Equal

~=

Not equal

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

Más contenido relacionado

La actualidad más candente

Secent method
Secent methodSecent method
Secent method
ritu1806
 
Direct Methods to Solve Linear Equations Systems
Direct Methods to Solve Linear Equations SystemsDirect Methods to Solve Linear Equations Systems
Direct Methods to Solve Linear Equations Systems
Lizeth Paola Barrero
 

La actualidad más candente (20)

Es272 ch5b
Es272 ch5bEs272 ch5b
Es272 ch5b
 
Non linear curve fitting
Non linear curve fitting Non linear curve fitting
Non linear curve fitting
 
Chapter 3: Linear Systems and Matrices - Part 2/Slides
Chapter 3: Linear Systems and Matrices - Part 2/SlidesChapter 3: Linear Systems and Matrices - Part 2/Slides
Chapter 3: Linear Systems and Matrices - Part 2/Slides
 
Chapter 3: Linear Systems and Matrices - Part 3/Slides
Chapter 3: Linear Systems and Matrices - Part 3/SlidesChapter 3: Linear Systems and Matrices - Part 3/Slides
Chapter 3: Linear Systems and Matrices - Part 3/Slides
 
Chapter 3: Linear Systems and Matrices - Part 1/Slides
Chapter 3: Linear Systems and Matrices - Part 1/SlidesChapter 3: Linear Systems and Matrices - Part 1/Slides
Chapter 3: Linear Systems and Matrices - Part 1/Slides
 
Numerical method-Picards,Taylor and Curve Fitting.
Numerical method-Picards,Taylor and Curve Fitting.Numerical method-Picards,Taylor and Curve Fitting.
Numerical method-Picards,Taylor and Curve Fitting.
 
Applications of numerical methods
Applications of numerical methodsApplications of numerical methods
Applications of numerical methods
 
Numerical Method 2
Numerical Method 2Numerical Method 2
Numerical Method 2
 
Secent method
Secent methodSecent method
Secent method
 
Numerical Methods
Numerical MethodsNumerical Methods
Numerical Methods
 
Polynomials and Curve Fitting in MATLAB
Polynomials and Curve Fitting in MATLABPolynomials and Curve Fitting in MATLAB
Polynomials and Curve Fitting in MATLAB
 
Matlab
MatlabMatlab
Matlab
 
MATLAB - Aplication of Arrays and Matrices in Electrical Systems
MATLAB - Aplication of Arrays and Matrices in Electrical SystemsMATLAB - Aplication of Arrays and Matrices in Electrical Systems
MATLAB - Aplication of Arrays and Matrices in Electrical Systems
 
MATLAB - Arrays and Matrices
MATLAB - Arrays and MatricesMATLAB - Arrays and Matrices
MATLAB - Arrays and Matrices
 
Direct Methods to Solve Linear Equations Systems
Direct Methods to Solve Linear Equations SystemsDirect Methods to Solve Linear Equations Systems
Direct Methods to Solve Linear Equations Systems
 
Presentation on Solution to non linear equations
Presentation on Solution to non linear equationsPresentation on Solution to non linear equations
Presentation on Solution to non linear equations
 
Applied numerical methods lec5
Applied numerical methods lec5Applied numerical methods lec5
Applied numerical methods lec5
 
Unit5
Unit5Unit5
Unit5
 
Lesson 8
Lesson 8Lesson 8
Lesson 8
 
NUMERICAL & STATISTICAL METHODS FOR COMPUTER ENGINEERING
NUMERICAL & STATISTICAL METHODS FOR COMPUTER ENGINEERING NUMERICAL & STATISTICAL METHODS FOR COMPUTER ENGINEERING
NUMERICAL & STATISTICAL METHODS FOR COMPUTER ENGINEERING
 

Destacado (6)

phd thesis presentation
phd thesis presentationphd thesis presentation
phd thesis presentation
 
Mathematical modeling
Mathematical modelingMathematical modeling
Mathematical modeling
 
Curve fitting - Lecture Notes
Curve fitting - Lecture NotesCurve fitting - Lecture Notes
Curve fitting - Lecture Notes
 
Chapter 14 Part I
Chapter 14 Part IChapter 14 Part I
Chapter 14 Part I
 
case study of curve fitting
case study of curve fittingcase study of curve fitting
case study of curve fitting
 
metode numerik kurva fitting dan regresi
metode numerik kurva fitting dan regresimetode numerik kurva fitting dan regresi
metode numerik kurva fitting dan regresi
 

Similar a Es272 ch1

Similar a Es272 ch1 (20)

Matlab1
Matlab1Matlab1
Matlab1
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
Tutorial2
Tutorial2Tutorial2
Tutorial2
 
Programming with matlab session 1
Programming with matlab session 1Programming with matlab session 1
Programming with matlab session 1
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
 
1.1Introduction to matlab.pptx
1.1Introduction to matlab.pptx1.1Introduction to matlab.pptx
1.1Introduction to matlab.pptx
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Matlab
MatlabMatlab
Matlab
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab-free course by Mohd Esa
Matlab-free course by Mohd EsaMatlab-free course by Mohd Esa
Matlab-free course by Mohd Esa
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
 
An Introduction to MATLAB with Worked Examples
An Introduction to MATLAB with Worked ExamplesAn Introduction to MATLAB with Worked Examples
An Introduction to MATLAB with Worked Examples
 
Mmc manual
Mmc manualMmc manual
Mmc manual
 
1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx
 
Matlab ch1 intro
Matlab ch1 introMatlab ch1 intro
Matlab ch1 intro
 
Matlab booklet
Matlab bookletMatlab booklet
Matlab booklet
 

Último

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Es272 ch1

  • 1. Chapter 1: Introduction – A Simple Mathematical Model – Conservation Laws – MATLAB Fundamentals – Computer Programming – Programming with Matlab
  • 2. A simple Mathematical Model Problem of a falling object in air: cd v 2 FD Fg= Force of gravity FD=Drag force m=mass v(t)= Velocity of the object cd= Drag coefficient m Fg mg FD ma m Newton’s 2nd law: Fnet Fg mg cd v 2 dv dt g cd 2 v m m dv dt dv dt (Equation of motion) v v(t ) An Ordinary Differential Equation (ODE) Need to solve for v(t)
  • 3. Analytical Solution: dv dt g cd 2 v m Initial condition: The object is initially at rest (using Calculus) v v(t ) gm tanh cd t 0 ; v 0 gcd t m Terminal velocity t (s) v (m/s) 0 0 2 18.7292 4 33.1118 6 42.0762 8 46.9575 10 49.4214 12 50.6175 51.6938 t
  • 4. Numerical Solution: dv dt g cd 2 v m Reformulate the problem so that it can be solved by arithmetic operations dv dt dv dt lim v t v(ti 1 ) v(ti ) ti 1 ti v(ti 1 ) v(ti ) ti 1 ti t 0 g v t cd v(ti ) 2 m Finite Difference Approximation (from Calculus) (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
  • 5. (rearrange) v(ti 1 ) v(ti ) g cd v(ti ) 2 ti m 1 ti Recursion relation  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). t (s) v (m/s) 0 0 2 19.6200 4 36.4137 6 46.2983 8 50.1802 10 51.3123 12 v 51.6008 Terminal velocity (numerical solution) (analytical solution) 51.6938 (for t=2 s) t
  • 6. Conservation Laws  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=const E is conserved.
  • 7. For example: Consider a current junction in a circuit: I1  Current in and out must be constant. junction (conservation of charge) I2 I1+ I2 = I3 + I4 I3  Can be applied to mass, flow, energy etc. I4 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 .
  • 8. Matlab Fundamentals  Command window: to enter commands and data.  Graphics window: to plot graphics.  Edit window: create and edit M-files. Command window:  Can be operated just like a calculator >> 55-16 ans= 39  Define a scalar value >> a=4 a= 4  Assignments can be suppressed by semicolon (;) >> a=4; (just stored in memory w/o displaying)
  • 9.  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; a= 4 (MATLAB treats names case-sensitive , i.e. a is not same as A in above example)  Can assign complex values as MATLAB handles complex arithmetic automatically: >> x=2+i*4 x= 2.0000 + 4.0000i  Predefined variables: >> pi ans= 3.1416
  • 10. If you desire more precision >> format long >> pi ans= 3.14159265358979 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
  • 11.  Square brackets ( [ ] ) are used to define an array in command mode. >> a= [ 1 2 3 4 5] 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]’ b= 2 4 6 8 10
  • 12.  A matrix of values can be assigned as follows: >> A = [1 2 3 ; 4 5 6; 7 8 9] 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: >> who Your variables are: A a ans b x
  • 13.  If you want more detail: >> whos Name Size A 3x3 a 1x5 ans 1x1 b 5x1 x 1x1 (complex) Grand total Bytes 72 40 8 40 16 Class double double double double double array array array array array is 21 elements using 176 bytes  To see an individual element in an array: >> b(4) ans= 8 >> A(2,3) ans= 6
  • 14.  Some predefined matrices are very useful. >> E= zeros(2,3) E= 0 0 0 0 >> u=ones(1,3) 0 0 u= 1 1 1  Colon (:) operator is very useful to generating arrays: >> t=1:5 t= 1 2 3 4 5 If you want increment other than 1, then you type: >> t= 1:0.5:3 t= 1.0000 1.5000 2.000 2.500 3.0000
  • 15.  Negative increments can also be defined: >> t= 10: -1: 5 t= 10 9 8 7 6 5  Colon (:) can also be used to select individual rows: >> A (2,:) ans= 4 5 6 returns the second row of the matrix.  We can also use colon (:) to extract a series of elements from an array >> t(2:4) ans= 9 8 7 Second through fourth elements are returned.
  • 16. Mathematical Operations:  The common operators, in order of priority ^ Exponentiation - Negation * / Multiplication and Division Left division (in matrix algebra) + - Addition and Subtraction >> y = pi/4; >> y ^ 2.45 ans= 0.5533  To override the priorities use paranthesis: >> y = y = 16 (-4) ^ 2
  • 17.  The real superiority of MATLAB comes in to carry out vector/matrix operations. Inner product (dot product) of two vectors: >> a*b ans= 110 Multiply vector with matrices >> a = [ 1 2 3]; >> a*A ans= 30 36 42 Multiply matrices >> A*A ans= 30 36 66 81 102 126 42 96 150 A^2 will return the same result.
  • 18.  If the inner dimensions are not matched, you get an error message: >> A*a ??? 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 ans= 1 16 49 4 25 64 9 36 81
  • 19. Built-in Functions:  MATLAB is very rich in predefined functions (e.g., sqrt, abs, sin, cos, acos, round, ceil, floor, sum, sort, min, max, mean,…) For a list of elementary functions: >> help elfun  They operate directly on matrix quantities. >> log (A) ans= 0 1.3863 1.9456 0.6931 1.6094 2.0794 1.0986 1.7918 2.1972
  • 20. Graphics:  Consider plotting time-versus-velocity for the falling object in air. The solution to the problem was: v(t ) gm tanh cd gcd t m  First need to define the time array: >> t=[0:2:20]’; This will define time (t) as 0,2,4..20. Total number of elements: >> length(t) ans= 11  Assign values to the parameters: >> g = 9.81 ; m = 68.1 ; cd=0.25 ;  Now calculate (v): >> v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
  • 21.  To plot t versus t: >> plot(t,v) 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) >> grid  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 >> plot(t,v) >> hold on >> plot (t,v,’o’) >> hold off
  • 22. 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 answer C  Step 5: Output the value for C  Step 6: End the calculation The same algorithm using a flowchart Start Input A Input B Add A and B Call the result C Output C end
  • 23. Flowcharts:  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. Monopoly flowchart
  • 24.
  • 25. Flowchart Symbols Terminal Start and End of a program Flowlines Flow of the logic Process Calculations or data manıpulations Input/Output Input or output of data and information Decision Comparison, question, or decision that determines alternative paths to be followed. On-page connector marks where the flow ends at one spot on a page and continues at another spot. Off-page connector Marks where the algorithms ends on one page and continues at another
  • 26. Computer Programming  It is the comprehensive process of (problem  algorithm  coding executables) Algorithms:  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, flowcharts, etc.  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.
  • 27. Flowchart example for calculating factorial N (N!)
  • 28. Pseudocodes:  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 algorithm.  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.
  • 31. Structured programming:  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. Modular 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.  Top-down design.  Coupling among modules are minimal.
  • 32. Programming with Matlab M-files:  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.
  • 33. Script 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: t=[0:2:20]’; g = 9.81 ; m = 68.1 ; cd=0.25 ; v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t); plot(t,v) title (‘A falling object in air’) xlabel (t in second) ylabel (v in meter per second) grid This script can be saved as an .m file and be executed at once in command window.
  • 34. Function files:  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) % Inputs % t(nx1) = time (nx1) in second % m = mass of the object (kg) % cd = drag coefficient (kg/m) % Output % v(nx1) = downward velocity (m/s) g = 9.81 ; % acceleration of gravity v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t); return
  • 35. Structured programming:  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
  • 36. Relational Operators == Equal ~= Not equal < Less than > Greater than <= Less than or equal to >= Greater than or equal to