1 d Conduction m Code

1
clear all; close all; % set segments m=4, so the number of nodes n=(m+1) m=4; n=m+1; %set dx dx=1.0/m; @generate_grid; x=generate_grid(n,dx); @set_matrix_eqn; [a,b,c,d]=set_matrix_eqn(n,dx,x); @solver_tdma; temperature=solver_tdma(a,b,c,d); %check the temperature at the n nodes temperature; plot(x,temperature,’o’); xlabel(’distance’); ylabel(’temperature’); hold on %plot the exact soln xx=0:0.01:1; t_exact=-exp(xx)+exp(1.0)*xx+1; plot(xx,t_exact,’r’); legend(’numerical result’,’exact temperature’);function x = generate_grid(n,dx) % %x = zeros(n); x(1)=0; for i=2:n x(i)=x(i-1)+dx; end function [a,b,c,d] = set_matrix_eqn(n,dx,x) % % a = zeros(n); for i=1:n a(i)=1.; b(i)=-2; c(i)=1; d(i)=-exp(x(i))*dx*dx; end a(1)=0.; b(1)=1.; c(1)=0.; d(1)=0.; a(n)=0.; b(n)=1.; c(n)=0.; d(n)=1.; May 17, 13 14:38 Page 1/2 1DconductionMcode.m function x = solver_tdma(a,b,c,f) % x = tridiag(a,b,c,f) % % Solve an nxn tridiagonal system with sub-diagonal a, diagonal b, % superdiagonal c, and rhs f % n = length(f); x = zeros(size(f)); c(1)=c(1)/b(1); f(1)=f(1)/b(1); % Forward elimination for i=2:n p = 1.0/(b(i)-c(i-1)*a(i)); c(i) = c(i)*p; f(i) = (f(i) - a(i)*f(i-1))*p ; end % Back substitution x(n) = f(n); for i=n-1:-1:1 x(i) = (f(i) - c(i)*x(i+1)); end May 17, 13 14:38 Page 2/2 1DconductionMcode.m Printed by Friday May 17, 2013 1/1 1DconductionMcode.m

description

code

Transcript of 1 d Conduction m Code

Page 1: 1 d Conduction m Code

clear all;close all;% set segments m=4, so the number of nodes n=(m+1)m=4;n=m+1;%set dxdx=1.0/m;@generate_grid;x=generate_grid(n,dx);@set_matrix_eqn;[a,b,c,d]=set_matrix_eqn(n,dx,x);@solver_tdma;temperature=solver_tdma(a,b,c,d);%check the temperature at the n nodestemperature;plot(x,temperature,’o’);xlabel(’distance’);ylabel(’temperature’);hold on%plot the exact solnxx=0:0.01:1;t_exact=−exp(xx)+exp(1.0)*xx+1;plot(xx,t_exact,’r’);legend(’numerical result’,’exact temperature’); function x = generate_grid(n,dx)%%x = zeros(n);x(1)=0;for i=2:n x(i)=x(i−1)+dx;end

function [a,b,c,d] = set_matrix_eqn(n,dx,x)%% a = zeros(n);for i=1:n a(i)=1.; b(i)=−2; c(i)=1; d(i)=−exp(x(i))*dx*dx;end

a(1)=0.;b(1)=1.;c(1)=0.;d(1)=0.;

a(n)=0.;b(n)=1.;c(n)=0.;d(n)=1.;

May 17, 13 14:38 Page 1/21DconductionMcode.m

function x = solver_tdma(a,b,c,f)% x = tridiag(a,b,c,f)%% Solve an nxn tridiagonal system with sub−diagonal a, diagonal b, % superdiagonal c, and rhs f %

n = length(f);x = zeros(size(f));c(1)=c(1)/b(1);f(1)=f(1)/b(1);% Forward eliminationfor i=2:n p = 1.0/(b(i)−c(i−1)*a(i)); c(i) = c(i)*p; f(i) = (f(i) − a(i)*f(i−1))*p ;end

% Back substitutionx(n) = f(n);for i=n−1:−1:1 x(i) = (f(i) − c(i)*x(i+1));end

May 17, 13 14:38 Page 2/21DconductionMcode.m

Printed by

Friday May 17, 2013 1/11DconductionMcode.m