# Critiqe MATLAB code

1. Oct 23, 2011

### roldy

This code calculates the internal temperatures of an insulated bar with left and right side boundary conditions of 350 K. The initial temperature of the bar is 250. This is not part of the assignment, but I want to get in the habit of optimizing my code. Is there any way to further improve the performance of the loops? For instance, instead of two FOR loops, combine them to make one FOR loop. I'm not looking for anything in terms of pre-allocating memory to arrays or matrices, that's basic. I'm just looking for other tips.

Basically what's going on here is that I'm solving for the interior temperatures at each time step using A\B. This is equivalent to solving these linear equations by hand using Gaussian elimination row operations. After solving for these temperatures. They are inserted into the main temperature matrix where the procedure is repeated. They are inserted into the main temperature matrix so that when the answer matrix, B, is calculated the temperatures can be pulled.

Code (Text):

%AE 339 Homework 8, Part B

clear all
clc

delta_tau=0.01;
delta_zeta=0.05;

%delta_t=0.05;
%delta_x=0.05;

endtime=.35;
barlength=1;
int=barlength/delta_zeta;

x=0:delta_zeta:barlength;
time=delta_tau:delta_tau:endtime;

lambda=delta_tau/delta_zeta^2;

M=int+1;              %number of spatial nodes
N=length(time);     %number of time nodes

U=zeros(N,M);
U0=250;
U1=350;
U2=350;

U(:,1)=U1;
U(:,int+1)=U2;
U_0=U0*ones(1,int+1);

U=cat(1,U_0, U);

for n=1:N

%Assemble the coefficient matrix
D=2*(1+lambda)*ones(1,int-1);               %Main diagonal
Dlambda=-lambda*ones(1,int-2);              %Upper and lower diagonal
A=diag(D)+diag(Dlambda,1)+diag(Dlambda,-1);

%U(n,i)=[(U(n,i-1)+U(n,i+1)+U(n+1,i-1)+U(n+1,i+1))*lambda+2*(1-lambda)*U(n,i)]/(2*(1+lambda))

%Assemble the answer matrix for the interior nodes i=2 to i=5
for i=2:M-1

B(i-1,1)=[U(n,i-1)+U(n,i+1)+U(n+1,i-1)+U(n+1,i+1)]*lambda+2*(1-lambda)*U(n,i);

end

%Compute the interior temperatures
C=A\B;
C=C';

%Insert solved interior temperatures into the temperature matrix
for k=1:length(C)

U(n+1,k+1)=C(k);

end

%non-dimensionalize temperature matrix
for y=1:n+1

for s=1:int+1
Theta(y,s)=(U(y,s)-U0)/(U1-U0);
end

end

end

Theta2=Theta(2,:);      %Row corresponding to t=.1
Theta5=Theta(5,:);      %Row corresponding to t=.25
Theta7=Theta(7,:);      %Row corresponding to t=.35

plot(x,Theta2,x,Theta5,x,Theta7)

xlabel('Distance (non-dimensional)')
ylabel('Non-Dimensional Temperature (K)')
title('Non-Dimensional Plate Temperature vs. Distance along plate')
h = legend('time=0.1','time=0.25 sec','time=0.35 sec','location','Best');
set(h,'Interpreter','none')