MATLAB: Fprintf into a stored variable

bisectionfprintfiMATLABmethodstoredtwovariable

Instead of using fprintf I want to store all the i, xe, and f(xe) into a vector instead. That way I can call them later. Also I had another problem where I wanted to use another 'i' later on in the code. But it only allowed me to use 1. How can you use two different 'i's. So they don't get mixed up.
f = @(x) x^2-6;
xl = 0;
xu = 10;
xe = (xu+xl)/(2);
acc = 0.00001;
while abs(f(xe))> acc
i = i + 1;
fprintf('%d)\t%f\tf(x)=%f\n',i,xe,f(xe));
if (f(xe)*f(xl)) < 0
xu = xe;
else
xl = xe;
end
xe = (xu+xl)/2;
end

Best Answer

Add
M = zeros( 0, 2 );
before the loop and replace
fprintf('%d)\t%f\tf(x)=%f\n',i,xe,f(xe));
by
M( end+1, 1:2 ) = [ xe, f(xe) ];
You'll get a warning about "Growing ..." , but if speed is acceptable ignore it.
&nbsp
"fprintf into a stored variable" &nbsp If understood literally, replace
fprintf('%d)\t%f\tf(x)=%f\n',i,xe,f(xe));
by
C{end+1,1} = sprintf('%d)\t%f\tf(x)=%f\n',i,xe,f(xe));
and add C=cell(0,1) before the loop