Introduction to Matlab 7
Download
Report
Transcript Introduction to Matlab 7
Introduction to Matlab 7
Part II
Daniel Baur
ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften
ETH Hönggerberg / HCI F128 – Zürich
E-Mail: [email protected]
http://www.morbidelli-group.ethz.ch/education/snm/Matlab
Daniel Baur / Introduction to Matlab Part II
1
Review of vectors
Vector handling
Row vector:
Column vector:
Vector with defined spacing:
Vector with even spacing:
Transpose:
a
a
b
c
d
e
f
=
=
=
=
=
=
=
[1 2 3];
[1, 2, 3];
[1; 2; 3];
0:5:100; (or 0:100)
linspace(0, 100, 21);
logspace(0, 3, 25);
e';
Daniel Baur / Introduction to Matlab Part II
2
Review of matrices
Creating matrices
Direct:
Matrix of zeros:
Matrix of ones:
Random matrix:
Normally distributed:
A = [1 2 3; 4 5 6; 7 8 9];
B = zeros(3,2);
C = ones(3,2);
R = rand(3,2);
RD = randn(2,3);
Matrix characteristics
Size
Largest dimension
Number of elements
[nRows, nColumns] = size(A);
nColumns = size(A,2);
maxDim = length(A);
nElements = numel(A);
Creating vectors
Single argument calls create a square matrix, therefore use
commands like v = ones(3,1); to create vectors
Daniel Baur / Introduction to Matlab Part II
3
Review of accessing elements
Vectors (a = (1:5).^2;)
a(3);
a([1, 3]);
a(2:4);
a(end);
a(:);
Single element:
Multiple elemets:
Range of elements:
Last element:
All elements:
a(:) always returns a
Matrices (A = a'*a;)
Single element:
Submatrix:
Entire row / column
Multiple rows / columns
Last element of row / column
All elements as column vector
column vector.
A(1,3);
A(2:3,2:3);
A(2,:);
A(:,3);
A([2, 3],[1, 3, 5]);
A(2,end);
A(end,3);
b = A(:);
Daniel Baur / Introduction to Matlab Part I
4
Review of matrix operations
Create a Matrix
A = rand(3);
Operations with constants
B = 2*A
C = 2+A
Matrix addition; Transpose
D = A+C
D = D'
Deleting rows / columns
C(3,:) = [];
D(:,2) = [];
Matrix multiplication
C*D
D*C
Not commutative!
A^2
Element-by-element operations
A.^2
E = 2.^A;
Ei,j = 2^Ai,j
sqrt(A)
Functions using matrices
sqrtm(A)
sqrtm(A)^2
inv(A)
Daniel Baur / Introduction to Matlab Part II
5
Review of matrix operations (continued)
Matrix properties
sum(A,dim);
det(A);
inv(A);
eigs(A);
More creation options and reshaping
B = [ones(4); diag(1:4); eye(4)];
B = reshape(B, 24, 6);
C = repmat(B, 1, 3);
Solution of linear algebraic systems
A = rand(3);
b = rand(3,1);
x = A\b;
Do not use
x = inv(A)*b!
Daniel Baur / Introduction to Matlab Part II
6
M-Files
What is an m-file?
An m-file is a collection of commands. It is equivalent to programs,
functions, subroutines, modules, etc. in other programming
languages. It can even contain entire class definitions.
What can I use it for?
Creating a permanent record of what you are doing
Experimenting on an algorithm
Writing utilities and whole programs
What types of m-files are there?
Script m-file: No input and output. Operates on workspace variables.
Function m-file: Starts with the function key-word, accepts inputs
and gives outputs. All variables are local.
Class m-file: Contains the classdef key-word, used in object
oriented programming.
Daniel Baur / Introduction to Matlab Part II
7
Example of a Script
Problem definition
v = 1e-17*ones(100,1); sum(v)
v1 = [v;1]; sum(v1)-1
v2 = [1;v]; sum(v2)-1
Create the «mysum» script
(In Matlab:) File New M-File
clear all; close all;
v = 1e-17*ones(100,1);
v1 = [v;1];
s = sum(v1);
s-1
Avoid reserved words and
built-in function names
(In Editor:) File Save As... mysum.m
Check the directory path!
Daniel Baur / Introduction to Matlab Part II
8
Example of a Script (Continued)
You should see
The editor has found unusual syntax
or even a syntax error here!
Mouse-over to see what is the issue.
How to run the script?
From the command window (check the path!)
From the editor (press Run button or use Debug Run or press F5)
Daniel Baur / Introduction to Matlab Part II
9
Relational and logical operators
Relational operators are straight forward in Matlab:
<, >, <=, >=, ==, ~=
The NOT operator is the tilde symbol «~»
For the logical operators AND and OR, two kinds exist:
&&, ||
&, |
Operators with short-circuiting (scalars only)
Operators for element-by-element comparisons
Logical operators return logical types
Example of how short-circuitung operators work:
In the context of if and while, both
kinds of operators short-circuit.
Daniel Baur / Introduction to Matlab Part I
10
Relational and logical operators (continued)
Example of element-by-element comparison:
All numbers other than
0 evaluate to TRUE
Compare entire matrices with isequal(A,B)
Daniel Baur / Introduction to Matlab Part I
11
Relational and logical Operators (continued)
There are a some more operators that you can use:
any(A,dim);
all(A,dim);
xor(A,B);
isnumeric(A);
isfinite(A);
True if at least one element is ≠ 0
True if all elements are ≠ 0
True if one is = 0 and the other is ≠ 0
True if A is a numerical type
True for each element if it is neither NaN nor inf
Indexing is possible through logical variable types (try it!)
A(A<0);
All elements < 0
A(isfinite(A)); All elements except NaN and inf
A(A == B);
All elements that are equal to their counterpart
You can even edit elements directly
this way
Daniel Baur / Introduction to Matlab Part I
12
For-loops in Matlab
General form of for-loops:
Example:
If Matlab gets stuck in a loop (or
any
other
calculation),
use
ctrl+c to terminate the program.
Daniel Baur / Introduction to Matlab Part II
13
Examples with for-loops
Try these:
Loops are almost always slower
than matrix / vector calculations!
Daniel Baur / Introduction to Matlab Part II
14
While-loops in Matlab
General form of while-loops:
while expression
statements;
end
The statements are executed as long as the expression is
true (or ≠ 0)
The statements are executed an indefinite number of times
It is good practice to limit the number
of iterations (eg. while n < nmax)
Daniel Baur / Introduction to Matlab Part II
15
Examples of loops
Try the following:
Vectorize your operations
and use built-in functions.
If you must use a loop,
preallocate your variables.
Daniel Baur / Introduction to Matlab Part II
16
Exercise
1. Create the matrix A(5,5) with random elements between -2 and 2
(type help rand to figure out how the function works)
2. Set all negative elements of A to 1.5 (use logical indexing!)
3. Create a matrix B consisting of the 2nd and 3rd column of A
4. Create a matrix C consisting of the 1st and 4th row of A
5. Calculate D = A∙B∙C. What is the size of D?
6. Add D+A = E. Multiply the transpose of E with B to create F.
7. Create the matrix G so that Gi,j = 2+2*Ci,j2 / Fj,i
8. Create an equally spaced row vector b with 5 elements from 3 to 38
9. Find the solution of the linear system A∙x = b’
10. Find the solution of y∙A = b
11. Compute the 2-norm of x
12. Find the vector v representing the 2-norm of each column of A
13. Find the values of the series s 0, s s v 2
0
Daniel Baur / Introduction to Matlab Part II
i
i 1
i
17
Solutions (one Possibility)
Daniel Baur / Introduction to Matlab Part II
18
Controlling program flow
The if block has the following structure
if expression
statements;
elseif expression
statements;
else
statements;
end
Example
The elseif and else
clauses are optional.
Daniel Baur / Introduction to Matlab Part II
19
Controlling program flow (Continued)
The switch block does multiple comparisons at once
switch variable
case expression
statements;
case expression
statements;
...
otherwise
statements;
end
Example
Message identifier
Error message
Daniel Baur / Introduction to Matlab Part II
20
Controlling program flow (Continued)
Other commands for controlling program flow are:
break;
continue;
return;
Exits the current loop
Immediately goes to the next iteration
Terminates the entire program / function
Daniel Baur / Introduction to Matlab Part II
21
Controlling program flow (Continued)
The try block checks for errors occuring during execution
try
statements;
catch err
statements;
end
If an error occurs in the try block, the catch block is
executed immediately instead of continuing
Example
Daniel Baur / Introduction to Matlab Part II
22
Data type «struct»
What is a struct?
Structs are arrays with a property called «fields». Fields hold
different kinds of data and are accessed by dots. Structs are very
useful for bundling different kinds of information.
Example (try it out!)
comp(1).name = 'water';
comp(1).Mw = 18.02;
comp(1).density = 1;
comp(2).name = 'ethanol';
comp(2).Mw = 46.06;
comp(2).density = 0.789;
Daniel Baur / Introduction to Matlab Part II
23
Data type «struct»
comp(1)
comp(2)
comp(3)
.name
= 'water'
.name
= 'ethanol'
.name
= ...
.MW
= 18.02
.MW
= 46.06
.MW
= ...
.density
= 1
.density
= 0.789
.density
= ...
.Antoine
= [ 8.07;
.Antoine
= [ 8.20;
.Antoine
= ...
1730;
1643;
233];
230];
comp
(1,n)
struct
Daniel Baur / Introduction to Matlab Part II
24
Exercise
Create a new m-file called quadratic_roots.m
Implement the following algorithm
If b > 0
b b 2 4ac
c
x2
; x1
2a
ax2
Elseif b < 0
b b 2 4ac
c
x1
; x2
2a
ax1
Else
1/2
c
x1 x2
a
Daniel Baur / Introduction to Matlab Part II
25
Possible Solution
Daniel Baur / Introduction to Matlab Part II
26