loglog plots with secant method

3 visualizzazioni (ultimi 30 giorni)
Kevin Osborn
Kevin Osborn il 2 Ott 2021
Commentato: Mathieu NOE il 4 Ott 2021
I am trying to make a loglog plot of the secant method. I have ran this exact code below before and it worked fine, and now when I run it today, it's not working anymore.
%Secant Methods
%Secant Method x0 = 2.5, x1 = 2.4
func = @(x) 2*exp(-2*x) + 4*sin(x) - 2*cos(2*x);
x1 = 2.5;
x2 = 2.4;
tol = 1e-9;
f1 = func(x1);
dx = inf;
iter = 0;
dispdata = [iter;x1;x2]
while abs(dx) > tol
iter = iter + 1;
f2 = func(x2);
dx = (x2 - x1)*f2/(f2 - f1);
x1 = x2;
f1 = f2;
x2 = x2 - dx;
dispdata(:, iter + 1) = [iter;x1;x2];
end
fprintf('Iteration x1 x2\n')
fprintf('--------------------------------\n')
fprintf('%2d: %7.4f %7.4f\n', dispdata)
y = log(abs(x(3:end) - x(2:end-1)));
x = log(abs(x(2:end-1) - x(1:end-2)));
p = polyfit(x,y,1);
alpha = p(1);
lambda = exp(p(2));
scatter(x,y)
hold on
plot(x, alpha*x + log(lambda))
hold off
xlabel('ln|z_{n} - z_{n-1}|')
ylabel('ln|z_{n+1} - z_{n}|')
title(['Y_{n} = ', num2str(alpha), 'X_{n} - ', num2str(lambda)])
legend('Data', 'Fitted line', 'location', 'southeast')
Now I am getting the error message, "The end operator must be used within an array index expression."
  2 Commenti
Kevin Osborn
Kevin Osborn il 2 Ott 2021
I think it has something to do with the two lines
y = log(abs(x(3:end) - x(2:end-1)));
x = log(abs(x(2:end-1) - x(1:end-2)));
They will not run by themselves anymore, giving me that error message regarding the end operator. How do I fix this error?
Mathieu NOE
Mathieu NOE il 4 Ott 2021
hello
yes , at this stage , x is a scalar , so those lines cannot work . It will create an empty x and y
what is the intention , is x supposed to be an array before these two lines ?

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by