Advertisement
Guest User

Untitled

a guest
Sep 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 2.09 KB | None | 0 0
  1. % Q2.2 Module 4
  2. %
  3. % Code to solve the 1D heat equation implicitly using Crank-Nicolson
  4. % Student name: Renee Meaney
  5. % Student ID: 27848779
  6.  
  7.  
  8. clear all;
  9.  
  10. % Set the number of grid points
  11. M=100; % These are the interior points (There will be M+2 including B.C's)
  12. L=1.0;
  13. dx=L/M;
  14. x=-0.5*dx:dx:L+0.5*dx; % x-grid including outer BC points
  15. x=x';  % Turn x into a column vector.
  16. a=0.4;
  17.  
  18. % Setup the time domain.
  19. dt = 0.01; % Timestep
  20. tfinal = 1;
  21. N = tfinal/dt;
  22. t = linspace(0,tfinal,N+1);
  23.  
  24. % Introduce the initial condition via f(x)
  25. f = zeros(M,1);
  26. for m = 1:M
  27.     if x(m) >= 0 & x(m) < L/4.0
  28.         f(m) = 0; end
  29.     if x(m) >= L/4 & x(m) < 3*L/4.0
  30.         f(m) = sin((2*pi/L)*(x(m)-(L/4.0))); end   % Basic sinusoidal I.C.
  31.     if x(m) >= 3*L/4.0 & x(m) <= L
  32.         f(m) = 0; end    
  33. end
  34. u = zeros(M+2,N);
  35. u(:,1)=[0;f;0];
  36. % So u(:,2) will be the solution at t = dt, u(:,3) at t = 2*dt etc.
  37.  
  38. % Create the matrices A and B by loading them with zeros
  39. A=zeros(M+2);
  40. B=zeros(M+2);
  41.  
  42. % load A and B at interior points
  43. alpha = (1/2)*(a^2/dx^2);
  44. beta =  (1/dt)+(a^2/dx^2);
  45. gamma = (1/dt)-(a^2/dx^2);
  46. for j=2:M+1
  47.   A(j,j-1)= -alpha;
  48.   A(j,j)  = beta;
  49.   A(j,j+1)= -alpha;
  50.   B(j,j-1)= alpha;
  51.   B(j,j)  = gamma;
  52.   B(j,j+1)= alpha;
  53. end
  54.  
  55. % Add values of '1' to A(1,1) and A(M+2,M+2)
  56. A(1,1)=1.0;            % T(0)=0
  57. A(M+2,M+2)=1.0;        % T(L)=0
  58.  
  59. % Now we advance through time, solving for each new solution vector!
  60. for n=1:N
  61.  
  62. u(:,n+1)= (A)\(B*u(:,n)); %Calculate the new solution vector u
  63.  
  64. % Make a movie of u in the loop, like in the previous module (with labels!)
  65. % You should delete this before submitting and only generate Fig1 later.
  66. %figure(1); %-%
  67. %plot(x,u(:,n+1)) %-%
  68. %xlabel('x') %-%
  69. %ylabel('u(x,t)') %-%
  70. %axis([0 1 0 1]) %-%
  71. %pause(0.02); %-%
  72.  
  73. end
  74.  
  75.  
  76. Fig1 = figure;
  77.  
  78.  
  79. % Make a surface plot of u(x,t) using the 'surf' or 'mesh' functions.
  80. % You do remember how to use 'meshgrid' right?
  81.  
  82. [x,t] = meshgrid(x,t);
  83. surf(x,t,u');
  84. title('Heat Equation surface plot using the Crank-Nicholson scheme');
  85. xlabel('x');
  86. ylabel('t');
  87. zlabel('u(x,t)');
  88.  
  89. %Conclusions:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement