MATLAB: Text output to a file

fprintfoutputtext file

Trying to essentially create a table similar to this
iter xL f(xL) xU f(xU) xR f(xR) ea
1 10.00000 -528.89877 50.00000 1772.65758 30.000000000 158.91822 100.00000
2 10.00000 -528.89877 30.00000 158.91822 20.000000000 -238.72334 50.00000
3 20.00000 -238.72334 30.00000 158.91822 25.000000000 -56.91554 20.00000
but instead I recieve the output in a sinlge line like this
iter xL func(xL) xU func(xU) xR func(xR) ea
1 10.00000 -528.89877 50.00000 1772.65758 30.000000000 158.91822 2 10.00000 -528.89877 30.00000 158.91822 20.000000000 -238.72334 3 20.00000 -238.72334 30.00000 158.91822 25.000000000 ...
Im sure there is something with this part of the code but I dont know what else besides \n it could be
while (1)
xrold = xr;
xr = (xL + xU)/2;
iter = iter + 1;
fprintf(fid,'%2i\t%9.5f %9.5f %9.5f %9.5f %9.9f %9.5f %9.5f\n',iter,xL,func(xL),xU,func(xU),xr,func(xr));
if xr ~= 0
ea= abs((xr - xrold)/xr)*100; end
test = func(xL,varargin{:})*func(xr,varargin{:});
Below is the entire code :
function [root, ea , iter] = bisecting(func, xL, xU, es, maxit, varargin)
%bisect : root location zeroes
%uses bsection method to find the root of a func
%input:
%func = function handle
%xl, xu = lower and upper guesses
% es = desired relative error (default = 0.0001%)
%maxit = maximum allowable iterations (default = 50)
%output:
%root = real root
%ea = approximate relative error (%)
%iter = number of iterations
if nargin<3, error('At least 3 input arguements required'),end
test = func(xL, varargin{:})*func(xU,varargin{:});
if test > 0, error('No sign change'),end
if nargin < 4 || isempty(es), es = 0.0001; end
if nargin < 5 || isempty(maxit), maxit = 50;end
iter = 0; xr = xL;
fid = fopen('Bisecting.txt','wt');
fprintf(fid,'%2s %8s %10s %10s %10s %10s %10s %10s\n','iter',...
'xL','func(xL)','xU','func(xU)','xR','func(xR)','ea');
while (1)
xrold = xr;
xr = (xL + xU)/2;
iter = iter + 1;
fprintf(fid,'%2i\t%9.5f %9.5f %9.5f %9.5f %9.9f %9.5f %9.5f\n',iter,xL,func(xL),xU,func(xU),xr,func(xr));
if xr ~= 0
ea= abs((xr - xrold)/xr)*100; end
test = func(xL,varargin{:})*func(xr,varargin{:});
if test < 0
xU = xr;
elseif test > 0
xL = xr;
else
ea = 0;
end
if ea <= es || iter >= maxit, break, end
end
root = xr;
fclose(fid);
type bisecting.txt
Edit: I posted the incorrect code the first time

Best Answer

You have 8 % signs in your format specifier; however, you have provided only seven values. Specify the value of ea at the end
fprintf(fid,'%2i\t%9.5f %9.5f %9.5f %9.5f %9.9f %9.5f %9.5f\n',iter,xL,func(xL),xU,func(xU),xr,func(xr), ea)
% ^ add this