My plot does not show anything

f = @(x) cos(x) - 0.3*x;
ea = 999;
es = 0.01;
x_upper = 2;
x_lower = 0;
x_mid = x_upper;
n = 0;
while ea > es
n = n+1;
x_mid = (x_upper + x_lower)/2;
ea = abs((x_mid - x_old) / x_mid);
fnew = f(x_mid);
f1 = f(x_lower);
if fnew*f1 < 0
x_upper = x_mid;
else
x_lower = x_mid;
end
x_old = x_mid;
end
plot(n,ea)

回答(1 个)

Your plot does show anything. The only problem, is that you cannot see it.
The variable ea and n is overwritten in each iteration. After the loop both are scalars and with plot you draw one point only. This is only visible if you use a marker like 'o' (see Birdman's solution). Alternatively you can create a vector:
f = @(x) cos(x) - 0.3*x;
ea = 999;
es = 0.01;
x_upper = 2;
x_lower = 0;
x_mid = x_upper;
ea_list = [];
while ea > es
x_mid = (x_upper + x_lower) / 2;
ea = abs((x_mid - x_old) / x_mid);
ea_list(end+1) = ea;
fnew = f(x_mid);
f1 = f(x_lower);
if fnew * f1 < 0
x_upper = x_mid;
else
x_lower = x_mid;
end
x_old = x_mid;
end
plot(1:length(ea_list), ea_list, 'o')
In the line "ea_list(end+1) = ea;" the editor will show a warning, because letting an array grow iteratively is very expensive. But the run-time does not matter here. Search in the forum for "pre-allocation" for details.

类别

在 帮助中心 和 File Exchange 中查找有关 Octave 的更多信息

标签

回答:

Jan
2018-2-1

Community Treasure Hunt

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

Start Hunting!

Translated by