matlab 绘图向量的长度必须相同

matlab plot vectors must be the same lengths

我正在编写一个程序,使用射击二分法解决以下边界值问题:

y''-y+x=0, y(0)=y(1)=0.

我首先将其转换为一阶方程组,设置

y'=z

然后我让dydt代表向量(y',z'),并得出脚本文件:

function dydt=shoot(t,y)
dydt=[y(2);y(1)-t]
end

有了这个,我想出了下面的代码:

clear
clc
a=0;
b=1;
alpha=0;
beta=0;
s(1)=(beta-alpha)/(b-a);
s(2)=-1
[G,Y]=ode113('shoot',[a b],[alpha;s(1)]);
[G,Z]=ode113('shoot',[a b],[alpha;s(2)])
hold
tol=1e-4
u=s(1);
v=s(2);
while abs(u-v)>tol;
s(3)=(u+v)/2;
[G,W]=ode113('shoot',[a b],[alpha;s(3)]);
if W(end,1)>0
    u=s(3);
else
    v=s(3);
end
end

 [G,W]=ode113('shoot',[a b],[alpha;s(3)])

plot(G,Y(:,1),'-o', G,Z(:,1),'-o',G,W(:,1),'-o')

然后我 运行 程序,MATLAB 说我错误地使用了绘图参数,其中绘图向量的长度必须相同。我不知道如何解决这个问题。感谢任何帮助。

您的 YZW 输出来自 ode113 的不同 运行。每个 运行 的输出独立变量 G 是不同的,因为 ode113 是自适应求解器。有两种方法可以解决此问题。您可以将 G 输出保存为单独的变量:

...
[Gy,Y]=ode113('shoot',[a b],[alpha;s(1)]);
[Gz,Z]=ode113('shoot',[a b],[alpha;s(2)]);
...
[Gw,W]=ode113('shoot',[a b],[alpha;s(3)]);
plot(Gy,Y(:,1),'-o', Gz,Z(:,1),'-o',Gw,W(:,1),'-o');

或者您可以指定一组固定的输出点 by specifying more than two points for tspanode113 的第二个参数):

...
tspan = linspace(a,b,50);
[G,Y]=ode113('shoot',tspan,[alpha;s(1)]);
[G,Z]=ode113('shoot',tspan,[alpha;s(2)]);
...
[G,W]=ode113('shoot',tspan,[alpha;s(3)]);
plot(G,Y(:,1),'-o', G,Z(:,1),'-o',G,W(:,1),'-o');

除非您的 Matlab 版本超过 10 年,否则您还应该通过 function handle 而非字符串指定积分函数 shoot,而不是字符串,即:

[Gw,W]=ode113(@shoot,[a b],[alpha;s(3)]);