# Solving ODE in Mathematica

I want to solve an ODE in the form $\{y'[t] == f[y[t]], y[2] == \{1, 2, 3\}\}$ using NDSolve in Mathematica, where $f: R^3 \rightarrow R^3$ is defined as follows,

f[y_] := {2 y[[1]] + 1, 3 y[[2]] + y[[3]], 2 y[[3]] + y[[1]]}
s = NDSolve[{y'[t] == f[y[t]], y[2] == {1, 2, 3}}, y, {t, 0, 10}]
Plot[First[y /. s][t], {t, 0, 10}]


However, when I run the code it says "Part::partw: "Part 2 of y(t) does not exist."". How can I solve the problem?

-
Did you forget double brackets in your expression? – Grumpy Parsnip Sep 11 '11 at 18:43
Hm, I do not know if Mathematica supports functions taking more than 1 arguments in NDSolve. Try to formulate question in terms of yx, yy and yz, instead, each taking t as argument, and they represent x, y resp. z. – Per Alexandersson Sep 11 '11 at 18:48
If I remove $f$, e.g. {y'[t] == 2 y[t], y[2] == {1, 2, 3}}, it can be easily solved. – Helium Sep 11 '11 at 18:53

Changing definition of $y$ and making as many equations as there are functions in $y$ could help here. This one works:

f[y_] := {2 y[[1]] + 1, 3 y[[2]] + y[[3]], 2 y[[3]] + y[[1]]}
y[t_] = {y1[t], y2[t], y3[t]};
s = NDSolve[{#[[1]] == #[[2]]&/@Transpose[{y'[t], f[y[t]]}],
#[[1]] == #[[2]]&/@Transpose[{y[2], {1, 2, 3}}]},
y[t], {t, 0, 10}]
Plot[First[y[t] /. s], {t, 0, 10}]

-
Well, it really works but what's the difference between #[[1]] == #[[2]]&/@Transpose[{y'[t], f[y[t]]}] and y'[t] == f[y[t]]? – Helium Sep 11 '11 at 19:16
The first one gives list of three equalities and the second only one equality (of lists) which seems not to work. – Andrew Sep 11 '11 at 19:24
Thanks Andrew, your solution is perfect for the above problem. But actually, the function $f$ must be more complicated than the above one. It has some local variables and ifs. When I use something like this f[y_] := Module[{test}, If[y[[1]] > 2, test = 1, test = 2]; Return[{test y[[2]], y[[2]] + y[[3]], y[[3]] + y[[1]]}]]; I get an error NDSolve::ndnum: Encountered non-numerical value for a derivative t==2. Any idea? – Helium Sep 12 '11 at 4:38
@Mohsen: I'd try to use Piecewise[] instead of If[]. Something like f[y_List] := {Piecewise[{{1, y[[1]] > 2}, {2, True}}]*y[[2]], y[[2]] + y[[3]], y[[3]] + y[[1]]} – J. M. Sep 12 '11 at 6:10

Thread[] is your friend:

f[y_] := {2 y[[1]] + 1, 3 y[[2]] + y[[3]], 2 y[[3]] + y[[1]]};
y[t_] = {y1[t], y2[t], y3[t]};