Matlab in Physics Nguyen Van Hong code

56 107 1
Matlab in Physics  Nguyen Van Hong code

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

% A few Matlab examples including 2D and 3D graphics, animations, and % matrix operations set(0,'DefaultTextInterpreter','LaTeX') %% 2d plot clear, clf x=-1:.1:1; y=x.^3; plot(x,y) box off xlabel('$x$') ylabel('$y$') title('$y=x^3$') %% 3d plot clear, clf [x y]=meshgrid(linspace(-1,1,50)); z=x.^2+y.^2; mesh(x,y,z) %% 3d plot (improvement 1) clear, clf r=linspace(0,1,25); vth=linspace(0,2*pi,25); [r vth]=meshgrid(r,vth); x=r.*cos(vth); y=r.*sin(vth); z=r.^2; mesh(x,y,z) %% 3d plot (improvement 2) clear, clf axes('Pos',[.2 8]) r=linspace(0,1,25); vth=linspace(0,2*pi,25); [r vth]=meshgrid(r,vth); x=r.*cos(vth); y=r.*sin(vth); z=r.^2; surfl(x,y,z+.5), hold on shading interp, colormap copper contour(x,y,z), hold off set(gca, 'XLim',[-1 1], 'YLim',[-1 1], 'ZLim',[-inf inf],'ZTickL',[0:.5:1.5],'ZTickL',[-.5:.5:1], 'Box','on','Color',[1 1]) grid off title('$z=x^2+y^2$') xlabel('$x$') ylabel('$y$') zlabel('$z$') %% movie clear, clf mov=avifile('example.avi') x=linspace(-3,3,25); y=linspace(-3,3,25); [X Y]=meshgrid(x,y); z=peaks(X,Y); surf(x,y,z) shading interp axis([-3 -3 -8 8]) set(gca,'Visible','off') N=25; for I=1:N surf(x,y,sin(2*pi*I/N)*z) shading interp axis([-3 -3 -8 8]) set(gca,'Visible','off') mov=addframe(mov,getframe(gca)); end mov=close(mov); %% matrix multiplication clear N=100; rand('state',1), A=ceil(5*rand(N)); rand('state',2), B=ceil(5*rand(N)); C=zeros(N); tic for I=1:N for J=1:N dmy=0; for K=1:N dmy=dmy+A(I,K)*B(K,J); end C(I,J)=dmy; end end toc tic, C=A*B; toc %% determinants, eigenvalues, etc clear A=[1 0;0 5]; det(A) [V D]=eig(A) A*V D*V %% fourier series clear, clf t=linspace(-.5,.5,250); f=.5*(square(t+.25)-square(t-.25)); h=[]; h=plot(t,f,'r','LineW',1); hold on n=1:15; A=[.5 sin(n*pi/2)./(n*pi/2)]; fn=A*cos(2*[0 n]'*pi*t); h=[h plot(t,fn,'b','LineW',.5)]; hold off set(gca, 'XLim',[-.5 5],'XTick',[-.5 5], 'YLim',[-.5 1.5], 'Box','off') legend(h,{'$f(t)$',['$f_{' num2str(max(n)) '}(t)$']}) xlabel('$t$') set(0,'DefaultTextInterpreter','TeX') function b=num2bin(n) %NUM2BIN Convert floating point number to binary string % NUM2BIN(N) returns the binary representation of the floating point % number N in the form [sign][exponent][mantissa] % % Example % float2bin(single(9.4)) returns % [0][10000000010][0010110011001100110011000000000000000000000000000000] % float2bin(double(9.4)) returns % [0][10000000010][0010110011001100110011001100110011001100110011001101] % % See also DEC2BIN, BIN2DEC, HEX2DEC, BASE2DEC % % Francisco J Beron-Vera $Revision: 1.2 $ $Date: 2006/08/30 16:13:31 $ % Convert to hex string h=sprintf('%bx',n); % Convert to cell array of strings h=cellstr(h'); % Convert hex numerals to decimal numbers h=hex2dec(h); % Convert numeric array to array of binary strings b=dec2bin(h); % Pad with zeros if necessary b=[repmat(num2str(zeros(16,1)),[1 4-size(b,2)]) b]; % Concatenate binary strings b=b'; b=b(:)'; % Output as a string of the form [sign][exponent][mantissa] b=['[' b(1) '][' b(2:12) '][' b(13:end) ']']; function b=double2bin(n) %DOUBLE2BIN Convert double precision floating point to binary string % DOUBLE2BIN(N) returns the binary representation of the double precision % floating point number N in the form [sign][exponent][mantissa] % % The binary representation of F is computed, not converted from its % hexadecimal representation as in NUM2BIN % % See also NUM2BIN, DEC2BIN, BIN2DEC, HEX2DEC, BASE2DEC % % Francisco J Beron-Vera $Revision: 1.3 $ $Date: 2006/08/30 16:19:35 $ % Convert integer part to binary string i=abs(fix(n)); ib=[]; while i~=0 ib=[ib num2str(rem(i,2))]; i=fix(i/2); end if isempty(ib) ib=['0']; end ib=fliplr(ib); % Convert fractional part to binary string f=abs(n-fix(n)); fb=[]; for j=1:53 fb=[fb num2str(fix(f*2))]; f=f*2-fix(f*2); end % Output as a string of the form [sign][exponent][mantissa] if n>0 s='0'; else s='1'; end if length(ib)==1 if str2num(ib)==0 e=[dec2bin(0) dec2bin(1022)]; m=fb(2:end); else e=[dec2bin(0) dec2bin(1023)]; m=fb; end else e=dec2bin(length(ib)+1022); m=[ib(2:end) fb]; end b=['[' s '][' e '][' m(1:52) ']']; function v = longhex(u, digits) %LONGHEX Long hexadecimal format % V=LONGHEX(U,N) takes a positive decimal fraction less than and converts % it to a binary fraction of length digits It then converts it to a IEEE % double precision number but possibly with a longer mantissa U is a vector % of decimal digits in the range [0-9] with the decimal point to the 'left' % of U(1) N is the length in binary digits to save V is a string of hexidecimal % digits of the IEEE double number, but with possibly longer mantiassa % % Algorithm: Knuth, Vol 2, p 319, Method 2a % % % % By: Martin Knapp-Cordes The MathWorks, Inc Date: Apr 2001 - 09 u2 = zeros(size(u,1)+1,1); u2(2:end) = u; b = zeros(digits,1); for i=1:digits u2 = mult2(u2); b(i) = u2(1); u2(1) = 0; end % Always produce an least an IEEE double o = find(b == 1); base = o(1); s = size(b,1); v = dec2hex(1023-base,3); n = max(ceil((s - base) / 4), 13); v2 = zeros(n * 4,1); v2(1:(s - base)) = b((base+1):end); for i=1:4:n*4 v = [ v dec2hex(bin2dec(sprintf('%d',v2(i:i+3))))]; end v = lower(v); % -function u2 = mult2(u) % Multiply by with carry u2 = * u; c = (u2>=10); u2(1:end-1) = u2(1:end-1) + c(2:end) - c(1:end-1) * 10; u2(end) = u2(end) - c(end) * 10; function y=logistic(x,r,anything) %LOGISTIC Logistic map % Y=LOGISTIC(X,R) evaluates R*X*(1-X) % Y=LOGISTIC(X,R,'EXPANDED') evaluates R*X*-R*X*X % % Francisco J Beron-Vera $Revision: 1.0 $ $Date: 2006/09/05 11:52:25 $ if nargineps*abs(x1) k=k+1; if k>25 warning('Tolerance not satisfied.') break end x=f(x0,varargin{:}); plot([x0 x],[x x],'r'), pause plot([x x],[x f(x,varargin{:})],'r'), pause x1=x0; x0=x; end hold off function y=newton(f,dfdx,x,xmin,xmax,varargin) %NEWTON Root finding, Newton method % X=NEWTON(F,DFDX,X0,A,B) attempts to find the solution of F(X)=0 near % X0 where DFDX is the derivative of the scalar function F defined % in the interval [A,B] using Newton method Both F and DFDX are function % handles The geometry of the method is ilustrated and convegence plots % are produced % % X=NEWTON(F,DFDX,X0,A,B,P1,P2, ) passes the parameters P1,P2, to F % % See also BISECTION, SECANT, IQI % % Francisco J Beron-Vera, 2006/09/07 $Revision: 1.1 $ $Date: 2006/09/07 09:00:25 $ % Plot function figure(1), clf X=linspace(xmin,xmax,100); plot(X,f(X,varargin{:}),'b') axis tight, box off, hold on xlabel('$x$', 'FontSize',14, 'Interpreter','LaTeX') ylabel('$y$', 'FontSize',14, 'Interpreter','LaTeX') disp('Press any key to continue.'), pause plot([X(1) X(end)],[0 0],'k'), pause plot([x x],[0 f(x,varargin{:})],'g.:'), pause % Newton loop k=0; y=x+1; Y=[]; while abs(y-x)>eps*abs(x) k=k+1; if k>50 warning('Tolerance not satisfied.') break end y=x; Y=[Y y]; x=x-f(x,varargin{:})/dfdx(x,varargin{:}); plot(X,f(y,varargin{:})+dfdx(y,varargin{:})*(X-y),'r'), pause plot([x x],[0 f(x,varargin{:})],'g.:'), pause end % Convergence analysis figure(2), clf k=0:length(Y)-1; e=abs(Y-Y(end)); subplot(211) plot(k,e) xlabel('$n$', 'FontSize',14, 'Interpreter','LaTeX') ylabel('$e_n:=|x_n-r|$', 'FontSize',14, 'Interpreter','LaTeX') title(['$r=' sprintf('%16.8f',Y(end)) '$'], 'FontSize',14, 'Interpreter','LaTeX') subplot(212) plot(k(2:end-1),e(2:end-1)./e(1:end-2).^2) xlabel('$k$', 'FontSize',14, 'Interpreter','LaTeX') ylabel('$e_n/e_{n-1}^2$', 'FontSize',14, 'Interpreter','LaTeX') function y=newtonsys(f,dfdx,x,varargin) %NEWTONSYS Root finding, Newton method, systems of equations % X=NEWTONSYS(F,DFDX,X0) attempts to find the solution of the nonlinear % system of equations F(X)=0 near X0 where DFDX is the derivative (Jacobian % matrix) of the function F using Newton method % % X=NEWTONSYS(F,DFDX,X0,P1,P2, ) passes the parameters P1,P2, to F % Francisco J Beron-Vera,2006/09/18 y=x+1; k=0; while norm(y-x)>eps*norm(y) k=k+1; if k>50 warning('Tolerance not satisfied.') break end y=x; x=x-dfdx(x,varargin{:})\f(x,varargin{:}); end function r=bisection(f,a,b,varargin) %BISECTION Root finding, bisection method % X=BISECTION(F,A,B) attempts to find the solution of F(X)=0 in the % interval [A,B] such that F(A)*F(B) < % % X=BISECTION(F,A,B,P1,P2, ) passes the parameters P1,P2, to F % % See also NEWTON, SECANT, IQI % % Francisco J Beron-Vera $Revision: 1.1 $ $Date: 2006/09/19 13:28:03 $ if f(a,varargin{:})*f(b,varargin{:})>=0 error('F(A)*F(B) must be negative.') end for k=1:54 r=(a+b)/2; if f(a,varargin{:})*f(r,varargin{:})0 plot(x([2 n+1]),f(x([2 n+1]),varargin{:}),'r'), pause else plot(x([1 n+1]),f(x([1 n+1]),varargin{:}),'r'), pause end end end r=x(n); if strcmp(ConvergenceAnalysis,'yes') % Convergence analysis figure(2), clf x=x(1:n); n=0:n-1; e=abs(x-x(end)); subplot(211) plot(n,e) xlabel('$n$', 'FontSize',14, 'Interpreter','LaTeX') ylabel('$e_n:=|x_n-r|$', 'FontSize',14, 'Interpreter','LaTeX') title(['$r=' sprintf('%16.8f',x(end)) '$'], 'FontSize',14, 'Interpreter','LaTeX') subplot(212) plot(n(2:end-1),e(2:end-1)./e(1:end-2).^1.62), hold on h=plot(n([2 end-1]),repmat(.5*d2fdx2(r)/dfdx(r),[1 2]),'r:'); hold off legend(h,{['$f''''(r)/2f''(r)\approx' num2str(.5*d2fdx2(r)/dfdx(r)) '$']}, 'FontSize',14, 'Interpreter','LaTeX') legend boxoff xlabel('$k$', 'FontSize',14, 'Interpreter','LaTeX') ylabel('$e_n/e_{n-1}^{1.62}$', 'FontSize',14, 'Interpreter','LaTeX') end function r=iqi(f,x1,x2,x3,varargin) %IQI Root finding, inverse quadratic interpolation method % X=IQI(F,X1,X2,X3) attempts to find the solution of F(X)=0 given initial % guesses X1, X2 and X3 using the inverse quadratic interpolation method % F is a function handle % % X=IQI(F,X1,X2,X3,P1,P2, ) passes the parameters P1,P2, to F n = n+1; if n > N warning('Tolerance not satisfied.') break end y(n+1) = y(n)-E(n)*(y(n)-y(n-1))/(E(n)-E(n-1)); if length(xspan) == [x z] = ode45(odefun,x,[A;y(n+1)],options,varargin{:}); else z = ode4(odefun,x,[A;y(n+1)],varargin{:}); end u(:,n+1) = z(:,1); E(n+1) = z(end,1)-B; end if length(xspan)==2 varargout{1} = x; else varargout{1} = x; end varargout{2} = u(:,1:n); if nargout > varargout{3} = y(1:n); varargout{4} = E(1:n); end % Solves numerically the one-dimensional diffusion equation, % % u_t = u_{xx} (x,t) \in [0,1]^2 % u(x,0) = \sin \pi x x \in [0,1] % u(0,t) = t \in [0,1] % u(1,t) = t \in [0,1] % % whose exact solution is % % u(x,t) = \sin \pi x \exp(-\pi^2 t), % % using forward-time difference, backward-time difference, and % Crank-Nicolson methods % Francisco J Beron-Vera, 2006/15/05 %% FORWARD-TIME DIFFERENCE (EXPLICIT) % % U(I,J) = u((I-1)*Dx,(J-1)*Dt), I = 1, ,Nx+1, J = 1, ,Nt+1 % (U(I,J+1) - U(I,J))/Dt = (U(I+1,J) - 2*U(I,J) + U(I-1,J))/Dx^2 % U(I,1) = sin(pi*(I-1)*Dx), U(1,J) = 0, U(Nx+1,J) = % s = Dt/Dx^2, Nx = 6: % |U(2,J+1)| |1-2*s s 0 | |U(2,J)| |s*U(1,J)=0| % |U(3,J+1)| | s 1-2*s s 0 | |U(3,J)| | | % |U(4,J+1)| = | s 1-2*s s | |U(4,J)| + | | % |U(5,J+1)| | 0 s 1-2*s s | |U(5,J)| | | % |U(6,J+1)| | 0 s 1-2*s| |U(6,J)| |s*U(7,J)=0| % Order of local truncation error: Dt + Dx^2 % Conditionally stable (s < 1/2) clear Nx = 50; Dx = 1/Nx; x = (0:Nx)'*Dx; Dt = 49/Nx^2; Nt = fix(1/Dt); t = (0:Nt)'*Dt; s = Dt/Dx^2; T = diag(repmat(s,Nx-2,1),1) + (1-2*s)*eye(Nx-1) + diag(repmat(s,Nx-2,1),-1); U = zeros(Nx-1,Nt+1); U(:,1) = sin(pi*x(2:end-1)); for J = 1:Nt-1 U(:,J+1) = T*U(:,J); end U = [zeros(1,Nt+1); U; zeros(1,Nt+1)]; figure(1), clf subplot(221) plot(x,U(:,[1 fix(rand(1,25)*Nt)+1]),'b') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x)$','FontS',14,'Interp','latex') text(1.25,1.15,['Forward-Time Difference ($N_x = ' num2str(Nx) '$, $N_t = ' num2str(Nt) '$)'], 'Hor','cen','FontS',14,'Interp','latex') subplot(222) surf(t,x,U), shading flat set(gca,'YDir','reverse') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$x$','FontS',14,'Interp','latex') zlabel('$u(x,t)$','FontS',14,'Interp','latex') subplot(223) [X T] = meshgrid(x,t); Ux05 = interp2(X,T,U',repmat(.5,size(t)),t); plot(t,Ux05,'bo'), hold on h = plot(t,sin(pi*.5)*exp(-pi^2*t),'r'); h =legend(h,'exact'); set(h,'FontSize',14,'Interp','latex') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$u(x=0.5,t)$','FontS',14,'Interp','latex') subplot(224) Ut05 = interp2(X,T,U',x,repmat(.5,size(x))); plot(x,Ut05,'bo',x,sin(pi*x)*exp(-pi^2*.5),'r') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x,t=0.5)$','FontS',14,'Interp','latex') %% BACKWARD-TIME DIFFERENCE (IMPLICIT) % % U(I,J) = u((I-1)*Dx,(J-1)*Dt), I = 1, ,Nx+1, J = 1, ,Nt+1 % (U(I,J) - U(I,J-1))/Dt = (U(I+1,J) - 2*U(I,J) + U(I-1,J))/Dx^2 % U(I,1) = sin(pi*(I-1)*Dx), U(1,J) = 0, U(Nx+1,J) = % s = Dt/Dx^2, Nx = 6: % |1+2*s -s 0 | |U(2,J)| |U(2,J-1)| |s*U(1,J)=0| % | -s 1+2*s -s 0 | |U(3,J)| |U(3,J-1)| | | % | -s 1+2*s -s | |U(4,J)| = |U(4,J-1)| + | | % | 0 -s 1+2*s -s | |U(5,J)| |U(5,J-1)| | | % | 0 -s 1+2*s| |U(6,J)| |U(6,J-1)| |s*U(7,J)=0| % Order of local truncation error: Dt + Dx^2 % Unconditionally stable clear Nx = 50; Dx = 1/Nx; x = (0:Nx)'*Dx; Nt = 1500; Dt = 1/Nt; t = (0:Nt)'*Dt; s = Dt/Dx^2; T = diag(repmat(-s,Nx-2,1),1) + (1+2*s)*eye(Nx-1) + diag(repmat(-s,Nx-2,1),1); U = zeros(Nx-1,Nt+1); U(:,1) = sin(pi*x(2:end-1)); for J = 2:Nt+1 U(:,J) = T\U(:,J-1); end U = [zeros(1,Nt+1); U; zeros(1,Nt+1)]; figure(2), clf subplot(221) plot(x,U(:,[1 fix(rand(1,25)*Nt)+1]),'b') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x)$','FontS',14,'Interp','latex') text(1.25,1.15,['Backward-Time Difference ($N_x = ' num2str(Nx) '$, $N_t = ' num2str(Nt) '$)'], 'Hor','cen','FontS',14,'Interp','latex') subplot(222) surf(t,x,U), shading flat set(gca,'YDir','reverse') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$x$','FontS',14,'Interp','latex') zlabel('$u(x,t)$','FontS',14,'Interp','latex') subplot(223) [X T] = meshgrid(x,t); Ux05 = interp2(X,T,U',repmat(.5,size(t)),t); plot(t,Ux05,'bo'), hold on h = plot(t,sin(pi*.5)*exp(-pi^2*t),'r'); h =legend(h,'exact'); set(h,'FontSize',14,'Interp','latex') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$u(x=0.5,t)$','FontS',14,'Interp','latex') subplot(224) Ut05 = interp2(X,T,U',x,repmat(.5,size(x))); plot(x,Ut05,'bo',x,sin(pi*x)*exp(-pi^2*.5),'r') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x,t=0.5)$','FontS',14,'Interp','latex') %% CRANK-NICOLSON (IMPLICIT) % % U(I,J) = u((I-1)*Dx,(J-1)*Dt), I = 1, ,Nx+1, J = 1, ,Nt+1 % (U(I,J) - U(I,J-1))/Dt = (U(I+1,J) - 2*U(I,J) + U(I-1,J) + U(I+1,J-1) 2*U(I,J-1) + U(I-1,J-1))/(2*Dx^2) % U(I,1) = sin(pi*(I-1)*Dx), U(1,J) = 0, U(Nx+1,J) = % s = Dt/Dx^2, Nx = 6: % |2+2*s -s 0 | |U(2,J)| |2-2*s s 0 | |U(2,J1)| |s*(U(1,J-1)+U(1,J))=0| % | -s 2+2*s -s 0 | |U(3,J)| | s 2-2*s s 0 | 1)| | | % | -s 2+2*s -s | |U(4,J)| = | s 2-2*s -s | 1)| + | | % | 0 -s 2+2*s -s | |U(5,J)| | 0 s 2-2*s s | 1)| | | % | 0 -s 2+2*s| |U(6,J)| | 0 s 2-2*s| 1)| |s*(U(1,J-1)+U(1,J))=0| % Order of local truncation error: Dt^2 + Dx^2 % Unconditionally stable |U(3,J|U(4,J|U(5,J|U(6,J- clear Nx = 50; Dx = 1/Nx; x = (0:Nx)'*Dx; Nt = 100; Dt = 1/Nt; t = (0:Nt)'*Dt; s = Dt/Dx^2; T1 = diag(repmat(-s,Nx-2,1),1) + (2+2*s)*eye(Nx-1) + diag(repmat(-s,Nx-2,1),1); T2 = diag(repmat(s,Nx-2,1),1) + (2-2*s)*eye(Nx-1) + diag(repmat(s,Nx-2,1),-1); U = zeros(Nx-1,Nt+1); U(:,1) = sin(pi*x(2:end-1)); for J = 2:Nt+1 U(:,J) = T1\(T2*U(:,J-1)); end U = [zeros(1,Nt+1); U; zeros(1,Nt+1)]; figure(3), clf subplot(221) plot(x,U(:,[1 fix(rand(1,25)*Nt)+1]),'b') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x)$','FontS',14,'Interp','latex') text(1.25,1.15,['Crank Nicolson ($N_x = ' num2str(Nx) '$, $N_t = ' num2str(Nt) '$)'], 'Hor','cen','FontS',14,'Interp','latex') subplot(222) surf(t,x,U), shading flat set(gca,'YDir','reverse') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$x$','FontS',14,'Interp','latex') zlabel('$u(x,t)$','FontS',14,'Interp','latex') subplot(223) [X T] = meshgrid(x,t); Ux05 = interp2(X,T,U',repmat(.5,size(t)),t); plot(t,Ux05,'bo'), hold on h = plot(t,sin(pi*.5)*exp(-pi^2*t),'r'); h =legend(h,'exact'); set(h,'FontSize',14,'Interp','latex') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$u(x=0.5,t)$','FontS',14,'Interp','latex') subplot(224) Ut05 = interp2(X,T,U',x,repmat(.5,size(x))); plot(x,Ut05,'bo',x,sin(pi*x)*exp(-pi^2*.5),'r') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x,t=0.5)$','FontS',14,'Interp','latex') % Solves numerically a two-dimensional diffusion equation, using forward% time difference, backward-time difference, Crank-Nicolson, or Peaceman% Rachford method % Francisco J Beron-Vera, 2006/15/05 clear disp('Solves numerically the two-dimensional diffusion equation:') disp(' ') disp(' u_t = u_{xx} +u_{yy} (x,y,t) \in [0,1]^2 \times [0,0.1],') disp(' u(x,y,0) = \sin \pi x \sin \pi y (x,y) \in [0,1]^2,') disp(' u(0,y,t) = (y,t) \in [0,1] \times [0,0.1],') disp(' u(1,y,t) = (y,t) \in [0,1] \times [0,0.1],') disp(' u(x,0,t) = (x,t) \in [0,1] \times [0,0.1],') disp(' u(x,1,t) = (x,t) \in [0,1] \times [0,0.1],') disp(' ') disp('whose exact solution is') disp(' ') disp(' u(x,y,t) = \sin \pi x \sin \pi y \exp(-2\pi^2 t).') disp(' ') disp('Available methods:') disp(' ') disp('(1) Forward-time difference : U(t+Dt) = Pfd*U(t) (N.B Dx^2 + Dy^2 > 4*Dt)') disp('(2) Backward-time difference: Pbd*U(t+Dt) = U(t)') disp('(3) Crank-Nicolson : Pcn1*U(t+Dt) = Pcn2*U(t)') disp('(4) Peaceman-Rachford : Ppr1x*U(t+Dt) = Ppr2y*U(t)') disp(' Ppr1y*U(t+Dt) = Ppr2x*U(t+Dt)') disp(' ') method = input('Your method choice: '); Nx = input('Number of grid points in x direction: ') - 1; Ny = input('Number of grid points in y direction: ') - 1; Nt = input('Number of time steps = '); u = @(x,y,t) sin(pi*x).*sin(pi*y)*exp(-2*pi^2*t); Dx = 1/Nx; x = (0:Nx)'*Dx; Dy = 1/Ny; y = (0:Ny)'*Dy; Dt = 1/Nt; t = (0:Nt)'*Dt; sx = Dt/Dx^2; sy = Dt/Dy^2; nx ny Sx Sy Z E Ex Ey = = = = = = = = d2dx2 d2dy2 Nx-1; Ny-1; repmat(sx,nx,1); repmat(sy,ny,1); spalloc(nx*ny,1,nx*ny); speye(nx*ny); speye(nx); speye(ny); = spdiags([Sx -2*Sx Sx],-1:1,nx,nx); = spdiags([Sy -2*Sy Sy],-1:1,ny,ny); nabla2 = kron(d2dy2,Ex) + kron(Ey,d2dx2); nabla2x = spdiags([Z diag(nabla2)+2*sy Z],[-nx nx],nabla2); nabla2y = spdiags([Z diag(nabla2)+2*sx Z],-1:1,nabla2); if method == Pfd = E + nabla2; elseif method == Pbd = E - nabla2; elseif method == Pcn1 = E - nabla2/2; Pcn2 = E + nabla2/2; else Ppr1x = E - nabla2x/2; Ppr2x = E + nabla2x/2; Ppr1y = E - nabla2y/2; Ppr2y = E + nabla2y/2; end % Initializing U [x y] = ndgrid(x,y); UdU = u(x,y,0); subplot(221) pcolor(x,y,UdU) axis([0 1]) shading flat, caxis([0 1]) set(gca,'XTick',[0 1],'YTick',[0 1]) xlabel('x'), ylabel('y'), title('NUMERIC') text(1.15,1.125,'t = 0','Hor','cen') subplot(222) pcolor(x,y,UdU) axis([0 1]) shading flat, caxis([0 1]) h = colorbar('SouthOutside'); set(h,'Pos',[.3 45 025]) set(get(h,'XLabel'),'Str','u') set(gca,'XTick',[0 1],'YTick',[0 1]) xlabel('x'), title('EXACT') drawnow U = UdU; U([1 end],:) = []; U(:,[1 end]) = []; U = U(:); % Time stepping U for J = 2:Nt+1 if method == U = Pfd*U; elseif method == U = Pbd\U; elseif method == U = Pcn1\(Pcn2*U); else U = Ppr1x\(Ppr2y*U); U = Ppr1y\(Ppr2x*U); end subplot(221) UdU(2:end-1,2:end-1) = reshape(U,[nx ny]); pcolor(x,y,UdU) axis([0 1]) shading flat, caxis([0 1]) set(gca,'XTick',[0 1],'YTick',[0 1]) xlabel('x'), ylabel('y'), title('NUMERIC') text(1.15,1.125,['t = ' num2str(t(J))],'Hor','cen') subplot(222) pcolor(x,y,u(x,y,t(J))) axis([0 1]) shading flat, caxis([0 1]) h = colorbar('SouthOutside'); set(h,'Pos',[.3 45 025]) set(get(h,'XLabel'),'Str','u') set(gca,'XTick',[0 1],'YTick',[0 1]) xlabel('x'), title('EXACT') drawnow end % Solves numerically the one-dimensional wave equation, % % u_t = u_{xx} (x,t) \in [0,1]^2 % u(x,0) = \sin 2\pi x x \in [0,1] % u_t(x,0) = x \in [0,1] % u(0,t) = t \in [0,1] % u(1,t) = t \in [0,1] % % whose exact solution is % % u(x,t) = \sin 2\pi x \cos 2\pi t), % % using explicit and implicit methods % Francisco J Beron-Vera, 2006/15/05 %% EXPLICIT METHOD % U(I,J) = u((I-1)*Dx,(J-1)*Dt), I = 1, ,Nx+1, J = 1, ,Nt+1 % (U(I,J+1) - 2*U(I,J) + U(I,J-1)/Dt^2 = (U(I+1,J) - 2*U(I,J) + U(I-1,J))/Dx^2 % U(I,1) = sin(2*pi*(I-1)*Dx), U(I,2) = U(I,2), U(1,J) = 0, U(Nx+1,J) = % Order of local truncation error: Dt^2 + Dx^2 % Conditionally stable: Dx^2/Dt^2 > (Courant-Friedrichs-Lewy) clear u = @(x,t) sin(2*pi*x).*cos(2*pi*t); Nx = 50; Dx = 1/Nx; x = (0:Nx)'*Dx; Dt = 25/Nx; Nt = fix(1/Dt); t = (0:Nt)'*Dt; s = Dt^2/Dx^2; S = repmat(s,Nx-1,1); T = spdiags([S 2-2*S S],-1:1,Nx-1,Nx-1); U = zeros(Nx-1,Nt+1); U(:,1) = u(x(2:end-1),0); U(:,2) = U(:,1); for J = 2:Nt U(:,J+1) = T*U(:,J) - U(:,J-1); end U = [zeros(1,Nt+1); U; zeros(1,Nt+1)]; figure(1), clf subplot(221) plot(x,U(:,[1 fix(rand(1,15)*Nt)+1]),'b') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x)$','FontS',14,'Interp','latex') text(1.25,1.2,['Explicit Method ($N_x = ' num2str(Nx) '$, $N_t = ' num2str(Nt) '$)'], 'Hor','cen','FontS',14,'Interp','latex') subplot(222) surf(t,x,U), shading flat set(gca,'YDir','reverse') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$x$','FontS',14,'Interp','latex') zlabel('$u(x,t)$','FontS',14,'Interp','latex') subplot(223) [X T] = meshgrid(x,t); Ux025 = interp2(X,T,U',repmat(.25,size(t)),t); plot(t,Ux025,'bo'), hold on h = plot(t,u(.25,t),'r'); h =legend(h,'exact'); set(h,'FontSize',14,'Interp','latex') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$u(x=0.25,t)$','FontS',14,'Interp','latex') subplot(224) Ut05 = interp2(X,T,U',x,repmat(.5,size(x))); plot(x,Ut05,'bo',x,u(x,.5),'r') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x,t=0.5)$','FontS',14,'Interp','latex') %% IMPLICIT METHOD % U(I,J) = u((I-1)*Dx,(J-1)*Dt), I = 1, ,Nx+1, J = 1, ,Nt+1 % (U(I,J+1) - 2*U(I,J) + U(I,J-1)/Dt^2 = (U(I+1,J+1) - 2*U(I,J+1) + U(I1,J+1))/(2*Dx^2) + % (U(I+1,J-1) - 2*U(I,J-1) + U(I-1,J1))/(2*Dx^2) % U(I,1) = sin(2*pi*(I-1)*Dx), U(I,2) = U(I,2), U(1,J) = 0, U(Nx+1,J) = % Order of local truncation error: Dt^2 + Dx^2 % Unconditionally stable clear u = @(x,t) sin(2*pi*x).*cos(2*pi*t); Nx = 50; Dx = 1/Nx; x = (0:Nx)'*Dx; Nt = 50; Dt = 1/Nt; t = (0:Nt)'*Dt; s = Dt^2/Dx^2; S = repmat(s,Nx-1,1); T = spdiags([-.5*S 1+S -.5*S],-1:1,Nx-1,Nx-1); U = zeros(Nx-1,Nt+1); U(:,1) = u(x(2:end-1),0); U(:,2) = U(:,1); for J = 2:Nt U(:,J+1) = T\(2*U(:,J)-T*U(:,J-1)); end U = [zeros(1,Nt+1); U; zeros(1,Nt+1)]; figure(2), clf subplot(221) plot(x,U(:,[1 fix(rand(1,15)*Nt)+1]),'b') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x)$','FontS',14,'Interp','latex') text(1.25,1.2,['Implicit Method ($N_x = ' num2str(Nx) '$, $N_t = ' num2str(Nt) '$)'], 'Hor','cen','FontS',14,'Interp','latex') subplot(222) surf(t,x,U), shading flat set(gca,'YDir','reverse') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$x$','FontS',14,'Interp','latex') zlabel('$u(x,t)$','FontS',14,'Interp','latex') subplot(223) [X T] = meshgrid(x,t); Ux025 = interp2(X,T,U',repmat(.25,size(t)),t); plot(t,Ux025,'bo'), hold on h = plot(t,u(.25,t),'r'); h =legend(h,'exact'); set(h,'FontSize',14,'Interp','latex') xlabel('$t$','FontS',14,'Interp','latex') ylabel('$u(x=0.25,t)$','FontS',14,'Interp','latex') subplot(224) Ut05 = interp2(X,T,U',x,repmat(.5,size(x))); plot(x,Ut05,'bo',x,u(x,.5),'r') xlabel('$x$','FontS',14,'Interp','latex') ylabel('$u(x,t=0.5)$','FontS',14,'Interp','latex') % Solves numerically a two-dimensional wave equation, using explicit or % implicit methods % Francisco J Beron-Vera, 2006/15/05 clear disp('Solves numerically the two-dimensional wave equation:') disp(' ') disp(' u_{tt} = u_{xx} +u_{yy} (x,y,t) \in [0,1] \times [0,5],') disp(' u(x,y,0) = \sin 2\pi x \sin 2\pi y (x,y) \in [0,1]^2,') disp(' u_t(x,y,0) = (x,y) \in [0,1]^2,') disp(' u(0,y,t) = (y,t) \in [0,1] \times [0,5],') disp(' u(1,y,t) = (y,t) \in [0,1] \times [0,5],') disp(' u(x,0,t) = (x,t) \in [0,1] \times [0,5],') disp(' u(x,1,t) = (x,t) \in [0,1] \times [0,5],') disp(' ') disp('whose exact solution is') disp(' ') disp(' u(x,y,t) = \sin 2\pi x \sin 2\pi y \cos(2\pi t).') disp(' ') disp('Available methods:') disp(' ') disp('(1) Explicit: U(t+Dt) = T*U(t) - U(t-Dt) (N.B (Dx^2 + Dy^2)/Dt^2 > 1)') disp('(2) Implicit: T*U(t+Dt) = 2*U(t) - T*U(t-Dt)') disp(' ') method = input('Your method choice: '); Nx = input('Number of grid points in x direction: ') - 1; Ny = input('Number of grid points in y direction: ') - 1; Nt = input('Number of time steps = '); u = @(x,y,t) sin(2*pi*x).*sin(2*pi*y)*cos(2*pi*t); Dx = 1/Nx; x = (0:Nx)'*Dx; Dy = 1/Ny; y = (0:Ny)'*Dy; Dt = 5/Nt; t = (0:Nt)'*Dt; sx = Dt^2/Dx^2; sy = Dt^2/Dy^2; nx ny Sx Sy E Ex Ey = = = = = = = Nx-1; Ny-1; repmat(sx,nx,1); repmat(sy,ny,1); speye(nx*ny); speye(nx); speye(ny); d2dx2 = spdiags([Sx -2*Sx Sx],-1:1,nx,nx); d2dy2 = spdiags([Sy -2*Sy Sy],-1:1,ny,ny); nabla2 = kron(d2dy2,Ex) + kron(Ey,d2dx2); if method == T = 2*E + nabla2/2; else T = E - nabla2/4; end % Initializing U [x y] = ndgrid(x,y); UdU = u(x,y,0); subplot(221) surf(x,y,UdU), shading flat axis([0 1 -1 1]) xlabel('x'), ylabel('y'), zlabel('u'), title('NUMERIC') text(2.05,1,.5,'t = 0','Hor','cen') subplot(222) surf(x,y,UdU), shading flat axis([0 1 -1 1]) xlabel('x'), ylabel('y'), zlabel('u'), title('EXACT') drawnow Uold = UdU; Uold([1 end],:) = []; Uold(:,[1 end]) = []; Uold = Uold(:); U = Uold; % Time stepping U for J = 2:Nt+1 if method == Unew = T*U - Uold; else Unew = T\(2*U - T*Uold); end Uold = U; U = Unew; subplot(221) UdU(2:end-1,2:end-1) = reshape(Unew,[nx ny]); surf(x,y,UdU), shading flat axis([0 1 -1 1]) xlabel('x'), ylabel('y'), zlabel('u'),title('NUMERIC') text(2.05,1,.5,['t = ' num2str(t(J))],'Hor','cen') subplot(222) surf(x,y,u(x,y,t(J))), shading flat axis([0 1 -1 1]) xlabel('x'), ylabel('y'), zlabel('u'), title('EXACT') drawnow end % Solves the Poisson equation with Dirichlet boundary conditions in a unit % square given by % % u_{xx} + u_{yy} = \exp xy (x,y) \in [0,1]^2, % u(0,y) = y (y - 1) y \in [0,1], % u(1,y) = - y ((y-1)^4) y \in [0,1], % u(x,0) = 0.5 sin 6\pi x x \in [0,1], % u(x,1) = sin 2\pi x x \in [0,1] % % Compares Gaussian eleimination (Matlab's backslash division)and fast sine % transfom methods clear, clf x = linspace(0,1,128+1); y = linspace(0,1,64+1)'; Dx = min(diff(x)); Dy = min(diff(y)); [X Y] = meshgrid(x,y); f = exp(X.*Y); f(:,1) = 5.*y.*(y-1); f(:,end) = -y.*((y-1).^4); f(1,:) = 5.*sin(6*pi.*x); f(end,:) = sin(pi*2.*x); % % % % east west south north subplot(221) tic, u = ps2d(f,Dx,Dy); et = toc; mesh(X,Y,u) xlabel('x'), ylabel('y'), zlabel('u') title({'Gaussian elimination';['(elapsed time = ' num2str(et) ')']}) subplot(222) tic, u = fps2d(f,Dx,Dy); et = toc; mesh(X,Y,u) xlabel('x'), ylabel('y'), zlabel('u') title({'fast sine transform';['(elapsed time = ' num2str(et) ')']}) function U = ps2d(F,Dx,Dy) %PS2D 2D Poisson equation solver % U = FPS2D(F,DX,DY) solves the Poisson equation in two-space dimensions % with source term F(X,Y) defined on a rectangular domain and Dirichlet % boundary conditions The boundary terms are specified in the perimeter % of the NY x NX matrix F generated using meshgrid Thus EAST, WEST, % SOUTH, and NORTH boundary conditions are to be specified, respectively, % in F(:,1) F(:,END), F(1,:), and F(END,:) Meshgrid widths in X and Y % directions are specified in DX and DY, respectively Inversion of the % five-point discrete Laplacian is done by Gaussian elemination as % implemented in Matlab's backslash division % % See also FPS2D, HS2D, FHS2D % % Francisco J Beron-Vera, 2006/11/15 $Revision: 1.1 $ $Date: 2006/11/22 22:01:20 $ % Get dimensions Nx = size(F,2)-2; Ny = size(F,1)-2; % Five-point discrete Laplacian DX = repmat(Dx,Nx,1); DY = repmat(Dy,Ny,1); d2dx2 = spdiags([1./DX.^2 -2./DX.^2 1./DX.^2],-1:1,Nx,Nx); d2dy2 = spdiags([1./DY.^2 -2./DY.^2 1./DY.^2],-1:1,Ny,Ny); nab2 = kron(d2dx2,speye(Ny)) + kron(speye(Nx),d2dy2); % Fold boundary into source term U = F; U(2:end-1,2:end-1) = 0; U(2:end-1,2:end-1) = 0; F = F - 4*del2(U,Dx,Dy); F([1 end],:) = []; F(:,[1 end]) = []; F = F(:); % Solve nabla2*U = F by Gaussian elimination U(2:end-1,2:end-1) = reshape(nab2\F,Ny,Nx); function U = fps2d(F,Dx,Dy) %FPS2D Fast 2D Poisson equation solver % U = FPS2D(F,DX,DY) solves the Poisson equation in two-space dimensions % with source term F(X,Y) defined on a rectangular domain and Dirichlet % boundary conditions The boundary terms are specified in the perimeter % of the NY x NX matrix F generated using meshgrid Thus EAST, WEST, % SOUTH, and NORTH boundary conditions are to be specified, respectively, % in F(:,1) F(:,END), F(1,:), and F(END,:) Meshgrid widths in X and Y % directions are specified in DX and DY, respectively Inversion of the % discrete five-point Laplacian is perfomed using the fast sine transform % For best performance speed NX - and NY - should be chosen as powers % of % % See also PS2D, HS2D, FHS2D % % Francisco J Beron-Vera, 2006/11/15 $Revision: 1.1 $ $Date: 2006/11/22 21:11:20 $ % Get dimensions Nx = size(F,2)-2; Ny = size(F,1)-2; % Fold boundary into source term U = F; U(2:end-1,2:end-1) = 0; U(2:end-1,2:end-1) = 0; F = F - 4*del2(U,Dx,Dy); F([1 end],:) = []; F(:,[1 end]) = []; % Eigenvalues of discrete Laplacian (nab2) [nx ny] = meshgrid(1:Nx,1:Ny); L = 2/Dx^2*(cos(nx*pi/(Nx+1))-1) + 2/Dy^2*(cos(ny*pi/(Ny+1))-1); % Solve nab2*U = F using fast sine transform U(2:end-1,2:end-1) = idst(idst(dst(dst(F)')'./L)')'; function U = hs2d(F,k,Dx,Dy) %HPS2D 2D Helmholtz equation solver % U = FHS2D(F,K,DX,DY) solves the Helmholtz equation in two-space % dimensions with source term F(X,Y) defined on a rectangular domain % assuming Dirichlet boundary conditions and for constant wavenumber K % The boundary terms are specified in the perimeter of the NY x NX matrix % F generated using meshgrid Thus EAST, WEST, SOUTH, and NORTH boundary % conditions are to be specified, respectively, in F(:,1) F(:,END), F(1,:), % and F(END,:) Meshgrid widths in X and Y directions are specified in DX % and DY, respectively Inversion of the five-point discrete Laplacian is % done by Gaussian elemination as implemented in Matlab's backslash division % % See also PS2D, FPS2D, FHS2D % Francisco J Beron-Vera, 2006/11/22 % Get dimensions Nx = size(F,2)-2; Ny = size(F,1)-2; % Five-point discrete Laplacian DX = repmat(Dx,Nx,1); DY = repmat(Dy,Ny,1); d2dx2 = spdiags([1./DX.^2 -2./DX.^2 1./DX.^2],-1:1,Nx,Nx); d2dy2 = spdiags([1./DY.^2 -2./DY.^2 1./DY.^2],-1:1,Ny,Ny); nab2 = kron(d2dx2,speye(Ny)) + kron(speye(Nx),d2dy2); % Fold boundary into source term U = F; U(2:end-1,2:end-1) = 0; U(2:end-1,2:end-1) = 0; F = F - 4*del2(U,Dx,Dy); F([1 end],:) = []; F(:,[1 end]) = []; F = F(:); % Solve nabla2*U + k^2*U = F by Gaussian elimination k2 = spdiags(repmat(k^2,Nx*Ny,1),0,Nx*Ny,Nx*Ny); U(2:end-1,2:end-1) = reshape((nab2+k2)\F,Ny,Nx); function U = fhs2d(F,k,Dx,Dy) %FHS2D Fast 2D Helmholtz equation solver % U = FHS2D(F,K,DX,DY) solves the Helmholtz equation in two-space % dimensions with source term F(X,Y) defined on a rectangular domain % assuming Dirichlet boundary conditions and for constant wavenumber K % The boundary terms are specified in the perimeter of the NY x NX matrix % F generated using meshgrid Thus EAST, WEST, SOUTH, and NORTH boundary % conditions are to be specified, respectively, in F(:,1) F(:,END), F(1,:), % and F(END,:) Meshgrid widths in X and Y directions are specified in DX % and DY, respectively Inversion of the discrete five-point Laplacian is % perfomed using the fast sine transform For best performance speed % NX - and NY - should be chosen as powers of % % See also HS2D, PS2D, FPS2D % % Francisco J Beron-Vera, 2006/11/15 $Revision: 1.1 $ $Date: 2006/11/22 21:11:20 $ % Get dimensions Nx = size(F,2)-2; Ny = size(F,1)-2; % Fold boundary into source term U = F; U(2:end-1,2:end-1) = 0; U(2:end-1,2:end-1) = 0; F = F - 4*del2(U,Dx,Dy); F([1 end],:) = []; F(:,[1 end]) = []; % Eigenvalues of discrete Laplacian (nab2) [nx ny] = meshgrid(1:Nx,1:Ny); L = 2/Dx^2*(cos(nx*pi/(Nx+1))-1) + 2/Dy^2*(cos(ny*pi/(Ny+1))-1); % Solve nab2*U + k^2*U = F using fast sine transform U(2:end-1,2:end-1) = idst(idst(dst(dst(F)')'./(L+k^2))')'; ... set(0,'DefaultTextInterpreter','TeX') function b=num2bin(n) %NUM2BIN Convert floating point number to binary string % NUM2BIN(N) returns the binary representation of the floating point % number N in the... b=double2bin(n) %DOUBLE2BIN Convert double precision floating point to binary string % DOUBLE2BIN(N) returns the binary representation of the double precision % floating point number N in the form... r=iqi(f,x1,x2,x3,varargin) %IQI Root finding, inverse quadratic interpolation method % X=IQI(F,X1,X2,X3) attempts to find the solution of F(X)=0 given initial % guesses X1, X2 and X3 using the inverse quadratic interpolation

Ngày đăng: 27/01/2018, 10:09

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan