introduction to matlab d. heslop and m. schulz. why matlab? if calculations have to be repeated many...

82
Introduction to MATLAB Introduction to MATLAB D. Heslop and M. Schulz

Upload: adam-nelson

Post on 27-Dec-2015

232 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Introduction to MATLABIntroduction to MATLAB

D. Heslop and M. Schulz

Page 2: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Why MATLAB?Why MATLAB?

• If calculations have to be repeated many times a

computer is the ideal tool for such boring task

• MATLAB combines the power of a classical

programming language for computation with

numerous extra tools, especially for visualization

• MATLAB stands for MATrix LABoratory The system

was originally designed to make matrix computation

particularly easy

Page 3: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Starting MATLABStarting MATLAB

Page 4: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Display WindowsDisplay Windows

Page 5: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Calculations at the Command LineCalculations at the Command Line

» a = 2;

» b = 5;

» a^b

ans =

32

» x = 5/2*pi;

» y = sin(x)

y =

1

» z = asin(y)

z =

1.5708

» a = 2;

» b = 5;

» a^b

ans =

32

» x = 5/2*pi;

» y = sin(x)

y =

1

» z = asin(y)

z =

1.5708

Results assigned to “ans” if name not specified

() parentheses for function inputs

Semicolon suppresses screen output

MATLAB as a calculator Assigning Variables» -5/(4.8+5.32)^2ans = -0.0488» (3+4i)*(3-4i)ans = 25» cos(pi/2)ans = 6.1230e-017» exp(acos(0.3))ans = 3.5470

» -5/(4.8+5.32)^2ans = -0.0488» (3+4i)*(3-4i)ans = 25» cos(pi/2)ans = 6.1230e-017» exp(acos(0.3))ans = 3.5470

Page 6: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Algebraic and Assignment OperatorsAlgebraic and Assignment Operators

Addition + a+b

Subtraction - a-b

Multiplication * a*b

Division / a/b

Power ^ a^b

Assignment = a=b (assign b to a)

Page 7: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Variables in MATLABVariables in MATLAB

• Variable names:

– must start with a letter

– may contain only letters, digits, and the underscore “_”

– are case sensitive, i.e. one & OnE are different variables

– must differ in the first 63 characters

• Assignment statement:

– Variable = number;

– Variable = expression;

Example:

>> a = 1234;

>> a = 1234

a =

1234

NOTE: when a semi-colon ”;” is placed at the end of a command, the result is not displayed.

Page 8: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Pre-Defined VariablesPre-Defined Variables

ans default variable name for the result

pi = 3.1415926…………

i or j imaginary unit (i = j = square root of -1)

Inf or inf infinity

NaN or nan not-a-number

eps smallest difference between 2 numbers (2.2204e-016)

realmin smallest usable positive real number (2.2251e-308)

realmax largest usable positive real number (1.7977e+308)

Page 9: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Commands Involving VariablesCommands Involving Variables

who lists the names of defined variables

whos lists the names and sizes of defined variables

clear clears all variables

clear name clears the variable name

clc clear command window

Page 10: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Getting Help

MATLAB has a very comprehensive online help system

• help – lists all the help topic

• help topic – provides help for the specified topic

help elfun – lists available elementary functions

• help command – provides help for the specified command

help sin – usage of the sine function

• lookfor keyword – Search all commands for keyword

• demo – Lists tutorial demos

Note: Use doc instead of help for browser-type help interface

Page 11: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

MATLAB MatricesMATLAB Matrices

• MATLAB treats all variables as matrices.

• A vector (or array) is a special form of a matrix

and contains only one row OR one column.

• A scalar is a matrix with only one row AND one

column.

Page 12: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

MATLAB MatricesMATLAB Matrices

A matrix with only one row AND one column is a scalar.

A scalar can be created in MATLAB as follows:

» a = 23

a =

23

Page 13: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

MATLAB MatricesMATLAB Matrices

A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas):

» rowvec = [12, 14, 63]rowvec = 12 14 63

For simplicity, the commas may be skipped (note spaces):» rowvec = [12 14 63]rowvec = 12 14 63

Use square brackets [ ]

Page 14: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

MATLAB MatricesMATLAB Matrices

A matrix with only one column is called a column vector.

A column vector can be created in MATLAB as follows

(note the semicolons):

» colvec = [13; 45; -2]

colvec =

13

45

-2

Page 15: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

MATLAB MatricesMATLAB Matrices

A matrix can be created in MATLAB as follows (note

spaces AND semicolons):

» matrix = [1 2 3; 4 5 6; 7 8 9]

matrix =

1 2 3

4 5 6

7 8 9

Row separatorsemicolon (;)

Column separatorspace / comma (,)

Page 16: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

The Matrix in MATLABThe Matrix in MATLAB

4 10 1 6 2

8 1.2 9 4 25

7.2 5 7 1 11

0 0.5 4 5 56

23 83 13 0 10

1

2

Rows (m) 3

4

5

Columns(n)

1 2 3 4 5

A = A (2,4)

Rectangular Matrix:Scalar: 1-by-1 arrayVector: m-by-1 array

1-by-n arrayMatrix: m-by-n array

Page 17: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Extracting a Sub-MatrixExtracting a Sub-Matrix

A portion of a matrix can be extracted and stored in a

smaller matrix by specifying the names of both matrices

and the rows and columns to extract. The syntax is:

sub_matrix = matrix(r1:r2,c1:c2);

r1, r2 beginning and ending rows

c1, c2 beginning and ending columns

Page 18: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

4 10 1 6 2

8 1.2 9 4 25

7.2 5 7 1 11

0 0.5 4 5 56

23 83 13 0 10

1

2

3

4

5

1 2 3 4 5

A =

A(3,1)

A(1:5,5)A(:,5)

A(4:5,2:3)

Sub-Matrices in MATLABSub-Matrices in MATLAB

Page 19: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Addressing Vector ElementsAddressing Vector Elements

• A vector element is addressed by an integer index enclosed in

parentheses

• Example:

>> x=[10 20 30 40 50 60];

>> x(3)

ans =

30

Note: MATLAB index starts at 1

3rd element of vector x

Page 20: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Addressing Vector ElementsAddressing Vector ElementsThe colon notation may be used to address a block of elements:

(start : increment : end)

start is the starting index

increment is the amount to add to each successive index

end is the ending index

A shortened format (start : end) may be used if increment is 1

Example:

>> x=[10 20 30 40 50 60];

>> x(1:2:6)

ans =

10 30 50

Page 21: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Useful Commands for VectorsUseful Commands for Vectors

x = start:end create row vector x starting with start, counting

by one, ending at end

x = start:increment:end create row vector x starting with start, counting

by increment, ending at or before end

x =

linspace(start,end,number)

create row vector x starting with start, ending at

end, having number elements

length(x) returns the length of vector x

y = x’ transpose of vector x

Page 22: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Scalar-Matrix OperationsScalar-Matrix Operations

• For addition, subtraction, multiplication, and division of a matrix

by a scalar, the operation is applied to all elements of the matrix

• Example:

>> A = [ 1 2; 3 4]

A =

1 2

3 4

>> B = 2*A – 1

B =

1 3

5 7

Each element in the matrix A is multiplied by 2, then subtracted by 1

Page 23: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Element-by-Element OperationsElement-by-Element Operations

• For element-wise multiplication, division and exponentiation of

matrices the corresponding operator must be preceded by a

dot

• Example:

>> x = [ 1 2 3 ];

>> y = [ 4 5 6 ];

>> z = x .* yz =

4 10 18

Each element in x is multiplied by the corresponding element in y

Page 24: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Element-by-Element OperationsElement-by-Element Operations

Operation Algebraic Form MATLAB

Addition a + b a + b

Subtraction a – b a – b

Multiplication a ∙ b a .* b

Division a b a ./ b

Exponentiation ab a .^ b

Note: Matrix addition and subtraction is element-wise by definition

Page 25: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Useful Commands for MatricesUseful Commands for Matrices

zeros(n)zeros(m,n)

ones(n)ones(m,n)

size (A)

length(A)

returns an n x n matrix of zerosreturns an m x n matrix of zeros

returns an n x n matrix of onesreturns an m x n matrix of ones

for an m x n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix

returns the larger of the number of rows or columns in A

Page 26: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

More Matrix Commands

Transpose B = A’

Identity Matrix eye(n) returns an n x n identity matrixeye(m,n) returns an m x n matrix with ones on the main diagonal and zeros elsewhere.

Addition and subtraction C = A + BC = A – B

Scalar Multiplication B = A, where is a scalar.

Matrix Multiplication C = A*B

Matrix Inverse B = inv(A), A must be a square matrix in this case.rank (A) returns the rank of the matrix A.

Matrix Powers B = A.^2 squares each element in the matrixC = A * A computes A*A, and A must be a square matrix.

Determinant det (A), and A must be a square matrix.

A, B, C are matrices, and m, n, are scalars.

Page 27: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

» w=[1 2;3 4] + 5w = 6 7 8 9» x = 1:5

x = 1 2 3 4 5» y = 2:-0.5:0

y = 2.0000 1.5000 1.0000 0.5000 0 » z = ones(2,4)

z =

1 1 1 1

1 1 1 1

» w=[1 2;3 4] + 5w = 6 7 8 9» x = 1:5

x = 1 2 3 4 5» y = 2:-0.5:0

y = 2.0000 1.5000 1.0000 0.5000 0 » z = ones(2,4)

z =

1 1 1 1

1 1 1 1

Scalar expansion

Creating sequences:colon operator (:)

Utility functions for creating matrices

Test yourself…Test yourself…

Page 28: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Deleting Columns and Rows in a Matrix Deleting Columns and Rows in a Matrix

>> A=[1 2 3; 4 5 6; 7 8 9]

A =

1 2 3 4 5 6 7 8 9

>> A(:,2)=[]

A =

1 3 4 6 7 9

>> A=[1 2 3; 4 5 6; 7 8 9]

A =

1 2 3 4 5 6 7 8 9

>> A(:,2)=[]

A =

1 3 4 6 7 9

>> A(2,:)=[]

A =

1 2 3 7 8 9

>> A(2,:)=[]

A =

1 2 3 7 8 9

delete 2nd col. delete 2nd row

Page 29: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Matrix, Vector and Array

• In programming jargon, an n-dimensional field of values is called an array

• Vector 1-dimensional array

• Matrix 2-dimensional array

• Arrays can be multidimensional 1 0 0 0

0 1 0 0

0 0 1 0

0 0 0 1

Page N

Page 1

0 0 0 0

0 0 0 0

0 0 0 0

0 0 0 0

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

1 1 1 1

1 2 3 4

1 3 6 10

1 4 10 20

A(r,c,p)

row column page

Page 30: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Elementary MathElementary Math

• Mathematical Functions

• Logical Operators

Page 31: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Elementary Math FunctionsElementary Math Functions

•abs,sign absolute value and sign functions

•sin,cos,asin,acos… trigonometric functions

•exp exponential (base e)

•log,log10 natural and base-10 logarithm

•sqrt square root function

•round round to the nearest integer (whole number)

Page 32: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Help on Math FunctionsHelp on Math Functions

• Elementary functions (sin, cos, sqrt, exp, log10)

help elfun

• Advanced functions (bessel, beta, gamma, erf)

help specfun

Page 33: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Logical Operations

» A = [-2 10 30 -11 Inf 31];

» each_pos = A >= 0

each_pos =

0 1 1 0 1 1

» A = [-2 10 30 -11 Inf 31];

» each_pos = A >= 0

each_pos =

0 1 1 0 1 1

== equal to

> greater than

< less than

>= greater or equal

<= less or equal

~ not

& and

| or

== equal to

> greater than

< less than

>= greater or equal

<= less or equal

~ not

& and

| or

Note: 1 = True0 = False

Page 34: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Graphics in MATLAB

Page 35: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

2-D Graphics – The plot Command

x = 0:pi/100:2*pi;

y = sin(x);

plot(x,y)

Page 36: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

…Adding Labels

x = 0:pi/100:2*pi;

y = sin(x);

plot(x,y)

xlabel('x [rad]')

ylabel('Sine of x')

title('Plot of the Sine Function')

Page 37: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

…Changing Axis Limits

Syntax: axis ([xmin xmax ymin ymax])

x = 0:pi/100:2*pi;

y = sin(x);

plot(x,y)

xlabel('x [rad]')

ylabel('Sine of x')

title('Plot of the Sine Function')

axis ([0 7 -1.1 1.1])

Page 38: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Multiple GraphsMultiple Graphs

x = 0:pi/100:2*pi;

y1=sin(x);

y2=sin(x+pi/2);

plot(x,y1,x,y2)

grid on

Page 39: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

……Adding a LegendAdding a Legend

x = 0:pi/100:2*pi;

y1=sin(x);

y2=sin(x+pi/2);

plot(x,y1,x,y2)

grid on

legend('sin(x)','sin(x+\pi/2)')

moveable object (mouse!)

Page 40: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Multiple PlotsMultiple Plots

x = 0:pi/100:2*pi;

y1=sin(x);

y2=sin(x+pi/2);

subplot(2,1,1)

plot(x,y1)

subplot(2,1,2)

plot(x,y2)

Syntax: subplot(rows,cols,index)

Page 41: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

SubplotsSubplots

Syntax:

»subplot(2,2,1);

» …

»subplot(2,2,2)

» ...

»subplot(2,2,3)

» ...

»subplot(2,2,4)

» ...

»subplot(2,2,1);

» …

»subplot(2,2,2)

» ...

»subplot(2,2,3)

» ...

»subplot(2,2,4)

» ...

subplot(rows,cols,index)subplot(rows,cols,index)

Page 42: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Adding Curves to an Existing PlotAdding Curves to an Existing Plot

Use the hold command to add lines/points to an existing plot.– hold on – retain existing axes, add new curves to current

axes. Axes are rescaled when necessary.– hold off – release the current figure window for new plots

Page 43: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Multiple PlotsMultiple Plots

x = 0:pi/100:2*pi;

y1=sin(x);

y2=sin(x+pi/2);

subplot(2,1,1)

plot(x,y1)

subplot(2,1,2)

plot(x,y2)

hold on

plot(x,y1)

By default, both lines have the same color.

Page 44: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Multiple PlotsMultiple Plots

x = 0:pi/100:2*pi;

y1=sin(x);

y2=sin(x+pi/2);

subplot(2,1,1)

plot(x,y1)

subplot(2,1,2)

plot(x,y2)

hold on

plot(x,y1,’r’)

Page 45: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Plot QualifiersPlot Qualifiers

Symbol Color

y yellow

m magenta

c cyan

r red

g green

b blue

w white

k black

Symbol Marker

.

o

x

+ +

*

s □

d ◊

v

^

h hexagram

Color

Symbol Line Style

– solid line

: dotted line

–. dash-dot line

– – dashed line

Marker Type Line Style

To find out more: doc plot and doc linespec

Page 46: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

3-D Surface Plotting3-D Surface Plottingcontourf plot3 waterfall contour3 mesh surf

Page 47: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Specialized Plotting RoutinesSpecialized Plotting Routinesbar bar3h hist area pie3 rose

Page 48: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

M-FilesM-Files

• An M-file is a text file that consists a group of MATLAB

commands

• MATLAB executes the commands in an M-file exactly

as if they were entered in the MATLAB command

window

So far, we have executed the commands in the command window. A more practical way is to create an M-file.

Page 49: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Creating an M-FileCreating an M-File

Page 50: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

The M-File EditorThe M-File Editor

Save M File to your working

directory

Page 51: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Running an M-FileRunning an M-File

Set „current directory“ to your working directory

Page 52: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Running an M-FileRunning an M-File

Use right mouse buttonto assess menu

Page 53: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

……Result of Running the M-FileResult of Running the M-File

Page 54: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub ModelBathtub Model

• Simple model for the filling of a bathtub (with the

plug in it):

New volume = the old volume + what's been added

• Or, mathematically: Vnew = Vold + Q * t

Inflow per unit time (t)

Page 55: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Numerical Solution of the Bathtub Equation

1 0

2 1

1n n

t t

t t

t t

V V tQ

V V tQ

V V tQ

“Initial Condition”

Time

Page 56: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Repeated Action – “For Loops”Repeated Action – “For Loops”

for variable = expression

commands

end

Example

for t = 1:5000

y(t) = sin (2*pi*t/10);

end

Page 57: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub Model 1Bathtub Model 1

• What is the modeled water volume after 30

minutes?

Page 58: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub Model 1Bathtub Model 1n = 30; % no. of timestepsdt = 1.0; % unit time interval [min.]q = 25.0; % inflow rate [liter per min.]%% initialize volume; start with empty bathtubvol(1) = 0.0; % water volume [liter]%% initialize time arraytime(1) = 0.0;%% loop over timefor i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt;end%% show volume evolution as function of timeplot (time, vol)xlabel('Time [min]')ylabel('Water Volume [liter]')

Define constants

Page 59: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub Model 1Bathtub Model 1

Define array variables

n = 30; % no. of timestepsdt = 1.0; % unit time interval [min.]q = 25.0; % inflow rate [liter per min.]%% initialize volume; start with empty bathtubvol(1) = 0.0; % water volume [liter]%% initialize time arraytime(1) = 0.0;%% loop over timefor i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt;end%% show volume evolution as function of timeplot (time, vol)xlabel('Time [min]')ylabel('Water Volume [liter]')

Page 60: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub Model 1Bathtub Model 1n = 30; % no. of timestepsdt = 1.0; % unit time interval [min.]q = 25.0; % inflow rate [liter per min.]%% initialize volume; start with empty bathtubvol(1) = 0.0; % water volume [liter]%% initialize time arraytime(1) = 0.0;%% loop over timefor i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt;end%% show volume evolution as function of timeplot (time, vol)xlabel('Time [min]')ylabel('Water Volume [liter]')

Use array variable in for-loop

Page 61: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub Model 1Bathtub Model 1n = 30; % no. of timestepsdt = 1.0; % unit time interval [min.]q = 25.0; % inflow rate [liter per min.]%% initialize volume; start with empty bathtubvol(1) = 0.0; % water volume [liter]%% initialize time arraytime(1) = 0.0;%% loop over timefor i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt;end%% show volume evolution as function of timeplot (time, vol)xlabel('Time [min]')ylabel('Water Volume [liter]')

Display result

Page 62: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub Model 1Bathtub Model 1

• What is the modeled water volume after 30

minutes?

• How would the volume change if time goes on?

Does this make sense?

Page 63: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Modeled Water Volume in BathtubModeled Water Volume in Bathtub

Page 64: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub Model 2Bathtub Model 2

• Limit the water volume in the bathtub at the maximum

possible level

• If more water flows in, it spills over

• Control Statement: If (water volume is larger than max.

volume) then volume is set to max. volume

if (vol > maxvol)

vol = maxvol

end

Condition (logical expression)

Action statement carried out if condition is true

Page 65: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub Model 2Bathtub Model 2n = 30; % no. of timestepsdt = 1.0; % unit time interval [min.]q = 25.0; % inflow rate [liter per min.]maxvol = 500.0; % max. volume that bathtub can hold [liter]%% initialize volume; start with empty bathtubvol(1) = 0.0; % water volume [liter]%% initialize time arraytime(1) = 0.0;%% loop over timefor i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt; if (vol(i+1) > maxvol) vol(i+1) = maxvol; end;end;

Define max. volume

“Spill-over function”

Page 66: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Modeled Water Volume in Bathtub withModeled Water Volume in Bathtub withVolume ConstraintVolume Constraint

Page 67: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

fopen Open a file for output

fprintf Write formatted data to an open file

fclose Close open file

Saving Variables to a Text FileSaving Variables to a Text File

Page 68: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

fid = fopen(filename, mode)

Opening a Text FileOpening a Text File

File Identifier (a variable)

'r‘ Open file for reading (default)

'w‘ Open file, or create new file, for

writing; discard existing

contents

'a‘ Open file, or create new file, for

writing; append data to the end

of the file.

Page 69: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

fid = fopen(filename, mode)

Opening a Text FileOpening a Text File

File Identifier (a variable)

'r‘ Open file for reading (default)

'w‘ Open file, or create new file, for

writing; discard existing

contents

'a‘ Open file, or create new file, for

writing; append data to the end

of the file.

Example: fid = fopen(‘myfile.txt‘, ‘w‘)

File access is in the „Current Directory“

Page 70: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

fprintf(fid, format, variable)

Writing to a Text FileWriting to a Text File

directs printing to file w/ this identifier

variable(s) to be printed

controls alignment, significant digits, field width of the output ( doc fprintf for details)

Page 71: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Note: format statement must be enclosed in single quotes (‘)

Text output:'Sample text\n' text output + new line

Formatting ExamplesFormatting Examples

Page 72: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Note: format statement must be enclosed in single quotes (‘)

Text output:'Sample text\n' text output + new line

Decimal notation'%5.1f\n' e.g. 123.4

% convert number into specified format5 field width incl. decimal point 1 number of decimal placesf use decimal notation

Formatting ExamplesFormatting Examples

Page 73: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Note: format statement must be enclosed in single quotes (‘)

Text output:'Sample text\n' text output + new line

Decimal notation'%5.1f\n' e.g. 123.4

Exponential notation'%5.1E\n' e.g. 123.4E+001

% convert number into specified format5 field width incl. decimal point 1 number of decimal placesE use exponential notation

Formatting ExamplesFormatting Examples

Page 74: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

fclose(fid)

Closing a Text FileClosing a Text File

File Identifier (a number)

Page 75: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Bathtub Model 3Bathtub Model 3% open file for output and write headerfid = fopen('bathtub.txt','w');fprintf(fid, '%% Bathtub Model\n');fprintf(fid, '%% Column 1: Time [min]\n');fprintf(fid, '%% Column 2: Water Volume [liter]\n');%fprintf(fid, '%2.0f %5.1f\n', time(1), vol(1));% loop over time; save output to file for i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt; if (vol(i+1) > maxvol) vol(i+1) = maxvol; end; fprintf(fid, '%2.0f %5.1f\n', time(i+1), vol(i+1));end;...fclose(fid);

Initialize output file

Close file

Save data to file (within loop)

Page 76: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

fprintf(fid, '%2.0f %5.1f\n', time(i+1), vol(i+1))

Page 77: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

fprintf(fid, '%2.0f %4.2E\n', time(i+1), vol(i+1))

Page 78: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring
Page 79: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Additional Material…Additional Material…

Page 80: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Matrix ConcatenationMatrix Concatenation

» a=[1 2;3 4]

a =

1 2

3 4

» cat_a=[a 2*a; 3*a 4*a; 5*a 6*a]cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24

» a=[1 2;3 4]

a =

1 2

3 4

» cat_a=[a 2*a; 3*a 4*a; 5*a 6*a]cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24

Use [ ] to combine existing arrays as matrix “elements”

Row separator:semicolon (;)

Column separator:space / comma (,)

Use square brackets [ ]

Note: The resulting matrix must be rectangular

4*a

Page 81: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

Character Array (String)• Created using single quote delimiter (')

• Each character is a separate matrix element

• Indexing same as for numeric arrays

» str1 = 'Hi there,'

str1 =

Hi there,

» str2 = 'Isn''t MATLAB great?'

str2 =

Isn't MATLAB great?

» str1 = 'Hi there,'

str1 =

Hi there,

» str2 = 'Isn''t MATLAB great?'

str2 =

Isn't MATLAB great?

1x9 vectorstr1 = H i t h e r e ,

Page 82: Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring

» str1 ='Hi there,';

» str2='Everyone!';

» new_str1=[str1, ' ', str2]

new_str1 =Hi there, Everyone! » str3 = 'Isn''t MATLAB great?';

» new_str2=[new_str1; str3]new_str2 =Hi there, Everyone!Isn't MATLAB great?

» str1 ='Hi there,';

» str2='Everyone!';

» new_str1=[str1, ' ', str2]

new_str1 =Hi there, Everyone! » str3 = 'Isn''t MATLAB great?';

» new_str2=[new_str1; str3]new_str2 =Hi there, Everyone!Isn't MATLAB great?

1x19 vector

1x9 vectors

String Array ConcatenationString Array Concatenation

Using [ ] operator:Each row must be same length

Column separator:space / comma (,)

Row separator:semicolon (;)

For strings of different length:•strvcat

» new_str3 = strvcat(str1, str3)new_str3 =Hi there, Isn't MATLAB great?

» new_str3 = strvcat(str1, str3)new_str3 =Hi there, Isn't MATLAB great?

2x19 matrix

2x19 matrix(“space padded”)

1x19 vectors