0
$\begingroup$

This code works fine only if a is not defined in the outside context:

getA[f_,total_]:=Module[{},
    result=Solve[\!\(
     \*SubsuperscriptBox[\(\[Integral]\), \(0\), \(255\)]\(f \[DifferentialD]i\)\)==total,a];
     If[Length[result] == 0,Return[False]];
     a/.First@result//N
];
plotShow[f_,max_]:=Module[{},
    a=getA[f,max];
    If[!a,Return[]];
    Print[f];
    Plot[f,{i,0,255}]
];

plotShow[i * a, 3500] (* => 0.107651 i      & a plot*)
(* Now showPlot has polluted the outside context with a = 0.107651 *)
plotShow[i * a, 3500] (* => Solve::ivar: "0.107651 is not a valid variable." *)

How can I make the function plotShow stop polluting the outside context?

$\endgroup$
2
  • $\begingroup$ @PinguinDirk Yes that fixed it, thank you! $\endgroup$
    – Tyilo
    Commented May 3, 2013 at 9:46
  • $\begingroup$ (I commented to repleace plotShow[f_,max_]:=Module[{},...] by plotShow[f_,max_]:=Block[{a},...] - this is ok only as long as a is empty) $\endgroup$ Commented May 3, 2013 at 9:48

1 Answer 1

4
$\begingroup$

As in my comment above, here's a way that works even if a and/or i have global values:

getA[f_, total_] := Module[{result},
    result = Solve[Integrate[f[a, i], {i, 0, 255}] == total, a];
    If[Length[result] == 0, Return[False]];
    a /. First@result // N
];

plotShow[f_, max_] := Block[{a, i},
    a = getA[f, max];
    If[! a, Return[]];
    Print[f[a, i]];
    Plot[f[a, i], {i, 0, 255}]
];

f[a_, i_] := i a
plotShow[f, 3500] 

I tried not to modify most of your code, just the Block is new and so is the declaration of f. I hope this helps (note that there are many threads here discussing Module vs. Block)

$\endgroup$

Your Answer

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

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