# Why the replacement rule works okay for scalars but not okay for matrices?

Consider the following UpSetDelayed:

D[Kstar0[x_, a_], x[b_]] ^:= dKstar0[x, a, b]


It works fine if applied to a scalar function:

D[Kstar0[x, a], x[b]]


dKstar0[x, a,b]

But if acting on the vector/matrix, it returns zero:

D[{Kstar0[x, a]}, x[b]]


{0}

Could you please tell me how to fix this problem?

Generically, is there any alternative to

D[Kstar0[x_, a_], x[b_]] ^:= dKstar0[x, a, b]


Make use of the NonConstants option to D:

Kstar0 /: D[Kstar0[x_, a_], x[b_], OptionsPattern[]] := If[
MemberQ[OptionValue[NonConstants], Kstar0],
dKstar0[x, a, b],
0
]


Then either:

D[{Kstar0[x, a]}, x[b], NonConstants->{Kstar0}]


{dKstar0[x, a, b]}

or:

SetOptions[D, NonConstants->{Kstar0}];
D[{Kstar0[x, a]}, x[b]]


{dKstar0[x, a, b]}

does what you want.

• Thanks! May I please ask you to look at this question and my attempt to answer it: mathematica.stackexchange.com/questions/288736/… ? In particular, I would like to define the rules with NonConstants automatically by having the list of function names instead of writing them manually many times (say, using the Do routine), but I cannot handle this. Commented Aug 13, 2023 at 12:34

Look at:

D[{Kstar0[x, a]}, x[b]] // Trace


You see that "{Kstar0[x, a]}" is not replaced because it does not fit your pattern. This then leaves: the derivative of "{Kstar0[x, a]}" relative to x[b]. However the former does not depend on the latter, therefore, the result is 0.

To fix this, you would have to specify a pattern that matches your input. However, you can not assign it to Kstar0, because Kstar0 is too deep nested in your definition. You would need to assign it to some other symbol.