Closure
Closure

Reputation: 147

matlab plot vectors must be the same lengths

I am writing a program regarding solving the following boundary value problem using shooting-bisection method:

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

I first convert this to a system of first order equations, set

y'=z

then I let dydt represent the vector (y',z'), and come up with the script file:

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

With this, I then came up with the following code:

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')

Then I run the program, MATLAB said I'm using the plot argument incorrectly, where plot vectors must be the same lengths. I have no idea how to fix this problem. Any help is appreciated.

Upvotes: 1

Views: 300

Answers (1)

horchler
horchler

Reputation: 18484

Your Y, Z and W outputs are from different runs of ode113. The output independents variables, G from each run are different because ode113 is an adaptive solver. There are two ways you can fix this. You can save your G outputs as separate variables:

...
[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');

Or you could specify a fixed set of output points by specifying more than two points for tspan (second argument to ode113):

...
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');

Unless your version of Matlab is more than 10 years old, you should also specify your integration function, shoot, via a function handle, not a string, i.e.:

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

Upvotes: 2

Related Questions