ODE45 needs column vector from anonymous function

5 次查看(过去 30 天)
I am trying to be able to use this code to plot the solution to this differential equation with 4 initial conditions and eventually have a legend with labels for each line plotted.
So far I have the code and output:
options = odeset('RelTol',1e-4,'AbsTol',1e-2);
yprime = @(x,y) ((-x.*y)/(sqrt(6-(y.^2))));
y0 = [0.5 1.0 1.5 2.0];
tspan = [0 5];
[x,y] = ode45(yprime,tspan,y0);
plot(t,y)
grid on
xlabel('x')
ylabel('y')
legend('0.5','1.0','1.5','2.0')
Error using odearguments
@(X,Y)((-X.*Y)/(SQRT(6-(Y.^2)))) must return a column vector.
Error in ode45 (line 107)
odearguments(odeIsFuncHandle,odeTreatAsMFile, solver_name, ode, tspan, y0, options, varargin);
I tried adding yprime = yprime'; after line 2 to make the output into a column vector, but that gave the error: Unary operator ''' is not supported for operand of type 'function_handle'.
Any help is appreciated!

回答(2 个)

Star Strider
Star Strider 2022-5-10
Do element-wise division:
yprime = @(x,y) ((-x.*y)./(sqrt(6-(y.^2))));
and it does —
options = odeset('RelTol',1e-4,'AbsTol',1e-2);
yprime = @(x,y) ((-x.*y)./(sqrt(6-(y.^2))));
y0 = [0.5 1.0 1.5 2.0];
tspan = [0 5];
[t,y] = ode45(yprime,tspan,y0);
plot(t,y)
grid on
xlabel('x')
ylabel('y')
legend('0.5','1.0','1.5','2.0')
.

KSSV
KSSV 2022-5-10
options = odeset('RelTol',1e-4,'AbsTol',1e-2);
yprime = @(x,y) ((-x.*y)/(sqrt(6-(y.^2))));
Y = [0.5 1.0 1.5 2.0];
tspan = [0 5];
y = cell(length(Y),1) ;
figure
hold on
for i = 1:length(Y)
y0 = Y(i) ;
[x,y{i}] = ode45(yprime,tspan,y0);
plot(x,y{i}) ;
end
grid on
xlabel('x')
ylabel('y')
legend('0.5','1.0','1.5','2.0')

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

产品


版本

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by