3
$\begingroup$

I have a list of parameters that will be used in different functions. I don't want to give them a global value so I thought on creating a list of parameters that I can call locally.

As an example, I would like to not have to type the {a = 1, b = 0.5, c = 0.75} part of the Block each time, just call my list of parameters:

f[x_, a_, b_, c_] := a*x + b + b*c;
g[y_, a_, b_, c_] := b*y + c + a*c;
h[z_, a_, b_, c_] := c*z + a + b*c;
Block[{a = 1, b = 0.5, c = 0.75}, Solve[f[x, a, b, c] == 0, x]]
Block[{a = 1, b = 0.5, c = 0.75}, Solve[g[y, a, b, c] == 0, y]]
Block[{a = 1, b = 0.5, c = 0.75}, Solve[h[z, a, b, c] == 0, z]]

Any ideas?

$\endgroup$
15
  • 1
    $\begingroup$ Don't, just put values in f[x, a, b, c] -> f[x,1,.5,.75]? $\endgroup$ – Kuba Sep 13 '17 at 16:06
  • 2
    $\begingroup$ Something like f[x_, a_:1, b_:0.5, c_:0.75] := (* stuff *) then? $\endgroup$ – J. M.'s ennui Sep 13 '17 at 16:10
  • 1
    $\begingroup$ f[x_, a_, b_, c_] := a*x + b + b*c; list = {1, .5, .75}; Solve[f[x, ##] == 0, x] & @@ list $\endgroup$ – Kuba Sep 13 '17 at 18:55
  • 1
    $\begingroup$ in this case the following may be useful: pars= Sequence[1,.5,.75] then you could just use: Solve[f[x,pars]==0,x] $\endgroup$ – mmeent Sep 13 '17 at 19:53
  • 1
    $\begingroup$ also possible: list={a->1,b->0.5,c->0.75};f[x,a,b,c]/.list $\endgroup$ – sebhofer Sep 14 '17 at 7:52
5
$\begingroup$

Since no one seems to dare an answer, let me give you one. At some point, you have to insert the values you want, but there are several shortcuts to make life easier especially if you want to insert the same at several occasions.

If you have like in your case a block of expressions, then one easy solution is to use With (which inserts values rather than creating local variables, but Block would work too) and surround all expressions where you want your paramters replaced:

f[x_, a_, b_, c_] := a*x + b + b*c;
g[y_, a_, b_, c_] := b*y + c + a*c;
h[z_, a_, b_, c_] := c*z + a + b*c;

With[{a = 1, b = 0.5, c = 0.75},
 {Solve[f[x, a, b, c] == 0, x],
  Solve[g[y, a, b, c] == 0, y],
  Solve[h[z, a, b, c] == 0, z]
  }
 ]
$\endgroup$
1
  • $\begingroup$ Ah, of course. That is exactly what I needed. Thank you very very much, @halirutan! $\endgroup$ – Laura K Sep 15 '17 at 17:25

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.