matlab lesson 5&6: symbolic mathematics & file i/o

44
The Hong Kong Polytechnic University Industrial Centre 1 MatLAB Lesson 5&6: Symbolic Mathematics & File I/O Edward Cheung email: [email protected] Room W311g 2008

Upload: foy

Post on 16-Jan-2016

45 views

Category:

Documents


0 download

DESCRIPTION

MatLAB Lesson 5&6: Symbolic Mathematics & File I/O. Edward Cheung email: [email protected] Room W311g. 2008. Polar Plots. In polar coordinates, the position of a point is given by an angle  and the radius. Polar plot is a plot of angles vs magnitudes for points of a function - PowerPoint PPT Presentation

TRANSCRIPT

The Hong Kong Polytechnic UniversityIndustrial Centre

1

MatLABLesson 5&6: Symbolic Mathematics & File

I/O

Edward Cheung

email: [email protected]

Room W311g

2008

2

Polar Plots

• In polar coordinates, the position of a point is given by an angle and the radius. Polar plot is a plot of angles vs magnitudes for points of a function

Compass plot is a plot of vector emanating from the origin

• The polar command can be used to create polar plots. Usage:- polar(theta, radius, ‘line specifiers’)

• Example:- Plot

>>t=linspace(0,2*pi,200);r=3*cos(0.5*t).^2+t;Polar(t,r)

)

2(cos3 2r 20

3

Equation Solving using the Left Division Operator

• By the left division ‘\’ operator

• Designed for numerical computation & faster than using the inverse; a preference method in MatLab

• Works fine with systems having a unique solution

• Example:-

64982

5327

704126

zyx

zyx

zyx

>> A=[6 12 4;7 -2 3;2 8 -9];

B=[70;5;64];

xyz=A\B

The solution is [3 5 -2]

4

Matrix Plotting

A = 6 12 4 7 -2 3 2 8 -9>> plot(A)>> grid

•Matlab will take each column as a line/axis.

5

Colormap

• A colormap is an m-by-3 matrix of real numbers between 0.0 and 1.0. Each row is an RGB vector that defines one colour. The kth row of the colormap defines the k-th colour, where map(k,:) = [r(k) g(k) b(k)] specifies the intensity of red, green, and blue.

• colormap(map) sets the colormap to the matrix map. colormap('default') sets the current colormap to the default colormap.

• Example:-MATLAB 's default colormap contains 64 colors and the 57th color is red.>>cm = colormap;cm(57,:)ans = 1 0 0

6

Colormap (cont.)

• M-files in ..\toolbox\matlab\graph3d generate a number of colormaps. Each M-file accepts the colormap size as an argument.

• For example,>>colormap(cool(128))

% creates an hsv colormap with 128 colors. If you do not specify a size, MATLAB creates a colormap the same size as the current colormap.

% Demonstration of changing and rotating image colormaps >>imageext

7

Example: cool.m

8

Colormap demonstration

• Example:- MatLab has a sample image call mandrill..\toolbox\matlab\demos\mandrill.mat

>>load mandrill

% noted the map & X

>>image(X)

colormap map

colormap default

% or colormap jet resume to normal

• You can try to change the colormap as in page 43 of the workbook.

9

colorbar

• The colorbar function displays the current colormap, either vertically or horizontally, in the figure window along with the graph.

• Example:- page 44 of the workbook[x,y] = meshgrid([-2:0.2:2]);z = x.*exp(-x.^2-y.^2);surf(x,y,z,gradient(z)) %colour is gradient(z)colorbarcolorbar horiz

10

Formatted Output

• The display command is used to display the elements of a variable without displaying the name of the variable and to display text string. disp(variable_name) or disp(‘string’)

• The fprintf command is used for formatted output fprintf(‘formated text & data’) does not automatically append LF for flexibility in

formatting Same formatting syntax as in C

11

Example – Formatted Output

>> p=0.052;n=100;fname='output.txt';fprintf(1,'The sample size is %d\nwith a %5.1f%%

defective rate.\n',n,100*p);The sample size is 100with a 5.2% defective rate.

>> fprintf(1,'The data is stored in %s.\n',fname);

The data is stored in output.txt.

Example:-> s=sprintf('%f',pi) % write pi to string ss = 3.141593

> sprintf('%s','hello') % print string

12

Output Data to File

• Writing the output to a file require 3 steps:-1. Open a file using fopen

2. Write the output to the file using fprintf

3. Close the file using fclose

>>fid=fopen(‘filename’,’permission’)fid = A scaler value created for file

identificationfclose(fid)

13

Example on Writing Output to a File

• Create a text file called ‘sin.txt’ containing a short table of the sine function:

>>x=0:360;y=[x;sin(x*pi/180)];fid=fopen('sin.txt','wt');fprintf(fid,'%6.2f%12.8f\n',y);fclose(fid);>> type sin.txt % checking

14

Data Input from String

• sscanf reads data from string variable s, convert it according to the specified format string and return a matrix

>>s = '2.7183 3.1416'; % s is a stringA = sscanf(s,'%f') : % A is a vectorA = 2.7183 3.1416>> A(1)ans = 2.7183

15

Formatted Input from File

• fscanf Read formatted data from file

• Usage:- A = fscanf(fid,format) [A,count] = fscanf(fid,format,size)

• Size=n %Read n elements into a column vector.

• Size=inf %Read to the end of the file, resulting in a column vector containing the same number of elements as are in the file.

• Size=[m,n] % Read enough elements to fill an m-by-n matrix, filling the matrix in column order. n can be inf, but not m.

16

Example on Reading Formatted Data from File

>>fid=fopen('earth.txt','r');s=fscanf(fid,'%f %f',[2 inf]);fclose(fid);plot(s(1,:),s(2,:),'.');

•Rewrite for a count of data read:->> fid=fopen('earth.txt','r');[s,count]=fscanf(fid,'%f %f',[2 inf]);countcount = 13840

• ginput enables you to select points from the figure using the mouse for cursor positioning. e.g. [x,y] = ginput(10)

17

Other File Formats

• MatLab has many file I/O functions, the following are examples, you can call help to explore them.

>> help iofun • Popular file formats

dlmread / dlmwrite - Read & write ASCII delimited file. A wizard uiimport is available for import data.

xlsread / xlswrite - data and text from a spreadsheet in an Excel workbook.

• Internet functions:-

urlread / urlwrite - Read & Write URL as a string.• From Ports

Serial – construct a serial port object for fopen, etc.

18

Symbolic Processing

• A symbolic expression is stored as a character string and it is one of the data types supported by MatLab

• Based on Maple from The University of Waterloo• http://www.maplesoft.com

• Symbolic toolbox contains functions in calculus, linear algebra, simplification and solution of equations, variable precision arithmetic, transforms (derivatives, integrals)

• User can manipulate symbolic expressions for simplification, solve and evaluate equations in symbolic form, do Calculus, do linear algebra, Laplace & Fourier transforms

• Symbolic object can be created using sym() function or syms Syms is a short-hand notation to sym() Use findsym() to identify the variables in an expression

• Given a function f(x), MatLab can provide the derivative and the integral in symbolic form using symbolic math toolbox

19

Symbolic Variables

To create symbolic variable>>syms x y % shortcut to create sym variables>>z=5*x % z is sym if x is sym variable>>sym x % ans=sym(‘x’) (x undefined)>>x=sym('x') % create sym variable x using sym()>>v=sym('u*sin(pi*t/2)') % create fun from string v = u*sin(pi*t/2)% u, t are absent in the workspace window because

they are not explicitly defined% MatLab does not indent symbolic variables like

numerical variables (ans does not indented)

• The memory size of symbolic variable is variable• Convert symbolic matrix to numeric form:-

Usage:- r = double(S)

20

Example on Symbolic Toolbox Applications

>> x=y^2 % define function x

>> ztrans(x) % get z transform of x

ans = z*(z+1)/(z-1)^3

>> laplace(x) % get Laplace transform of x

ans = 2/s^3

>> u=cos(x) % we can also do substitution

u =cos(y^2)

>> laplace(u) % get Laplace transform of u

ans =1/2*2^(1/2)*pi^(1/2)*sin(1/4*s^2)*(1/2-FresnelC(1/2*s*2^(1/2)/pi^(1/2)))+1/2*2^(1/2)*pi^(1/2)*cos(1/4*s^2)*(1/2-FresnelS(1/2*s*2^(1/2)/pi^(1/2)))

21

Symbolic Toolbox Application (cont. example)

• FresnelC is the Fresnel Cosine Integral defined as:-

• Over fifty special functions are available from the Symbolic Toolbox and can be evaluated using mfun(‘function’, variable)

>> help mfun

• Function list is available with

>>mfunlist

z

dttzC0

2

2cos)(

22

Special Function Evaluation - Example

• Let’s try to plot the Fresnel Cosine Integral >> z=0:0.01:10;>> y=mfun('FresnelC',z);>> plot(z,y)

z

dzzzCy0

2

2cos)(

23

Example - Factorization of Large Integer >> n=sym('224') % To factorize integer 224>> factor(n)ans =(2)^5*(7)>> 2^5*7ans = 224% Try a 40-digit number>>n1=sym('123456789012345678901234567890123456789

0')>> factor(n1)ans =(2)*(3)^2*(5)*(73)*(101)*(137)*(1676321)*(5964848

081)*(3803)*(3607)*(27961)*(3541)>> isprime(1676321) % check prime factorans = 1 % 0=false 1=true

24

Factorization & Simplification with Symbolic Toobox

>> syms x y % define x, y symbolic variables>> y=2*(x+3)^2/(x^2+6*x+9); % define function y>> [num,denum]=numden(y) % separate num & denumnum =2*(x+3)^2denum =x^2+6*x+9>> expand(num)ans =2*x^2+12*x+18>> factor(num)ans =2*(x+3)^2>> factor(denum)ans =(x+3)^2>> simplify(y)ans =2

25

Numerical Calculations with Symbolic Expressions

• Symbolic substitution subs(s,old,new) can be used to subsititute numerical value to evaluate symbolic expression

• Usage:- Y=subs(Expression, {var1,var2},{n1,n2})

>> syms x m b % create symbolic variablesy=m*x+b; % define eqn>> subs(y,{x,b,m},{1,10,2}) % subst values into eqnans = 12>> diff(y)ans =m

26

Expansion using Collect()

Symbolic variables are stored as strings.

Collect() can be used to expand a polynomial>> y=x^2*(x^3+x)*(x^2*3*x+3)*(x-4);>> collect(y)ans =3*x^9-12*x^8+3*x^7-9*x^6-12*x^5+3*x^4-12*x^3

27

Simplify

• The simplify function uses operations such as addition, multiplication, rules of fractions, powers, logarithms, special functions and trigonometric identities to simply the expression.>> eqn1=sym('fx=x^4-2*x^3-33*x^2+18*x+216');simplify(eqn1)ans =fx = x^4-2*x^3-33*x^2+18*x+216

• As the expression is being placed in quotes, x is not defined as symbolic variable. This is not recommended as it will cause error if x is being called later by other expressions.

>>syms x;eqn2=cos(x)^2+sin(x)^2;simplify(eqn2)ans =1

28

Example on the Simple Function• The simple function simplify a symbolic expression using different

methods and report the shortest result.>> syms x; num=x^2+4*x+4;den=x+2;fx=num/densimple(fx)

simplify: x+2 radsimp: x+2 combine(trig): x+2 factor: x+2 expand: 1/(x+2)*x^2+4/(x+2)*x+4/(x+2) combine: (x^2+4*x+4)/(x+2) convert(exp): (x^2+4*x+4)/(x+2) convert(sincos): (x^2+4*x+4)/(x+2) convert(tan): (x^2+4*x+4)/(x+2) collect(x): (x^2+4*x+4)/(x+2)ans = x+2

>>pretty(fx) % display the function in typeset form

2

44)(

2

x

xxxf

29

Further Example on Simple Function

• Rework eqn1 in previous slide:->> eqn1=sym('fx=x^4-2*x^3-33*x^2+18*x+216');simplify(eqn1)simple(eqn1)ans = fx = (x-3)*(x-6)*(x+4)*(x+3)

• Alternative usage for simple(). In the following example, the shortest form is assigned to g

and the name of the simplification method used is assigned to how as a character string>> [g how]=simple(eqn1)fx = (x-3)*(x-6)*(x+4)*(x+3)how =factor

30

Symbolic Expression Plotting

>> syms x yy=x^2;ezplot(y)grid onezplot(y,[0,3])grid on

31

Polynomial & Symbolic Expressions

• poly2sym() & sym2poly() convert vectors or polynomials into symbolic expressions or vice versa>>p=[1 0 -7 6];p_sym=poly2sym(p)p_sym = x^3-7*x+6>> pretty(p_sym) >> p1=sym2poly(p_sym)p1 = 1 0 -7 6

• horner() transpose a symbolic polynomial into its nested (Horner) representation>> horner(y^2+y) % ans = (1+y)*y

>> px=x^4+2*x^3+x+10 horner(px)ans = 10+(1+(x+2)*x^2)*x

32

Solve Equations

• The solve(eqn) sets the expression to 0 and solve for roots>> y=sym('3*x-9');solve(y)ans = 3

• If the equation has one variable, the solution is numerical. If the equation has more than one variables, a solution will be obtained for any of the variables in terms of others Usage: y=solve(eqn,var)

>> eqn=sym('y=x^2+2*t*x+30')solve(eqn)ans = [ -t+(t^2+y-30)^(1/2)] [ -t-(t^2+y-30)^(1/2)]syms t xsolve(eqn,t)ans =-1/2*(-y+x^2+30)/x

33

Solving System of Equations

• Usage:- soln= solve(eqn1, eqn2,….,eqnN) soln is the name of the structure in the form

• Structure_name.field_name

• Example>> eqn1=sym('5*x+6*y=20');eqn2=sym('6*x+7*y=34');soln=solve(eqn1,eqn2)soln = x: [1x1 sym] % name of solution structure y: [1x1 sym]>> soln.x % display the answer ans = 64>> soln.yans = -50

34

Differentiation

• Diff() can be used to determine the derivative of function

• Usage:- diff(function) or diff(function, variable)

• Example:- >> sym(‘x’);p_sym = x^3-7*x+6;pretty(diff(p_sym)) 2 3 x - 7

pretty(diff(p_sym,2)) % double differentiation 6 x

35

Partial Differentiation

>> syms r t x>> r=6*x+8*cos(3*t)r =6*x+8*cos(3*t)>> diff(r,t)ans =-24*sin(3*t)>> diff(r,x)ans =6

6

)3sin(24

)3cos(86

x

r

tt

r

txr

36

Integration

>> syms x>> y=cos(x)y =cos(x)>> int(y)ans =sin(x)>> int(y,0,pi)ans =0>> int(y,0,pi/2)ans =1

xdxcos

2

0cos

xdx

0cos xdx

37

Integration with respect to a variable

>> syms n x>> eqn=x^n;>> int(eqn,n)ans =1/log(x)*x^n

x

xdnx

nn

ln

38

Example on Integration

• Integral sometimes does not exist

>> syms xeqn=int(1/(x-1))eqn =log(x-1)>> eqn=int(1/(x-1),0,2)Warning: Explicit integral

could not be found.>> eqn=int(1/(x-1),2,3)eqn =log(2)>> double(eqn) %conversionans = 0.6931

1ln1

1

xdxx

The indefinite integral exist but the definite integral does not exist because a singularity at x=1

39

• First order differential equation

• t is an independent variable

• x is a function of t

• Solution is in a form of x=g(t) + C

• C can be determined when applying boundary conditions

• x=x(t1) when t=t1

• If the condition obtained at t=0, it is called the initial condition

• Using symbolic toolbox, we can obtain an analytical solution rather than numerical solution

Ordinary Differential Equation

dt

dxxf

xtf

xftxF

)(

)(

0))(,,(

'

'

40

Solution to ODE using dsolve

>> help dsolve Usage:- dsolve('eqn1','eqn2', ...) By default, the independent variable is 't'. It can be changed

by including a different variable at the last input argument. The letter 'D' denotes differentiation

• e.g., D2y denotes the second derivative of y w.r.t. t

• Due to this syntax, the names of symbolic variables cannot contain the letter "D".

Initial conditions are specified by equations like 'y(a)=b' or 'Dy(a) = b‘

dsolve accepts up to 12 input arguments dsolve returns a warning message, if it cannot find an

analytic solution – may try numerical solution

41

First Order ODE Solution

>> dsolve('Dx+2*x=10')ans =5+exp(-2*t)*C1% note C1 is the constant% with initial condition that e.g. x(0)=0>> y=dsolve('Dx+2*x=10','x(0)=0')y =5-5*exp(-2*t)>> ezplot(y)

42

Solution of Set of Equations

>>[x,y]=dsolve('Dx=3*x+4*y','Dy=-4*x+3*y')x =exp(3*t)*(cos(4*t)*C1+sin(4*t)*C2)y =exp(3*t)*(-sin(4*t)*C1+cos(4*t)*C2)

yxdt

dy

yxdt

dx

34

43

teCteCty

teCteCtxtt

tt

4cos24sin)(

4sin24cos)(3

23

1

32

31

•Example:-

Solution:-

43

Second Order ODE with Boundary Conditions

• Example:-

• Boundary conditions:-

>>y=dsolve('D2y+9*y=0','y(0)=1','Dy(pi)=2')y =-2/3*sin(3*t)+cos(3*t)

092

2

ydt

yd

2)(

1)0(

y

y

44

Solution to First Order Nonlinear Differential Equations

>> dsolve('Dy=4-y^2','y(0)=1')ans =(2*exp(4*t+log(-3))+2)/(-1+exp(4*t+log(-3)))simple(ans)ans =(-6*exp(4*t)+2)/(-1-3*exp(4*t))simple(ans) ans =(6*exp(4*t)-2)/(1+3*exp(4*t))

• Sometimes, more than one application of simple function is needed to get a simplified answer

24 ydt

dy 1)0( y

t

t

e

ety

4

4

31

26)(