Matlab 使用阀杆(第43行)时出错X的长度必须与Y的长度相同
我正在尝试用matlab和stem计算二分法的误差 abs(x2-x1)为每次迭代计算误差,所以我需要使用stem绘制它 输出必须如下所示: 这是我的代码:Matlab 使用阀杆(第43行)时出错X的长度必须与Y的长度相同,matlab,matlab-figure,Matlab,Matlab Figure,我正在尝试用matlab和stem计算二分法的误差 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 ('===========================
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
如您所见,迭代、根和错误的值即使由于此错误也无法打印
如何解决此问题?在这种情况下,Y被创建为空,指令
Y(end+1)
将使其添加一个元素
全部关闭;清楚的clc;
符号x;
f=@(x)(x^(2))-(2);
x1=1;
x2=2;
acc=10^(-8);
n=0;
disp(‘二分法’)
disp('======================================================================================================')
disp('迭代根(P-hat)错误')
Y=[]
而(abs(x2-x1)>acc)
n=n+1;
xm=(x1+(x2-x1)/2);
如果(f(x1)*f(xm)在这种情况下Y被创建为空,并且指令Y(end+1)
将使其添加一个元素
全部关闭;清除;clc;
符号x;
f=@(x)(x^(2))-(2);
x1=1;
x2=2;
acc=10^(-8);
n=0;
disp(‘二分法’)
disp('======================================================================================================')
disp('迭代根(P-hat)错误')
Y=[]
而(abs(x2-x1)>acc)
n=n+1;
xm=(x1+(x2-x1)/2);
if(f(x1)*f(xm)
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);