I am dealing with a very simple code, which turns to be slow when I try to plot the final Piecewise function. Is the code computing back again the integral iteratively rather than just substituting d=2 and easily plotting?
AbsoluteTiming[g[t_, d_] = Integrate[d*Sin[t - t1]*f[t1], {t1, 0, t},
Assumptions -> t \[Element] Reals && d \[Element] Reals]]
AbsoluteTiming[f[t1_] = Piecewise[{{-t1^2, 0 <= t1 <= 3}, {t1, t1 > 3}}]]
AbsoluteTiming[g[t, d]]
Plot[g[t, 2], {t, 0, 5}]
Even if I use /.d->2 inside Plot it is very slow.
So what I did is the following, trying to avoid the Evaluate and understand why I had problems (which seem to come from that 4th raw g[t,d]. Two ways worked well: 1) changing the order of the rows
AbsoluteTiming[
f[t1_] = Piecewise[{{-t1^2, 0 <= t1 <= 3}, {t1, t1 > 3}}]]
AbsoluteTiming[
g[t_, d_] =
Integrate[d*Sin[t - t1]*f[t1], {t1, 0, t},
Assumptions -> t \[Element] Reals && d \[Element] Reals]]
AbsoluteTiming[g[t, d]]
Plot[g[t, 2], {t, 0, 5}]
or 2) changing the initial definition of g[t_,d_] into g[t_]deleting g[t,d] and defining a new function:
AbsoluteTiming[
g[t_] = Integrate[d*Sin[t - t1]*f[t1], {t1, 0, t},
Assumptions -> t \[Element] Reals && d \[Element] Reals]]
AbsoluteTiming[
f[t1_] = Piecewise[{{-t1^2, 0 <= t1 <= 3}, {t1, t1 > 3}}]]
h[t_, d_] = g[t]
Plot[h[t, 2], {t, 0, 5}]
I think Mathematica gets confused because of that g[t,d] definition after g[t_,d_]? Anyone can explain why?
rather than g[t_,d_] and then a new function, such as h[t_,d_]=g[t_] and then plot h[t,2], it works. Why?
– Andrea G Mar 29 '17 at 09:10Plothas the attributeHoldAlland as the documentation will tell you in the section Detail & Options sometimes anEvaluatewill help, so this runs fast:Plot[ Evaluate@g[ t, 2 ], {t,0,5}]. – gwr Mar 29 '17 at 09:32SetOptions[Plot, Evaluated -> True];. Or, the shortest way:Plot @@ {g[t, 2], {t, 0, 5}}, which is fast because of what @gwr told you. – Rolf Mertig Mar 29 '17 at 09:37Evaluatedto be found in the documentation? It is neither listed by itself, nor underPlotorGraphicsnor to be found in the tutorials about evaluation... – gwr Mar 29 '17 at 09:51Evaluateto me seems saver. – gwr Mar 29 '17 at 10:57Evaluatedis an undocumented option, but has been there for quite a while. – J. M.'s missing motivation Mar 29 '17 at 11:03f@expris a Short Form for thePrefixnotation. – gwr Mar 29 '17 at 11:08f[x],f @ x, andx // fare equivalent expressions. – J. M.'s missing motivation Mar 29 '17 at 11:14SetandSetDelayed. See this. – gwr Mar 29 '17 at 12:11