loglog plots with secant method

조회 수: 4 (최근 30일)
Kevin Osborn
Kevin Osborn 2021년 10월 2일
댓글: Mathieu NOE 2021년 10월 4일
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
Kevin Osborn
Kevin Osborn 2021년 10월 2일
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 2021년 10월 4일
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 ?

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by