1
$\begingroup$

I am trying to generate a list of functions from a vector of expressions. I have the list

$H=[1,x,x^2+1,3x^3+2x,4x^2+2x]$ and I want to define a function $f$ using two inputs such that $f(n,x)$ returns the evaluation of the $n$th entry of $H$. For example, I want $f(3,y)=y^2+1$.

I tried this:

test[n_,y_]:=Module[
{func},
func[x_]:=Evaluate[Part[H,n]];
func[y]
].

However, it always return an expression of $x$ instead of the function output. Can anyone please help me?

$\endgroup$

2 Answers 2

2
$\begingroup$

How about

ClearAll[x, f]
h = {1, x, x^2 + 1, 3*x^3 + 2*x, 4*x^2 + 2*x}
f[(n_Integer)?Positive,var_Symbol]:=(h[[n]]/.x->var)

And now

Mathematica graphics

I am sure there are other ways to do this.

$\endgroup$
2
  • $\begingroup$ Why are you restricting var to be a symbol? $\endgroup$
    – Roman
    May 13, 2021 at 15:29
  • $\begingroup$ @Roman well, from the spirit of the intended use, the var parameter is expected to be a symbol. But ofcourse one can change or remove this if that is not what they wanted. $\endgroup$
    – Nasser
    May 13, 2021 at 17:54
0
$\begingroup$
H = {1, x, x^2 + 1, 3*x^3 + 2*x, 4*x^2 + 2*x};
MapIndexed[(f[#2[[1]], x_] = #1) &, H];

f[3, y]
(*    1 + y^2    *)

?f
(*    f[1, x_] = 1
      f[2, x_] = x
      f[3, x_] = 1 + x^2
      f[4, x_] = 2 x + 3 x^3
      f[5, x_] = 2 x + 4 x^2     *)
$\endgroup$
2
  • $\begingroup$ Thank you very much. I am a bit new to the language so can you plese explain to me the meaning of the second line of your code? What does the & do and what are #2 and #1? $\endgroup$
    – abka
    May 13, 2021 at 15:43
  • $\begingroup$ Slots refer to the arguments of a pure function. In this case, the pure function (f[#2[[1]], x_] = #1) & sets the value of the function f with given arguments, which afterwards we can check with ?f as shown. $\endgroup$
    – Roman
    May 13, 2021 at 16:49

Your Answer

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

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