ODE45 needs column vector from anonymous function

3 views (last 30 days)
Austin C
Austin C on 10 May 2022
Answered: KSSV on 10 May 2022
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!

Answers (2)

Star Strider
Star Strider on 10 May 2022
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 on 10 May 2022
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')

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!