# Block works when directly used but not when used in a function

I want to calculate a derivative such as: $\delta f=\sum_{i=A,B} \sum_{k=1,2,3} \frac{\partial f}{\partial a_k^i}$. Since $a_k^i$ are assigned values other places in the code, I have used Block. I obtain correct results for $\delta f$ directly calculating a function. However, when I define a function deltaf which is suppose to do the same thing I don't get the correct results.

Here are the values of a[i,k]

a[A, 1] = 1; a[A, 2] = 2; a[A, 3] = 3;
a[B, 1] = 5; a[B, 2] = 10; a[B, 3] = 15;


As a sample function for which I want the derivative of, I use f1[i,x]

f1[i_, x_] := (1 - x)*Sum[a[i, k]^2, {k, 1, 3}]


Using Block works for getting the derivative of f1[A,x] with respect to a[i,k] (I emphasize that I'm calculating f1[A,x] and not f1[i,x]):

Block[{a},Sum[D[f1[A, x], a[i, k]], {i, {A, B}}, {k, {1, 2, 3}}]]

12 (1 - x)


However if I define a function that does the same thing:

deltaf[f_] := Block[{a}, Sum[D[f, a[i, k]], {i, {A, B}}, {k, {1, 2, 3}}]]


It doesn't give the correct value anymore:

deltaf[f1[A, x]]

0


Why is this happening? How is it that when I calculate the same thing directly I get a correct answer but not when defined as a function?

• Hi ! As this is a Q&A site you should also explicitly state what are you trying to do - e.g ask a question, not just leave it blank. – Sektor Apr 21 '15 at 11:36
• Sorry, this is my first question. My question is exactly why this is happening. In other words the same thing as mentioned in the title: "Why does Block not work when used as a function? But it works when directly used? " – nein Apr 21 '15 at 11:39
• Did you try deltaf[Evaluate[f1[A, x]]]? – Sosi Apr 21 '15 at 11:47
• Yes I did but it still didn't work! @Sosi – nein Apr 21 '15 at 11:49
• Actually, I think you want the exact opposite of what I was suggesting. Notice that when you do deltaf[f1[A,x]] you are evaluating D[f, a[i, k]] (=14 (1 - x)) AND THEN using this result to compute the Sum. This is why the derivative then gives 0, because you are evaluating the derivatives of 14(1-x) with respect to a[i,k]. – Sosi Apr 21 '15 at 13:29

The problem is that deltaf[f1[A,x]] evaluates f1[A,x] (=14 (1 - x)) before actually computing Sum[D[f, a[i, k]], {i, {A, B}}, {k, {1, 2, 3}}]. Specifying that the attributes of deltaf are to remain unevaluated solves the problem:
SetAttributes[deltaf, HoldAll];

12 (1 - x)