Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

64
math403 Introductory MATLAB Zheng Chen Spring 2010 1

Transcript of Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

Page 1: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

1

math403Introductory MATLAB

Zheng ChenSpring 2010

Page 2: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

2

Environment of matlab

• 3 windows:• Command window• History window• Editor window

Page 3: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

3

Executable file form

• Files of form .m for functions and main programs

• All files to solve one problem should be in one directory

• Pwd, cd, ls, cd.., cp, mkdir, rmdir, • Help while

Page 4: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

4

Matlab as a calculator

• 2+3/4.0*5+(-2)^3+ log(3.4)• Sin(pi/4);• 1.2+3i• Format of numbers• Format long• Format short

Page 5: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

5

variables

• X=3-2^3;• Assign the value to x• Y=x+4; assign the value to y• Pi=3.1415…, eps=2.2204e-16• I, j have the value sqrt(-1);

Page 6: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

6

Built in functions

• Trig• Log• Sqrt(x);• exp

Page 7: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

7

vectors

• Row vector: V=[1,2 3]• U=[-5, 6, 12]• V+/-U;• W=[7,8];• Cd=[2*w, 3V];• V(2); it is the same as V(1,2);• Column vector w=[7;8;9]• W(2) =w(2,1);

Page 8: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

8

Colon notations

• V=1:8;• V=3:7;• V=.32:0.1:-2

• Extracting• A=[1,2 ,3 ,4,5 ,6 ,7 ,8]• What is the b=A(4:7) and c=A(1:3:7)

Page 9: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

9

transpose

• Row vector to column vector or vice verse• General matrices with size m*n• W’ is of size n*m if W has size m*n

Page 10: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

10

Scalar product of vectors u*v

• Scalar product:• u=[a, b, c], v=[l, m,n]’• In matlab, u*v=al+bm+cn; it is a number• sqrt(u*u’) ; and norm(u);• Recall what is the meaning of norm?

Page 11: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

11

Dot product .*

• u=[a, b, c], v=[l, m, n]• u.*v is a vector with the same size as u and v;• simply multiply the corresponding elements of

two vectors• u.*v named as dot product

Page 12: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

12

Dot Division ./

• ./ is defined to give element by element division

• u=[a, b, c], v=[l, m, n];• u./v=[a/l , b/m, c/n];• Try 1./[2, 3, 4];

Page 13: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

13

Dot Power of Arrays (.^)

• u = [ 10, -11, 12];• u.^2;• .* ; ./ ; .^ mean component wise

operations

Page 14: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

14

Functions applied to arrays

• u = [ 10, 11, 12];• sin(u), sqrt(u);

Page 15: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

15

Matrices –Two-Dimensional Arrays

• Input: a=[1 2 3; 5 6 7]; • or a= [1 2 3 5 6 7]; b=[1 2; 3 4; 5 6];• size(a) = dimensions of matrix, that is, number

of rows and number of columns• size(a) is itself one vector with size 1, 2.

Page 16: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

16

Special Matrices

• ones(2,3); zeros(2,3); eye(3);• d = [-3 4 2], D = diag(d);• given F = [0 1 8 7; 3 -2 -4 2; 4 2 1 1], find diag(F);• c=[0 1; 3 -2; 4 2]; x=[8;-4;1]; find g = [c x] (extra column) find h=[c; k] (stacked c and k) where k=[7 8]• Try spy(F), grid for fun

Page 17: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

17

Extracting Bits of Matrices

• J =[ 1 2 3 45 6 7 89 0 3 11];

Find J(2,4); J(:,2); J(3,:); J(1:2, 2:4);

Page 18: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

18

Dot product of matrices (.*)

• The dot product works as for vectors: corresponding elements are multiplied together

Page 19: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

19

Matrix{vector products

• An (m x n) matrix times an (n x k) matrix is a (m x k) matrix.

• A = [5 7 9; 1 -3 -7]; x = [8; -4; 1]; find A*x• Practice: choose two matrices A and B, find A*B, (A*B)’ and B’*A’• Practice: choose matrices A, B and C, find

A*(B*C) and (A*B)*C

Page 20: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

20

Sparse matrices

• >> i = [1, 3, 5]; j = [2,3,4];• >> v = [10 11 12];• >> S = sparse (i,j,v); T=full(S);• save memory, only save diagonal elements• >> n = 5;• >> l = -(2:n+1)'; d = (1:n )'; u = ((n+1):-1:2)';• >> B = spdiags([l d u],-1:1,n,n);• >> full(B) (%l,d,u are column vectors)

Page 21: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

21

System of linear equations

• Ax=b• x = A \ b; (“\backslash")• try inv(A) and inv(A)*b

Page 22: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

22

Overdetermined system of linear equations

• generally speaking, Ax=b has no solution when # of equations > # of unknowns

• r = Ax-b;• Least square solution: make r minimum• normal equations:

Cx = d; where C = A’A and d = A’b• matlab gives the solution in its routine library x = A\b

Page 23: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

23

• A =[0.0000 0.0000; 0.0001 0.0000; 0.0013 0.0000; 0.0030 0.0000; 0.0075 0.0001]• b = [5 50 500 1000 2000];• X=A\b’

Page 24: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

24

For Loop

• for i=1:10 disp([i i^2 i^3]) end • for i=1:4 for j=1:4 disp([i j i^2+j^2]) end end

Page 25: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

25

example

• for i=1:4 for j=i:4 disp([i j i^2+j^2]) end end

Page 26: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

26

example

• sum=0.0; bigsum=0.0;• for i=i:1000

bigsum =bigsum+1/i; end

for i=i:1000 sum =sum+1/i^2;

end disp([ bigsum sum])

Page 27: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

27

Questions

• What is the sum of 1+1/2+1/3+… until the term where 1/n<=10^(-3) ?

• How many terms we have in the expansion of 1+1/2+1/3+… if the partial sum is just >=2 ?

Page 28: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

28

While loop

• % format long i = 1; % start the counter at 1 total = 0; % initialize the sum while(1/i >= 1e-3) % condition total = total + 1/i; % update the sum i=i+1; end disp([i 1/i total]) % display the number of

loops, 1/i, and the current sum

Page 29: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

29

While loop(condition changed)

i = 1; % start the counter at 1 total = 0; % initialize the sum while(total <= 2) % condition changed total = total + 1/i % update the sum i= i+1 end % disp([I total]) disp([i-2 total-1/(i-1)]) % display the

number of terms, and the final sum

Page 30: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

30

Example to use while loop

• Problem: what is the greatest value of n that can be used in the sum

1+(1/2)^2+ (½)^2 +… + (1/n)^2and get a value of less than 2?

S = 1; n = 1;while S+ (1/(n+1))^2 < 2

n = n+1; S = S + (1/n)^2;end

• [n, S]

Page 31: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

31

Logicals

• true = 1, false = 0• If x<1.0 elseif

Page 32: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

32

if...then...else...end

• if logical test 1 commands to be executed if test 1 is true elseif logical test 2 commands to be executed if test 2 is true

but test 1 is false ... end

Page 33: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

33

• R = input('What is your name:','s') if R=='cuana'

'today your hw: read the notes'else 'bye'end

Page 34: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

34

• Problem: find out all triples of integers, at most 20, as the 3 sides of one right triangle,like 3, 4, 5;

Page 35: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

35

Using for and if loop

for i=1:20 for j=i:20 for k=j:20 if k^2==i^2+j^2 [i, j, k] end end endend

Page 36: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

36

Functions defined by yourself

• % Compute the area of a triangle whose• % sides have length a, b and c.• % Inputs: a,b,c: Lengths of sides• % Output: A: area of triangle• % Usage: Area = area(2,3,4); function [A] = area(a,b,c) s = (a+b+c)/2; A = sqrt(s*(s-a)*(s-b)*(s-c));

Page 37: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

37

• Problem: find the are of one triangle with given 3 numbers, you need to decide whether these three numbers can be the 3 sides of one triangle.

for example, 3, 4 and 5 are 3 sides of one triangle, 3, 4 and 8 are not 3 sides of one triangle.

given a<=b<=c , criteria for them to be 3 sides of a triangle: c<a+b & a> c-b.

Page 38: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

38

Functions countinue

• function [A] =triValue(a,b,c) s = (a+b+c)/2; A = sqrt(s*(s-a)*(s-b)*(s-c));• save the file as triValue.m• Another function: two results are provided function [cir, A] =triValue(a,b,c) s = (a+b+c)/2; cir=s*2; A = sqrt(s*(s-a)*(s-b)*(s-c));

Page 39: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

39

• function area=tri_area(a, b, c)dd=min([a,b,c]);aa=max([a,b,c]);b=a+b+c-dd-aa;a=aa; c=dd;if c>(a-b) & b+c>a 'the given numbers are 3 sides of one triangle, and the area is: ' s=(a+b+c)/2; area=sqrt(s*(s-a)*(s-b)*(s-c))else 'the given numbers are not 3 sides of one triangle'end

Page 40: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

40

Another example of functions

• Fibonnaci sequence is dened by

n=3,4, … input: integrer output:

1 2 1 20; 0; n n nf f f f f

nf

Page 41: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

41

Method 1: File Fib1.mfunction f = Fib1(n)

% Returns the nth number in the% Fibonacci sequence.F=zeros(1,n+1);F(2) = 1;for i = 3:n+1F(i) = F(i-1) + F(i-2);endf = F(n);

Page 42: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

42

function f = Fib2(n)% Returns the nth number in the Fibonacci sequence.if n==1

f = 0;elseif n==2

f = 1;else

f1 = 0; f2 = 1;for i = 2:n-1

f = f1 + f2;f1=f2; f2 = f;

endend

Page 43: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

43

Recursive programming

function f = Fib3(n)% Returns the nth number in the% Fibonacci sequence.

if n==1f = 0;elseif n==2f = 1;elsef = Fib3(n-1) + Fib3(n-2);end

Page 44: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

44

% The final version uses matrix powers. The vector y has two components,

% Returns the nth number in the Fibonacci sequence.function f = Fib4(n)

A = [0 1;1 1];y = A^n*[1;0];f=y(1);

1

n

n

fy

f

Page 45: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

45

Which method you like most?

• Which algorithm is most efficient?• method 3(recursive programming) no efficient

Page 46: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

46

More Built-in Functions

• x = pi*(-1:3), round(x)• Try fix(x); floor(x); ceil(x); sign(x), rem(x,3)• A = [1:3; 4:6; 7:9];• s = sum(A), ss = sum(sum(A));• x = [1.3 -2.4 0 2.3], max(x), max(max(A));

min(x);• y = rand, Y = rand(2,3)

Page 47: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

47

Use rand

% simulates "n" throws of a pair of dice% Input: n, the number of throws% Output: an n times 2 matrix, each row% referring to one throw.% Useage: T = dice(3)

function [d] = dice(n)d = floor(1 + 6*rand(n,2));

%% end of dice

Page 48: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

48

Function ‘find’

• A = [ -2 3 4 4; 0 5 -1 6; 6 8 0 1];• k = find(A==0); To interpret the result we have to recognize That “find" first reshapes A into a column vector; this is

equivalent to numbering the elements of A by columns as in

1 4 7 102 5 8 113 6 9 12Now try n = find(A <= 0); and A(n)

Page 49: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

49

• A=[1 4 7 10 2 5 8 11

3 6 9 12];n = find(A <= 0);Try A(n);Try m = find( A' == 0);

Page 50: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

50

plot

• linspace (a,b,n) producing n+1 points;• N = 10; h = 1/N; x = 0:h:1; doing the same.• X=linspace(0,1,110);• y = sin(3*pi*x);• Plot(x,y)

Page 51: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

51

Plot with title

• Using string inside of ‘ ’title('Graph of y = sin(3pi x)')xlabel('x axis')ylabel('y-axis')gridoff (% off grid)

Page 52: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

52

Plot-line styles & color• plot(x,y,'w-');• Colors line stylesy yellow . pointm magenta o circlec cyan x x-markR red + plusg green - solidb blue * starw white : dottedk black -. dashdot

-- dashed• Try plot(x,y,'b*‘)

Page 53: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

53

• plot(x,y,'w-'), hold on• plot(x,y,'gx'), hold off• save or print the graphs in .eps form

• clf, N = 100; h = 1/N; x = 0:h:1;• y = sin(3*pi*x); plot(x,y)• axis([-0.5 1.5 -1.2 1.2]), grid

Page 54: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

54

subplot

for n = 1:8 subplot(2,4,n), plot(x,sin(n*pi*x))end

Page 55: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

55

Characters, Strings and Text

• %The ability to process text in numerical processing is useful for the input and output of data to the screen or to disk-les.

• The assignment, t1 = ‘abc ‘, t2 = ‘efghijk‘;• t3 = [t1,t2];• T3 is abcdefghijk;

Page 56: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

56

Conversion among strings, integers and real numbers

• 'str2num‘, 'int2tr' and 'num2str‘;• Example: N = 11:20; ncube = N.^2; ['The perfect squares of integere from ',

int2str(ncube(1)),' to ', int2str(ncube(10)), ' are in the following: ']

num2str(ncube)% fprintf(num2str(ncube)) % disp(ncube)

Page 57: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

57

Plotting Surfaces

• Plot the surface of f(x; y) = (x -3)^2-(y-2)^2 for 2<= x <= 4 and 1<= y<= 3.

[X,Y] = meshgrid(2:.5:4, 1:.5:3);Z = (X-3).^2-(Y-2).^2;mesh(X,Y,Z)

Page 58: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

58

f=-xyexp(-2(x^2+y^2)), -2<=x,y<=2; [X,Y] = meshgrid(-2:.1:2,-2:.2:2);f = -X.*Y.*exp(-2*(X.^2+Y.^2)); figure (1) mesh(X,Y,f), xlabel('x'), ylabel('y'), gridfigure (2), contour(X,Y,f) xlabel('x'), ylabel('y'), grid, hold on

Page 59: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

59

To locate the maxima of the “f” values on the grid

fmax = max(max(f))kmax = find(f==fmax)Pos = [X(kmax), Y(kmax)]plot(X(kmax),Y(kmax),'*') text(X(kmax),Y(kmax),' Maximum‘)

% the ‘find’ above gives the index numbers of matrices X and Y

Page 60: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

60

timing

% Matlab allows the timing of sections of code by providing the functions tic and toc.

ticx=0;for j=1:1000

x=x+j^3;

end toc

Page 61: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

61

Reading and Writing Data Files

In a file 'table.dat' , data is as following:1 562 583 654 67fid = fopen('table.dat','r'); % action is reading, file identfier fid a = fscanf(fid,'%1d%2d'); % one with 1 digits and one with 2 digits fclose(fid); % close the file with file identier fid.A = reshape(a,2,5)';. % change the size of a to 2times5

Page 62: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

62

HW and projects

• Pob1: using the mid point method to find the approximate solution of any equation in one interval for example: 4x+3sin(pi/2*x)-5=0 in [0,1]

• Pob2: using Newton’s method to find the approximate solution of any equation in one interval for example: 4x+3sin(pi/2*x)-5=0 in [0,1]

Page 63: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

63

• Pob3: find the determinant value of any given matrix of size n by n. (your program should ask people in input the matrix row by row)

• Pob4: using echelon method to find the solution of any linear system with 2 unknowns; your program should ask people to input the coefficients of the system and the program should be valid to any such system, in other words, your program should contain 3 possible situations of solutions.

Page 64: Math403 Introductory MATLAB Zheng Chen Spring 2010 1.

64

• Given 3 points, find the distance from the third point to the line though the other two points. Your program should ask the people input the three points or a matrix of size 3by2