I'm in a numerical analysis class and we've been going over Jacobi iteration and GaussSeidel. I understand the problems, and how to code them, but i'm having a problem with unwanted answers being shown in the command window. As i'm using the diary command to print the code and the answers, this is a problem. Here's my code:
%% P2.78
a1 = [7 3 4];
a2 = [2 5 3];
a3 = [3 2 6];
b = [6 5 2];
x1(1)=0;
x2(1)=0;
x3(1)=0;
i(1)=1;
epsilon=1.*10^5;
residual=10;
while residual > epsilon
x1(i+1)=x1(i) + (1./a1(1)).*(b(1)  a1(1).*x1(i)  a1(2).*x2(i)  a1(3).*x3(i));
x2(i+1)=x2(i) + (1./a2(2)).*(b(2)  a2(1).*x1(i)  a2(2).*x2(i)  a2(3).*x3(i));
x3(i+1)=x3(i) + (1./a3(3)).*(b(3)  a3(1).*x1(i)  a3(2).*x2(i)  a3(3).*x3(i));
i=i+1;
residual(i)=abs(7.*x1(i)  3.*x2(i) +4.*x3(i) 6);
end
fid=fopen('P278.txt','w+');
fprintf(fid,'i x1 x2 x3 Residual\n');
for k=1:max(i);
fprintf(fid,'%u %f %f %f %f\n',k,x1(k),x2(k),x3(k),residual(k));
end
fclose(fid);
type('P278.txt')
%% P2.81
% Part a
a1 = [4.63 1.21 3.22];
a2 = [3.07 5.48 2.11];
a3 = [1.26 3.11 4.57];
b = [2.22 3.17 5.11];
x1(1)=0;
x2(1)=0;
x3(1)=0;
i=1;
epsilon=1.*10^5;
residual=10;
while residual > epsilon
x1(i+1)=x1(i) + (1./a1(1)).*(b(1)  a1(1).*x1(i)  a1(2).*x2(i)  a1(3).*x3(i));
x2(i+1)=x2(i) + (1./a2(2)).*(b(2)  a2(1).*x1(i)  a2(2).*x2(i)  a2(3).*x3(i));
x3(i+1)=x3(i) + (1./a3(3)).*(b(3)  a3(1).*x1(i)  a3(2).*x2(i)  a3(3).*x3(i));
i=i+1;
residual(i)=abs(4.63.*x1(i)  1.21.*x2(i) +3.22.*x3(i) 2.22);
end
fid=fopen('P281a.txt','w+');
fprintf(fid,'i x1 x2 x3 Residual\n');
for k=1:max(i);
fprintf(fid,'%u %f %f %f %f\n',k,x1(k),x2(k),x3(k),residual(k));
end
fclose(fid);
type('P281a.txt')
%Part b
a1 = [4.63 1.21 3.22];
a2 = [3.07 5.48 2.11];
a3 = [1.26 3.11 4.57];
b = [2.22 3.17 5.11];
x1(1)=0;
x2(1)=0;
x3(1)=0;
i=1;
epsilon=1.*10^5;
residual=10;
while residual > epsilon
x1(i+1)=x1(i) + (1./a1(1)).*(b(1)  a1(1).*x1(i)  a1(2).*x2(i)  a1(3).*x3(i));
x2(i+1)=x2(i) + (1./a2(2)).*(b(2)  a2(1).*x1(i+1)  a2(2).*x2(i)  a2(3).*x3(i));
x3(i+1)=x3(i) + (1./a3(3)).*(b(3)  a3(1).*x1(i+1)  a3(2).*x2(i+1)  a3(3).*x3(i));
i=i+1;
residual(i)=abs(4.63.*x1(i)  1.21.*x2(i) +3.22.*x3(i) 2.22);
end
fid=fopen('P281b.txt','w+');
fprintf(fid,'i x1 x2 x3 Residual\n');
for k=1:max(i);
fprintf(fid,'%u %0.5f %0.5f %0.5f %0.5f\n',k,x1(k),x2(k),x3(k),residual(k));
end
fclose(fid);
type('P281b.txt')
When i run the code, i get the tables i was trying to make with fprintf, but i also get ans=63,ans=59,etc. Where is this coming from?
