# Problem with local variables when using Module twice in the same code

ClearAll["Global*"];
g1[K1_, K2_, K3_] :=
Module[{w, e}, Subscript[C, 1] = K1/2; Subscript[C, 2] = K2/2;
Subscript[C, 3] = K3/3; ω = K1 + K2 + K3;
w = (Subscript[C, 1]*Subscript[C, 2]*Subscript[C, 3])/ω;
e = ω*w ; Return[{w, e}]];
a = g1[10, 15, 20]
g2[K1_, K2_, K3_] :=
Module[{w, e}, e1 = (Subscript[C, 1]*K1*K2)/2;
e2 = (K2*K3*Subscript[C, 2])/2;
e3 = (Subscript[C, 2]*K3*K2 + K1)/3;
f1 = D[e1, {Subscript[C, 1]}]; f2 = D[e2, {Subscript[C, 2]}];
f3 = D[e3, {Subscript[C, 3]}]; w = (e1 + e2 + e3);
e = 30*w ; Return[{w, e}]];
b = g2[10, 15, 20]


I have written two Module in the same program. The variable I am finding in the first Module is there in the second Module. I used clear[c1,c2,c3] I turned out not working. How to implement two module in the same program. The above is the simple replica of the error I am getting.

## Error

f1 = D[e1, {Subscript[C, 1]}]


and it is not related to the Module, but to the fact you have already defined a value for Subscript[C, 1] in this case 5, and you can not take the derivative with respect to 5.

## Solution

Module would play a role in the solution and not the problem if you had use it to make c1,c2,c3 local, like

ClearAll["Global*"];
g1[K1_, K2_, K3_] := Module[{w, e , c1, c2, c3},
c1 = K1/2;
c2 = K2/2;
c3 = K3/3;
ω = K1 + K2 + K3;
w = (c1*c2*c3)/om;
e = ω*w; Return[{w, e}]];
a = g1[10, 15, 20]
g2[K1_, K2_, K3_] := Module[
{w, e, c1, c2, c3},
e1 = (c1*K1*K2)/2;
e2 = (K2*K3*c2)/2;
e3 = (c3*K3*K2 + K1)/3;
f1 = D[e1, {c1}];
f2 = D[e2, {c2}];
f3 = D[e3, {c3}];
w = (e1 + e2 + e3)/om;
e = 30*w; Return[{w, e}]];
b = g2[10, 15, 20]


## Documentation

You should read the "Details" section in the documentation for Module. Because Module creates a symbol with name xxx$nnn to represent a local variable with name xxx, it doesn't matter if xxx is defined outside, all local evaluations will use a temporary variable xxx$nnn (notice the output).

## Side Note

You should avoid using Subscript while defining symbols (variables). Subscript[C, 1] is not a symbol, but a composite expression where Subscript is an operator without built-in meaning. You expect to do $C_1=5$ but you are actually doing Set[Subscript[C, 1], 5] which is to assign a DownValues to the operator Subscript and not an OwnValues to an indexed C as you may intend. Read how to properly define indexed variables here

• Actually, in my original code, I am actually finding the values of c1 c2 c3 using the first module. But in the second module, I have to do some operation which involves taking derivatives wrt c1 c2 c3. Since c1 c2 c3 are the local variables in the first module. I don't have to worry about taking derivatives wrt c1 c2 c3 in the second module. Is it right? – acoustics Aug 9 '18 at 10:30
• @vijay yes, see my edit. – rhermans Aug 9 '18 at 11:18
• Thanks for your suggestions. I implemented in my main code and it worked. – acoustics Aug 9 '18 at 17:55