How do I use a loop variable in the initial conditions in dsolve?

4 次查看(过去 30 天)
I am trying to build a loop which calls dsolve with different initial conditions in each iteration. To accomplish this, I built this loop:
y0 = -2:0.5:2;
y1 = -2:2:2;
syms y(t)
for i = y1
for k = y0
y(t) = dsolve(diff(y,2) + diff(y) - 2*y == t^2 - 4*t + 3,...
['y(0) == ',num2str(k)],['Dy(0) == ',num2str(i)])
end
end
It works through the first iteration, but it fails for the second one with this error:
Error using mupadengine/feval (line 157)
MuPAD error: Error: Invalid equation or initial condition. [ode::splitSys]
Error in dsolve>mupadDsolve (line 325)
T = feval(symengine,'symobj::dsolve',sys,x,options);
Error in dsolve (line 186)
sol = mupadDsolve(args, options);
Error in Blatt4_A5_MWE (line 9)
y(t) = dsolve(diff(y,2) + diff(y) - 2*y == t^2 - 4*t + 3,...
The command works outside the loop for all the initial conditions I have tried. Inside the loop, the first iteration works, the next one always fails. It does not seem to matter which ones I choose.
What's going on?

采纳的回答

Stephen Bosch
Stephen Bosch 2013-6-28
You are assigning the first solution to the function y on the first iteration. When dsolve is executed again, y contains the first solution, and dsolve can't interpret that.
The answer is to use a different variable for the solution to the ODE, like so
y0 = -2:0.5:2;
y1 = -2:2:2;
syms y(t)
for q = y1
for k = y0
ysol(t) = dsolve(diff(y,2) + diff(y) - 2*y == t^2 - 4*t + 3,...
['y(0) == ',num2str(k)],['Dy(0) == ',num2str(q)])
end
end
Also, it is inadvisable to use i as a loop variable, even though it works in this case.
Many thanks to slitvinov, who helped with this problem on StackOverflow.

更多回答(0 个)

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by