0
$\begingroup$

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?

  • 0
    Did you forget double brackets in your expression?2011-09-11
  • 0
    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.2011-09-11
  • 0
    If I remove $f$, e.g. {y'[t] == 2 y[t], y[2] == {1, 2, 3}}, it can be easily solved.2011-09-11

2 Answers 2

1

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}] 
  • 0
    Well, it really works but what's the difference between #[[1]] == #[[2]]&/@Transpose[{y'[t], f[y[t]]}] and y'[t] == f[y[t]]?2011-09-11
  • 1
    The first one gives list of three equalities and the second only one equality (of lists) which seems not to work.2011-09-11
  • 0
    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?2011-09-12
  • 0
    @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]]}`2011-09-12
2

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]}; s = NDSolve[Join[Thread[y'[t] == f[y[t]]], Thread[y[2] == {1, 2, 3}]],     y[t], {t, 0, 10}]; Plot[First[y[t] /. s], {t, 0, 10}] 
  • 0
    Thanks J.M., good point. Do you have any idea about my comment under Andrew's answer?2011-09-12