I'm defining a vector whose elements depend on time, i.e. I'm defining a real vector function of real elements that depend on the real scalar time variable. The vector function is named pdemand and I initially define it as pdemand[t_] := {a, b, c} in Mathematica (i.e. as a time-independent vector).

Now suppose I want to change the second element of that function from b to t^2. To begin with, as we know to select an element of a constant vector defined as v = {a, b, c} we type v[[2]]; and as we also know to call a scalar function defined as f[t_] := t^2 we type f[t]. However, for pdemand it looks like I have to both specify it is a time-dependent function as well as the element to choose, as pdemand[t][[2]].

All of this is shown in the following figure.

enter image description here

So good so far. Now suppose I want to select the second element of pdemand and set it to t^2. I tried typing pdemand[[2]] = t^2, pdemand[t][[2]] = t^2 and pdemand[t_][[2]] := t^2 but they failed, as shown in the following figure.

enter image description here

How can I successfully set the second element of the vector function pdemand[t] (currently set to b) to t^2?

  • 1
    $\begingroup$ This is not really doable in general. The issue is that pdemand[t_] could be an arbitrarily complicated function, where you have no way of knowing what to replace to change the second element. I guess you could hack something together for simple cases, but I am not sure that is the best solution: Changing the function definition in the middle of the program will likely lead to confusion, I would suggest you simply update the original definition instead, or create a new function (that could even call pdemand internally to get some of its elements) $\endgroup$
    – Lukas Lang
    Jul 23, 2021 at 8:51

1 Answer 1


pdemand[t_] := {a, b, c}

To replace the second part of pdemand use ReplacePart

ReplacePart[pdemand[t], 2 -> t^2]

(* {a, t^2, c} *)

If the second part is a symbol and you want to Set the symbol's value use

Evaluate[pdemand[t][[2]]] = t^2;


(* t^2 *)

EDIT: If you want to change the definition of pdemand, change its DownValues



(* {HoldPattern[pdemand[t_]] :> {a, b, c}} *)

DownValues[pdemand] = 
  ReplacePart[DownValues[pdemand], {1, -1, 2} -> t^2]

(* {HoldPattern[pdemand[t_]] :> {a, t^2, c}} *)


(* {a, 1, c} *)
  • $\begingroup$ Note that your last example won't work as expected: pdemand[1] returns {a, t^2, c}, not {a, 1, c} $\endgroup$
    – Lukas Lang
    Jul 23, 2021 at 14:47
  • $\begingroup$ @LukasLang - The last example sets the definition for b it doesn't change the definition of pdemand. To get the result that you expect, use pdemand[t] /. t -> 1 after b is defined. $\endgroup$
    – Bob Hanlon
    Jul 23, 2021 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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