hw06_p01 - if (fid4 < 0) error('could not open...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
clear all clc c % open file fid = fopen('A.dat','r'); % 'r' means "read only" if (fid < 0) error('could not open file "A.dat"'); end; m = fscanf(fid,'%d',1); % read a matrix dimension m n = fscanf(fid,'%d',1); % read a matrix dimension n A_T = zeros(n,m); A_T = fscanf(fid, '%10f',[n,m]); fclose(fid); A = A_T' % convert to m columns and n row per line into m rows and n columns. fid2 = fopen('b.dat','r'); % 'r' means "read only" if (fid2 < 0) error('could not open file "b.dat"'); end; b_T = fscanf(fid2, '%10f',[1,inf]); % close the file fclose(fid2); b = b_T' % covert a row into a column b fid3 = fopen('x0.dat','r'); % 'r' means "read only" if (fid3 < 0) error('could not open file "x0.dat"'); end; x0_T = fscanf(fid3, '%10f',[1,inf]); % close the file fclose(fid3); x0 = x0_T' % covert a row into a column x % open file fid4 = fopen('hw06_p01_answer.txt','wt'); % 'wt' means "write text"
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: if (fid4 &lt; 0) error('could not open file &quot;hw06_p01_answer.txt&quot;'); end; e max = 10000; tol = 1.0e-6; x=x0; for i = 1:m r(i,1)=b(i,1)/A(i,i); end e i=1; while (i&lt;= max &amp;&amp; err &gt; tol) x_old=x; for j=1:m x(j,1) = r(j,1); for k=1:n if (k ~= j) x(j,1) = x(j,1) - (A(j,k)/A(j,j))*x(k,1); end end end % flag flag = 0; for j =1:m if (abs(x(j,1)-x_old(j,1)) &gt; tol) flag = 1; end end disp(i); % disp(x); if flag == 0 disp(x); fprintf(fid4,'Tolerance = %10.3e\n',tol); fprintf(fid4,'Number of iteration = %10d\n',i); fprintf(fid4,'Initial guesses are \n'); for i = 1:m fprintf(fid4,'%15.5f\n',x0(i,1)); end fprintf(fid4,'Gauss-Seidel method is converged and solutions are \n'); for i = 1:m fprintf(fid4,'%15.5f\n',x(i,1)); end fclose(fid4); return; end i=i+1; end fprintf(fid4,'Gauss-Seidel method did not converge'); fclose(fid4);...
View Full Document

Page1 / 2

hw06_p01 - if (fid4 &amp;amp;lt; 0) error('could not open...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online