I am trying to use a do loop to make a vector of an arbitrary number of functions that can be evaluated later. I think the problem I am having is because of the AppendTo function in my code, because when I hard code a short vector it does what I want. For example:

Y[{x_}] = {x} + {3}
(*works, but*)
X[{x_}] = {};
Do[AppendTo[X[{x}], x + 3], 1];

does not. Does anyone have any tips or advice to make this work?

  • $\begingroup$ Check X[{x}] to see what your Do[AppendTo[... is doing. To get what you seek, you would need to somehow include your Do[AppendTo[... inside the definition of X[{x_}], which isn't natural. Are you trying to do something else with this? If you tell us what that is, we can better help you. As written, your first method (though you should use SetDelayed rather than Set) appears to be the natural way to do it. $\endgroup$
    – jjc385
    Nov 12 '17 at 1:40
  • $\begingroup$ Have you seen Function and its shorthand &? $\endgroup$
    – Edmund
    Nov 12 '17 at 1:45
  • $\begingroup$ If these functions are related (I assume they must be if there's an "arbitrary number" of them), you could try something like ft = Table[With[{k = k}, k - #^k &], {k, 3}]. It's hard to know what would be best without some idea of how you're going to use them. $\endgroup$ Nov 12 '17 at 11:28

The example you have provided does not align well with the language of the question.

If you would like to have a vector of functions, you can simply store all the function definitions in a list and define an application function, like so:


fnList1 = {
    # + 1 &,
    2 * # + 3 &

applyFnList = With[{fnl = #1, a = #2}, Map[#[a] &, fnl]] &;

applyFnList[fnList1, 3]

(* Output = {4, 9} *)

Now you can append (or prepend) an element to the list of functions:

fnList2 = Append[fnList1, 3 * # - 4 &];

and still invoke the new list with applyFnList:

applyFnList[fnList2, 3]

(* Output = {4, 9, 5} *)

If, on the other hand, you meant something else, please clarify your question.


Modify DownValues[X]:

X[{x_}] = {};

DownValues[X] = Replace[DownValues[X],
      (Verbatim[HoldPattern[X[{x_}]]] :> {a___}) ->
       Verbatim[HoldPattern[X[{x_}]]] :> {a, 3 + x}, {1}] /. Verbatim -> Identity



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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