Introduction to MATLAB Session 2 - University of Helsinki Confluence

advertisement
Introduction to MATLAB
Session 2
Simopekka Vänskä, THL
Department of Mathematics and Statistics
University of Helsinki 2010
Contents of this course
Session 1
 General
Session 4
 Function functions
 Matrices
 M-files
Session 5
 Graphics 2
Session 2
Some matrix commands
Logical expressions
Graphics 1
Session 3
 My functions + stings, cells
 Controlling program flow
Introduction to MATLAB - Session 2
 More linear algebra
 Starting homework
Basic commands
MATLAB commands/functions
INPUT
parameters
Function
OUTPUT
parameters
 Genaral syntax:
[OUTPUT parameters] = functionname(INPUT parameters);
 Functions do not change the INPUT parameters
 Number of parameters can variate
 Help function: >> help functionname
Introduction to MATLAB - Session 2
Some elementwise functions
 Operate on each element of
the input matrix A:
size(OUTPUT) = size(A)
 Examples
>> A = [1 0; pi pi/2];
>> sin(A)
ans =
0.8415
0
0.0000 1.0000
>> round(A)
ans =
1 0
3 2
 Some common functions:
sin, cos, tan, asin, acos, atan
exp, log, sqrt
abs, conj, imag, real, angle
fix, floor, ceil, round, sign
 For more, see >> help elfun
Introduction to MATLAB - Session 2
Try the following:
>> asin(1)
>> asin(5)
>> exp(1)
>> exp(709)
>> exp(710)
>> log(exp(50))
>> v = [-1.2, 0.5, 1.2];
>> round(v)
>> fix(v)
>> floor(v)
>> ceil(v)
>> sign(v)
>> sign(0)
Some columnwise functions
 Operate on each column of the
input matrix A:
size(OUTPUT) = size(A,2)
 Exception: raw vectors
 Example
>> A = [1 0; pi pi/2];
>> sum(A)
ans =
4.1416 1.5708
 Operating dimension choosable
>> sum(A,2)
ans =
1.0000
4.7124
 Examples
sum, prod, cumsum, cumprod
mean, median, std, min, max
sort
Introduction to MATLAB - Session 2
Try the following
>> A = [1 3 3; 2 2 4]
>> mean(A)
>> mean(A’)
>> min(A)
>> [X,I] = min(A)
>> cumsum(A)
>> cumprod(A)
>> sort(A)
Polynomials and interpolation
 Finding the roots of the polynomial:
roots(C) returns the roots of the polynomial whose
coefficients are given by vector C
 P(x) = C(1)*X^N + ... + C(N)*X + C(N+1).
 Recall: Polynomial of degree n has exactly n complex roots.
 Polynomial fitting:
polyfit(x,y,n) fits a polynomial of degree n to the data
points (X,Y) and returns the coefficients.
 Simple interpolation interp1
interp1(X,Y,X0) interpolates the data points (X,Y) to
given interpolation points X0.
 interp2, interp3 for 2- and 3-dimensional data.
Introduction to MATLAB - Session 2
Logical expressions
Logical expressions and functions
 Logical datatype
 False: 0
 True: 1 (nonzero)
 Relational operations:
== equal
~= not equal
>=, >, <=,<
 Logical operations:
& (and), | (or), ~ (not),
xor, any, all
 isempty, isnan
Introduction to MATLAB - Session 2
Try the following
>> v = 1:5;
>> v==3
>> (v>=2)&(v<5)
>> (v>=2).*(v<5)
>> f = v==3
>> f = (v==3)
>> whos f
>> all(f)
>> any(f)
>> ~f
>> g = (v>=2)
>> xor(g,f)
>> g|f
FIND
 find(X) returns the indeces of
non-zero (true) entries of X
>> I = find(X)
returns the vector indeces
Try the following
>> X = rand(4)
>> I = find(X<0.4)
>> [I,J] = find(X<0.4)
>> [I,J] = find(X)
returns the matrix indeces
>> I = find(X,k)
return the k first indeces
 Restricting vectors with find.
Optional notations
>> X(find(X<4))
and
>> X(X<4)
are the same.
Introduction to MATLAB - Session 2
>> Y = X(X<0.4)
>> I = find(X<0.4)
>> X(I)
Graphics 1 - PLOT
No. 1 plotting command - plot
Basic idea:
 Command plot(x,y) connects the points
(x(1),y(1)), (x(2),y(2)) , …, (x(n),y(n))
with lines.
 Into current figure and axis (if does not exist, creates).
 For matrices X and Y:
plot(X,Y) acts columnwise (exceptions exist).
Introduction to MATLAB - Session 2
Plot line properties
 Basic line properties
 Plot symbols: ., o, x, +, *, …
 Color: b, g, r, c,…
 Line style: -, :, -., -For more, see >> help plot
 How to use:
 Remark:
 Text within ’ ’ is a string
 A string is a char array, a
char valued matrix, e.g.
>> J = ’the Lord’
>> plot(x,y,’bo’)
 Multiple data in one plot:
>> plot(x1,y1,’bo’,x2,y2,’r’,…)
OR use hold command:
>> plot(x1,y1,’bo’)
>> hold on
>> plot(x2,y2,’r’)
>> hold off
 Additional properties:
Graphics 2 session.
Introduction to MATLAB - Session 2
Try the following
>> x = (-3:.1:3)’;
>> plot(x,exp(x))
>> c = 1:5;
>> plot(x,x.^2*c)
>> plot(x,x,’rx’,x,x+2,’b-’)
Basic plot editing commands
Example
>> plot(x,y,’r’,x0,y0,’bo’)
 Title for the image
>> title(’Linear fit’)
 Labels for the axes
>> xlabel(’Month’)
>> ylabel(’Cases’)
 Setting the axis limits
>> axis([0 6.5 0 15])
 Labeling of the plot lines
>> legend(’fit’,’data’)
Here, an additional property
’Location’ was used:
>> legend(’fit’,’data’,’Location’,’NorthWest’)
OR
move with the mouse in the figure window.
Introduction to MATLAB - Session 2
Figure and subplot
>> subplot(m,n,k)
 Breaks the figure window to
>> figure(n)
 sets figure n as current figure
subfigures with m raws and n
 or, creates figure n if it does
columns and sets current
not exist
axis to axis number k
 For more, see >> help subplot
Example: Numbering subplots.
1
2
3
4
5
6
Introduction to MATLAB - Session 2
Try the following:
>> subplot(1,2,1)
>> plot(rand(3))
>> subplot(2,2,2)
>> plot(rand(10))
>> subplot(2,2,4)
>> plot(0:.1:5,sqrt(0:.1:5))
Problems
Session 2
Problems
Write your solutions to m-files
1. Check how matrix A =
a) [2 0; b) [2 0; c) [-1 0; d) [ 1 1; e) [1 -1; f) [2 1;
0 1];
0 -1];
0 1];
-1 1];
1 1];
0 2];
maps the points
P = [0, 4, 4, 3, 3, 2.5, 2.5, 2, 0, 0;
0, 0, 3, 4, 5, 5, 4.5, 5, 3, 0];
by plotting P and points A*P. To plot P you can use
plot(P(1,:),P(2,:)).
2. Plot functions y=sin(x) and y = cos(x) on interval [0,4p]
in the same figure but with different colors.
Introduction to MATLAB - Session 2
Problems
3. Draw the unit circle in R2.
 Draw the unit circle so that the line is green for x>0 and black
for x<0.
4. Map the unit circle to the ellipse with major axes u =
[2;1], minor axes v = [-1/2;1], and center (1,1). Draw the
ellipse in the same picture with the unit circle.
 Hint: Map linearly and transport.
5. Draw the image of the mapping f: 1 + [-i,i]  C,
a) f(z) = log(z),
b) f(z) = z^2,
in the complex plane. Hint: Real plane.
Introduction to MATLAB - Session 2
Mortality fitting
6. In this exercise we consider mortality in Finland at 2007
(data loaded from Tilastokeskus website).
 Copy kuolleisuus.xls (at the wikipage of the course) to
your working directory. Load it to MATLAB (start your
m-file with M = xlsread(’kuolleisuus.xls’);). The file
contains matrix M with

M(:,1) = age

M(j,2) = mortality for mails at age(j) [1/1000]

M(j,3) = mortality for femails at age(j)
 Fit polynomials of degree 2 and 3 to the mortality data.
 Fit an exponential function to the mortality data, i.e., fit
a polynomial of degree 1 to the log(mortality) –data.
 Present your fit graphically. Use subplots, colors, titles,
legends, and axis labels.
Introduction to MATLAB - Session 2
Computing area
with random points
7. Compute the area of the unit triangle T =
span((0,0),(1,0),(0,1)) with uniformly distributed random
numbers as follows:
 Generate N uniformly distributed random points x
=(x1,x2) in the unit square
 Find the fraction of the points falling in T. Illustrate this
graphically, plot the random points and T. Plot the
points in T and the points out T with different colors.
 Approximate area of T. Test the accuracy with different
number of points N.
Introduction to MATLAB - Session 2
>> quit
…to exit MATLAB.
Download