0
$\begingroup$

Let's say I have the following set of parameters:

param=
{a->1,b->2,c->3}

and the following function that uses the parameters:

func = a+b*x+c*x^2

I can apply the parameters to the function by the following assignment:

func /.param

1+2*x+3*x^2

Now I would like to change only the param c for some specific param, let's say:

c -> {10,22,23,1}

How can I create a new set of param, which should look like that in the end:

param = {
{a->1,b->2,c->10},
{a->1,b->2,c->22},
{a->1,b->2,c->23},
{a->1,b->2,c->1}
}

such that I can sweep through the parameters of c without having to retype every time the parameters from a and b ?

What I tried:

param ={
a->#[[1]],b->#[[2]],c->#[[3]]} &/@ {Table[1,{i,1,4}],Table[1,{i,1,4}],{10,22,23,1}}

but this did not work out + it is not very nice, as the variable i has to be adjusted manually to the number of different c values there exist.

$\endgroup$
5
  • $\begingroup$ It might be more expedient to do the following instead: func[a_, b_, c_][x_] := a + b x + c x^2; Table[func[1, 2, c][x], {c, {10, 22, 23, 1}}] $\endgroup$ Mar 30, 2018 at 11:21
  • $\begingroup$ Yes, I agree. However, this is only a toy example. My program is much longer and the parameters are evaluated at different instances. $\endgroup$
    – james
    Mar 30, 2018 at 11:34
  • 1
    $\begingroup$ I suggest that you go easy with rules and replacements. Try pure function. $\endgroup$ Mar 30, 2018 at 11:43
  • $\begingroup$ Btw.: func is not a function; it is an expression. $\endgroup$ Mar 30, 2018 at 12:18
  • $\begingroup$ As for adjusting Table, you can do Table[...,{i, Length[cvalues]}], if you have your c values in a list cvalues. $\endgroup$
    – Michael E2
    Mar 30, 2018 at 13:45

1 Answer 1

1
$\begingroup$

There's this way:

param = Thread[{a -> 1, b -> 2, Thread[c -> {10, 22, 23, 1}]}]
(*
  {{a -> 1, b -> 2, c -> 10}, {a -> 1, b -> 2, c -> 22},
   {a -> 1, b -> 2, c -> 23}, {a -> 1, b -> 2, c -> 1}}
*)

Maybe also this?:

func = a + b*x + c*x^2
(*  a + b x + c x^2  *)

csub = List /@ Thread[c -> {10, 22, 23, 1}]
(*  {{c -> 10}, {c -> 22}, {c -> 23}, {c -> 1}}  *)

func /. csub /. {a -> 1, b -> 2}
(*  {1 + 2 x + 10 x^2, 1 + 2 x + 22 x^2, 1 + 2 x + 23 x^2, 1 + 2 x + x^2}  *)

If your func is Listable, you can do this:

func /. c -> {10, 22, 23, 1} /. {a -> 1, b -> 2}
(*  {1 + 2 x + 10 x^2, 1 + 2 x + 22 x^2, 1 + 2 x + 23 x^2, 1 + 2 x + x^2}  *)
$\endgroup$

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.