Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
@PinguinDirk Yes that fixed it, thank you! –  Tyilo May 3 '13 at 9:46
    
(I commented to repleace plotShow[f_,max_]:=Module[{},...] by plotShow[f_,max_]:=Block[{a},...] - this is ok only as long as a is empty) –  Pinguin Dirk May 3 '13 at 9:48

1 Answer 1

up vote 4 down vote accepted

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)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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