How can i store absolute errors into a 1D array and then plot a e(k+1) against e(k)?

function Newton
% MATLAB M-file to solve a single equation using Newton's method.
% The function is f(x)= exp(x) - x - 2 = 0
clc % clear command window
clear % clear workspace
% Set the iteration number
x=input('Give the first starting value: ');% Set the starting value
k=0;
w=input('Give the final root for the first value: ');
diff = 1; % Set the difference between successive x values
% to an arbitrary value to start the iteration
while diff > 0.5e-5 % Continue until convergence is achieved to 5 decimal places
xlast = x;
x = xlast - f(xlast)/fd(xlast); % defines x(k+1) = xk - f(xk)/f'(xk)
diff = abs(x - xlast); % Calculate the difference between two successive iterations
ae=abs(x-w);
k = k + 1; % Add 1 to the iteration number
fprintf('%15.8f\n', ae) % Output the intermediate solutions to 6 decimal places
end
function y = f(x) % Define f(x)
y = x.^3 -2.44*x.^2 - 8.9216*x + 22.1952;
function z = fd(x) % Define f'(x)
z = 3*x^2 - 2*2.44*x - 8.9216;

2 Comments

@David Rogers: today I foramtted your code for you. In future you can do it yourself: select the code text, then click the {} Code button.
Using diff as a variable name interferes with using the MATLAB function diff()

Sign in to comment.

Answers (1)

ae(k) = abs(x-w);
After that you might want
plot(ae)
or
semilogy(ae)
or
plot(ae(2:end)./ae(1:end-1))

Tags

Asked:

on 12 Jan 2016

Answered:

on 12 Jan 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!