matlab - 使用词干时出错(第 43 行)X 的长度必须与 Y 相同
问题描述
我正在尝试使用带有stem的matlab对二等分方法进行错误计算,每次迭代都会通过abs(x2-x1)计算错误,所以我需要使用stem绘制它,输出必须是这样的:
这是我的代码:
close all; clear ; clc;
syms x;
f=@(x)(x^(2))-(2);
x1=1;
x2=2;
acc=10^(-8);
n=0;
disp (' Bisection Method')
disp ('===========================================')
disp ('iteration root(P-hat) error')
while (abs(x2-x1)>acc)
n = n + 1;
xm=(x1+(x2-x1)/2);
if (f(x1)*f(xm)<0)
x2=xm;
else
x1=xm;
end
figure(1)
X = linspace(0,30);
Y = abs(x2-x1);
stem(X,Y);
grid on
hold on
fprintf('%3d %20.8f %20.10f \n', n, xm, abs(x2-x1));
end
这个错误向我显示:
Bisection Method
===========================================
iteration root(P-hat) error
Error using stem (line 43)
X must be same length as Y.
Error in Ass1Bisection (line 28)
stem(X,Y);
如您所见,即使由于此错误而未打印的迭代、根和错误的值
我该如何解决?
解决方案
在这种情况下,Y 被创建为空,并且指令Y(end+1)
将使其添加一个元素。
close all; clear ; clc;
syms x;
f=@(x)(x^(2))-(2);
x1=1;
x2=2;
acc=10^(-8);
n=0;
disp (' Bisection Method')
disp ('===========================================')
disp ('iteration root(P-hat) error')
Y = []
while (abs(x2-x1)>acc)
n = n + 1;
xm=(x1+(x2-x1)/2);
if (f(x1)*f(xm)<0)
x2=xm;
else
x1=xm;
end
figure(1)
Y(end+1) = abs(x2-x1);
stem(1:length(Y),Y);
grid on
hold on
fprintf('%3d %20.8f %20.10f \n', n, xm, abs(x2-x1));
end
推荐阅读
- sql - 在另一列最大的列上连接表
- javascript - 使用代理时如何停止NodeJS“请求”模块更改请求
- java - PDF java 跟踪器
- javascript - 将状态列表下拉 HTML 链接到特定页面
- verilog - 案例变量是否应该以原子方式递增?
- swift - 使用 swift 使 DispatchQueue 异步崩溃
- javascript - 如何根据值更改@html 对象属性
- python - 如何将串行数据从数字倾角仪转换为 Python 中的可读格式?
- jmeter - 在另一个测试计划中引用在 Jmeter 中有一组采样器的线程组?
- ms-access - 访问来自不同行的合并文本