Invalid indexing for dsolve

2 次查看(过去 30 天)
matlab_day
matlab_day 2021-1-12
I am trying to make a plot of 2 ODE'S x(t), y(t) with the following code as explained in (https://www.mathworks.com/help/symbolic/solve-a-system-of-differential-equations.html):
syms x(t) y(t)
ode1 = diff(x) == x(t)*y(t) + 0.5*x(t)^3 + x(t)*y(t)^2;
ode2 = diff(y) == -y(t) - 2*x(t)^2 + x(t)^2*y(t);
odes = [ode1; ode2];
cond1 = x(0) == 0;
cond2 = y(0) == 1;
conds = [cond1; cond2];
[xSol(t), ySol(t)] = dsolve(odes,conds);
fplot(xSol)
hold on
fplot(ySol)
grid on
legend('uSol','vSol','Location','best')
However, I ge the following message: "In myODE (line 10)
Error using sym/subsindex (line 857)
Invalid indexing or function definition. Indexing must follow
MATLAB indexing. Function arguments must be symbolic
variables, and function body must be sym expression."
I'm not sure why there is an error since it matches the website I linked above. Thank you!

回答(1 个)

Star Strider
Star Strider 2021-1-12
The equations are nonlinear, and for most nonlinear differential equations, an analytic solution does not exist.
Try this instead:
syms x(t) y(t) T Y
ode1 = diff(x) == x(t)*y(t) + 0.5*x(t)^3 + x(t)*y(t)^2;
ode2 = diff(y) == -y(t) - 2*x(t)^2 + x(t)^2*y(t);
odes = [ode1; ode2];
cond1 = x(0) == 0;
cond2 = y(0) == 1;
conds = [cond1; cond2];
[VF,Subs] = odeToVectorField(odes);
ODEfcn = matlabFunction(VF, 'Vars',{T,Y});
[t, Sol] = ode45(ODEfcn, [0 1], [1 0]+eps);
figure
yyaxis left
plot(t, Sol(:,1))
yyaxis right
plot(t, Sol(:,2))
grid on
legend(string(Subs),'Location','N')
.
  14 个评论
matlab_day
matlab_day 2021-1-14
Thank you. I changed the initial conditions so that I would have x(0) = -5, -.4,...,.4, .5, and I wanted my interval for my independent variable to be from 0 to 10. When I used the following code:
comb_func = @(t,x)[x(1)*x(2) + 0.5*x(1)^3 + x(1)*x(2)^2; -x(2) - 2*x(1)^2 + x(1)^2*x(2)]; %System of ODES x(t) = x(1), y(t) = x(2)
tspan = [0 10]; % Choose Time Vector
for k = 1:11
ic = -.5 + k*.1; % Set Initial Conditions
[tc{k}, Sol{k}] = ode45(comb_func, tspan, ic); % Integrate & Store Results
end
it spit the error message
Index exceeds the number of array elements (1).
Error in myODE>@(t,x)[x(1)*x(2)+0.5*x(1)^3+x(1)*x(2)^2;-x(2)-2*x(1)^2+x(1)^2*x(2)]
(line 16)
which is weird because this error message doesn't appear when I change nothing else but replace the initial conditions line to the random number generator you had.
Star Strider
Star Strider 2021-1-14
You have 2 differential equations, so you need 2 initial conditions.
Try this:
ic = [-.5, k*0.1]; % Set Initial Conditions
That will not throw the same error, however you could still encounter the warning about an infinite result. (I did not test the integration code with those initial conditions, so I cannot determine that.)

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by