3
$\begingroup$

Suppose I want to define a function $f(x)=mx+b$. And suppose I might want to change $m$ or $b$ later.

Specifically, suppose I initially want $m=-2,b=10$, but maybe will change these values later

Two ways I can think of to do this are

slope=-2;
intercept=10;
f[x_]:= intercept+slope*x

or, I can define it as

f[intercept_,slope_,x_]:=intercept+slope*x
f[10,-2,x]

Does anyone have suggestions vs when to use one approach vs the other?

I usually do a hybrid kind of thing, when I use the latter way, but then define something like slopeCase1=-2; interceptCase1=10; and then call f[interceptCase1,slopeCase1,x], but this looks ugly is probably problematic in more ways than one.

The former way seems nicer to me, but I always worry that when I later go and change slope (say slope=-3), some definition somewhere will not be changed because of some technicality.

  • (If I am only calling f[x_] once this is not really a worry, but if I use f in another function, which is used in another, etc, theres a lot of places where a mistake can happen
$\endgroup$
6
$\begingroup$

Consider defining the function family instead of the function:

f[b_, m_] := Function[{x}, m x + b];

Then:

fcase1 = f[10, -2];
fcase2 = f[10, -3];

{fcase1[x], fcase2[x]}
$\endgroup$
2
  • $\begingroup$ Would fcase1 and fcase2 be "Listable", or would I need to be explicit and use something like Function[Null, m*#+b,Listable]? $\endgroup$ – user106860 Nov 12 '20 at 22:42
  • 6
    $\begingroup$ @user106860 fcase1 and fcase2 are listable due to internal vectorization of Plus and Times and will be hundreds to thousands times more efficient than Function[..., Listable]. If you call fcase1 etc. on only a few thousand x, the difference in efficiency won't matter that much. $\endgroup$ – Michael E2 Nov 12 '20 at 23:36

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.