introduction to matlab d. heslop and m. schulz. why matlab? if calculations have to be repeated many...
TRANSCRIPT
Introduction to MATLABIntroduction to MATLAB
D. Heslop and M. Schulz
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
Starting MATLABStarting MATLAB
Display WindowsDisplay Windows
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
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)
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.
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)
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
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
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.
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
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 [ ]
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
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 (,)
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
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
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
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
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
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
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
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
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
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
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.
» 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…
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
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
Elementary MathElementary Math
• Mathematical Functions
• Logical Operators
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)
Help on Math FunctionsHelp on Math Functions
• Elementary functions (sin, cos, sqrt, exp, log10)
help elfun
• Advanced functions (bessel, beta, gamma, erf)
help specfun
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
Graphics in MATLAB
2-D Graphics – The plot Command
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
…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')
…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])
Multiple GraphsMultiple Graphs
x = 0:pi/100:2*pi;
y1=sin(x);
y2=sin(x+pi/2);
plot(x,y1,x,y2)
grid on
……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!)
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)
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)
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
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.
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’)
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
3-D Surface Plotting3-D Surface Plottingcontourf plot3 waterfall contour3 mesh surf
Specialized Plotting RoutinesSpecialized Plotting Routinesbar bar3h hist area pie3 rose
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.
Creating an M-FileCreating an M-File
The M-File EditorThe M-File Editor
Save M File to your working
directory
Running an M-FileRunning an M-File
Set „current directory“ to your working directory
Running an M-FileRunning an M-File
Use right mouse buttonto assess menu
……Result of Running the M-FileResult of Running the M-File
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)
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
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
Bathtub Model 1Bathtub Model 1
• What is the modeled water volume after 30
minutes?
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
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]')
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
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
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?
Modeled Water Volume in BathtubModeled Water Volume in Bathtub
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
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”
Modeled Water Volume in Bathtub withModeled Water Volume in Bathtub withVolume ConstraintVolume Constraint
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
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.
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“
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)
Note: format statement must be enclosed in single quotes (‘)
Text output:'Sample text\n' text output + new line
Formatting ExamplesFormatting Examples
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
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
fclose(fid)
Closing a Text FileClosing a Text File
File Identifier (a number)
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)
fprintf(fid, '%2.0f %5.1f\n', time(i+1), vol(i+1))
fprintf(fid, '%2.0f %4.2E\n', time(i+1), vol(i+1))
Additional Material…Additional Material…
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
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 ,
» 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