# Why aren't my variables evaluated in this function?

Consider this code :

Clear[Ptest]

Ptest[1, 1] = p + Theta;

Ptest[1, 2] = 2*p + Theta;

Ptest[1, 3] = 3*p + Theta;

Ptest[1, 4] = 4*p + Theta;

Clear[test]

test[x_, p_, Theta_] = Sum[Ptest[x, k], {k, 1, 4}];

test[1, 1, 2]

(*10 p + 4 Theta*)

test[1, p, Theta]

(*10 p + 4 Theta*)


I don't understand why the variables p and Theta are not replaced in the before the last line ? Indeed in the very last line we see that the function has the good values.

So : first question why when I give explicit numbers to p and Theta, nothing is computed ?

And after the why it does this, how to fix it properly (without making replacement rules).

I would like to avoid replacing Ptest by its exact expression as a function of p and Theta (because in my code it would be complicated for my own purpose). Thus I would like to keep something like

test[x_,p_,Theta_]=Sum[Ptest[x,k],{k,1,4}]


without writing explicit dependance inside of the function definition (because maybe there is some "magic" function to add around to make it work).

So second question : how to fix the code without having to write the explicit function of p and theta inside the definition of test ?

You can use Block to temporarily set the values for Theta and p globally:

Clear[Ptest]

Ptest[1, 1] = p + Theta;
Ptest[1, 2] = 2*p + Theta;
Ptest[1, 3] = 3*p + Theta;
Ptest[1, 4] = 4*p + Theta;

Clear[test]

test[x_, p2_, Theta2_] := Block[{Theta = Theta2, p = p2}, Sum[Ptest[x, k], {k, 1, 4}]];

test[1, 1, 2]
(* 18 *)

test[1, p, Theta]
(* 10 p + 4 Theta *)


Note that in order for it to work, you need to use SetDelayed (:=) for the definition of test, since Block disappears upon evaluation. The parameters also need different names.