首页 > 解决方案 > 使用词干时出错(第 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);

如您所见,即使由于此错误而未打印的迭代、根和错误的值

我该如何解决?

标签: matlabmatlab-figure

解决方案


在这种情况下,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

推荐阅读