Mathematically, the two expressions are identical:
row1∗(row2⊤+col) = row1∗row2⊤ + row1∗col
However, the symbolic engine might treat it differently. In the form
the engine sees a product of a 1×5 row vector (row1) and a 5×1 subexpression (row2⊤+col).
When you then say diff(..., row2) ,MATLAB tries to interpret “differentiate w.r.t. row2 (a 1×5 matrix variable),” but inside that product, it finds row2⊤ (5×1) plus another column vector. It does not automatically expand or reconcile the shapes. This sometimes leads the engine to get confused as it can’t see how row2 (1×5) is showing up in this subexpression (5×1), and it fails or returns an unevaluated derivative.
Expanding the product helps the engine sometimes:
Once you rewrite:
row1*(row2.’ + col) → row1*row2.’ + row1*col
now it’s two simpler terms:
In this form, MATLAB can more easily see how each term depends on the entries of row2 and can take partial derivatives with respect to them. That’s why
diff(row1*row2.’ + row1*col, row2)
succeeds.
By contrast, when you write
diff( expression, row2.' )
you are telling MATLAB to “differentiate w.r.t. the column vector” version of row2. That column vector has dimension (N×1). Symbolically, that’s more natural for the engine—it sees “N separate scalar entries in a column.”
After doing that differentiation, MATLAB’s result is typically an (N×1) column vector. If you want it back in a row shape, you then do another transpose:
diff(expression, row2.').'
which flips the result from (N×1) back to (1×N).
MATLAB likes to differentiate with respect to columns of scalar variables. A column vector is the simplest shape for partial derivatives in the engine’s logic.
If your variable is defined as a row vector, the symbolic engine may get confused and fail or yield unexpected results in some cases.
From the documentation(reference link below):
“When differentiating a scalar function f with respect to a vector or matrix mvar, diff uses the convention of returning an output size that is the transpose of the input size mvar.”
- This statement tells you that if mvar is 1×5, the result is supposed to be 5×1.
- In practice, if your expression references mvar in a transposed form (e.g., a 5×1 subexpression) but you still pass in the 1×5 version as the differentiation target, the engine may fail to unify those shapes. That’s exactly what happens with diff(row1*(row2.' + col), row2): the internal shapes mismatch, so it behaves unexpectedly.
Here is the link to the documenetation of "diff" :
Hope this helps!