introduction to matlab session 2 simopekka vänskä, thl department of mathematics and statistics...

21
Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Upload: bryce-dalton

Post on 06-Jan-2018

232 views

Category:

Documents


2 download

DESCRIPTION

Basic commands

TRANSCRIPT

Page 1: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLABSession 2

Simopekka Vänskä, THLDepartment of Mathematics and StatisticsUniversity of Helsinki 2010

Page 2: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

Contents of this courseSession 1

General Matrices M-files

Session 3 My functions + stings, cells Controlling program flow

Session 2Some matrix commandsLogical expressions Graphics 1

Session 4 Function functions

Session 5 Graphics 2 More linear algebra Starting homework

Page 3: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Basic commands

Page 4: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

MATLAB commands/functions

Genaral syntax:[OUTPUT parameters] = functionname(INPUT parameters);

Functions do not change the INPUT parameters

Number of parameters can variate

Help function: >> help functionname

FunctionINPUT

parametersOUTPUT

parameters

Page 5: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

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 03 2

Some common functions:sin, cos, tan, asin, acos, atanexp, log, sqrtabs, conj, imag, real, anglefix, floor, ceil, round, sign

For more, see >> help elfun

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)

Page 6: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

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, cumprodmean, median, std, min, maxsort

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)

Page 7: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

Polynomials and interpolationFinding 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.

Page 8: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Logical expressions

Page 9: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

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

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

Page 10: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

FIND find(X) returns the indeces of

non-zero (true) entries of X>> I = find(X)

returns the vector indeces

>> [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.

Try the following>> X = rand(4)>> I = find(X<0.4)>> [I,J] = find(X<0.4)

>> Y = X(X<0.4)>> I = find(X<0.4)>> X(I)

Page 11: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Graphics 1 - PLOT

Page 12: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

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).

Page 13: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

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: >> 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.

Remark: Text within ’ ’ is a string A string is a char array, a

char valued matrix, e.g.

>> J = ’the Lord’

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-’)

Page 14: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

Basic plot editing commandsExample

>> 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.

Page 15: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

Figure and subplot

>> figure(n) sets figure n as current figure or, creates figure n if it does

not exist

Example: Numbering subplots.

>> subplot(m,n,k) Breaks the figure window to

subfigures with m raws and n

columns and sets current

axis to axis number k For more, see >> help subplot

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))

1 2 3

654

Page 16: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

ProblemsSession 2

Page 17: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

ProblemsWrite 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,4 in the same figure but with different colors.

Page 18: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

Problems3. 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.

Page 19: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

Introduction to MATLAB - Session 2

Mortality fitting6. 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.

Page 20: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

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.

Page 21: Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010

>> quit

…to exit MATLAB.