Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

I'm having problems working with the output from DSolve whilst in a module. To handle the result outside a module typically I would do something like

 f[t] = y[t] /. solution

But inside a module my t is now t$ followed by some numbers. How can I create and return a function from the output of DSolve inside a module?

Here is my code:

  equations = {y''[t]== -m g,y'[0]==100,y[0]==0};
  solution = Flatten@ DSolve[equations,y,t];
  h[t] = y[t] /. solution;

I get h = 100. t$16608-4.9 t$16608^2, but h[1] = h$16909[1).

share|improve this question

marked as duplicate by Oleksandr R., Artes, Jens, Sjoerd C. de Vries, R. M. Mar 29 '13 at 18:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

OK, it is not clear what you try to achieve. There is an architectural error if you try to return an lokal variable like h. Furthermore, (in your additional post) you don't return a function! You return only an expression. Can you please clear up what exactly you try and how you want to use it? Btw, you can edit your question and improve it. Don't write an additional post. – halirutan Feb 27 '13 at 10:05
I think the most straightforward answer is just "use Block rather than Module in this case", so I voted to close this as a duplicate of a question the explains the distinctions rather well. – Oleksandr R. Mar 28 '13 at 23:08
See… You're using Set (=) instead of SetDelayed (:=); and you should use a pattern h[t_]. You could also simply skip h and return y[1] /. solution. – Michael E2 Mar 29 '13 at 11:42

If I understand you correctly, you can use DSolve[eqs, y, t] instead of DSolve[eqs, y[t], t] to get a rule like y -> Function[ arg, ... ], so the t, whether it's local or not, will not make difference.

Module[{t}, DSolve[y'[t] == t, y, t] ]
{{y -> Function[{t$31879}, t$31879^2/2 + C[1]]}}
y[t] /. %
{t^2/2 + C[1]}
share|improve this answer

You could return a pure function. Like this

m = 1;
g = 9.8;

h = Module[{equations, solution, t},
      equations = {y''[t] == -m g, y'[0] == 100, y[0] == 0};
      solution = First@Flatten@DSolve[equations, y[t], t];
      With[{x = Last @solution /. t -> #1}, x &]]
100. #1 - 4.9 #1^2 &


share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.