Error in the program at startup

1 view (last 30 days)
Anastasya
Anastasya on 12 Jun 2023
Answered: Mrinal Anand on 13 Jun 2023
Code:
f =@(x) x^3 - 2*x - 5; % задаем функцию f(x)
g = @(x) x - f(x);
a = 2; % задаем границы отрезка [a;b]
b = 3;
M1 = @(x) max(abs(4*del2(f(x)))); % оценка модуля производной второго порядка функции f на промежутке [a;b]
x0 = (a+b)/2; % начальное приближение
N_apr = @(x) ceil(log(M1(x)*(b-a)/eps)/log(2)); % априорная оценка числа итераций
N_post = 0; % счетчик числа итераций
while true
x1 = g(x0); % итерация метода простых итераций
N_post = N_post + 1;
if abs(x1-x0) < eps*(1-M1(x1))/M1(x1) % проверка условия окончания итераций
break;
end
x0 = x1;
end
disp(['Приближенное решение: x = ', num2str(x1)]);
disp(['Число итераций: N = ', num2str(N_post)]);
disp(['Априорная оценка числа итераций: N_apr = ', num2str(N_apr(x1))]);
% построение графика функции и точек итераций
xx = linspace(a,b,100);
yy = f;
plot(xx, yy,'LineWidth',2);
hold on;
plot(xx,xx,'--','LineWidth',2);
for i=0:N_post
plot(x0-f(x0),f(x0),'ro','MarkerSize',8);
plot([x0,x0-f(x0)],[f(x0),f(x0)],'r--');
plot([x0-f(x0),x0-f(x0)],[f(x0),f(x0-f(x0))],'r--');
x0 = x0 - f(x0);
end
xlabel('x');
ylabel('f(x)');
legend('f(x)','y=x','точки итераций');
hold off;
Mistake:
Error using plot
Invalid data argument.
Error in kkk (line 27)
plot(xx, yy,'LineWidth',2);

Answers (1)

Mrinal Anand
Mrinal Anand on 13 Jun 2023
The error is because of the line:
yy = f
Since f is a function and you want to plot it f(xx), the line should be:
yy = f(xx)
In addition, the definition of f in the first line contains the power operator (^), which will give an error with non-square matrices, such as 'xx' defined in the code. you can change it to element wise power operator (.^) if you want to run it for non-square matrices.

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!