MATLAB: Simplify outputs huge result for diff symbolic expression with hyperbolic functions

diff()hyperbolicimagrealsimplifysymbolic

Matlab R2019 Update 3
syms x y k real;
syms f(x,y);
syms a b;
xd = -a*tanh(k*f)+b*sech(k*f);
yd = -b*tanh(k*f)-a*sech(k*f);
chid = atan2(yd, xd);
d_chid_dx = diff(chid, x);
simplify(d_chid_dx, 'Steps', 100, 'Criterion', 'preferReal')
produces result
ans(x, y) =
(((real(b*k*diff(f(x, y), x)*(tanh(k*f(x, y))^2 - 1)) - imag((b*k*sinh(k*f(x, y))*diff(f(x, y), x))/cosh(k*f(x, y))^2) + real((a*k*sinh(k*f(x, y))*diff(f(x, y), x))/cosh(k*f(x, y))^2) + imag(a*k*diff(f(x, y), x)*(tanh(k*f(x, y))^2 - 1)))/(imag(b*tanh(k*f(x, y))) - real(a*tanh(k*f(x, y))) + imag(a/cosh(k*f(x, y))) + real(b/cosh(k*f(x, y)))) - ((imag((a*k*sinh(k*f(x, y))*diff(f(x, y), x))/cosh(k*f(x, y))^2) - real(a*k*diff(f(x, y), x)*(tanh(k*f(x, y))^2 - 1)) + real((b*k*sinh(k*f(x, y))*diff(f(x, y), x))/cosh(k*f(x, y))^2) + imag(b*k*diff(f(x, y), x)*(tanh(k*f(x, y))^2 - 1)))*(imag(a*tanh(k*f(x, y))) + real(b*tanh(k*f(x, y))) - imag(b/cosh(k*f(x, y))) + real(a/cosh(k*f(x, y)))))/(imag(b*tanh(k*f(x, y))) - real(a*tanh(k*f(x, y))) + imag(a/cosh(k*f(x, y))) + real(b/cosh(k*f(x, y))))^2)*(imag(b*tanh(k*f(x, y))) - real(a*tanh(k*f(x, y))) + imag(a/cosh(k*f(x, y))) + real(b/cosh(k*f(x, y))))^2)/((imag(a*tanh(k*f(x, y))) + real(b*tanh(k*f(x, y))) - imag(b/cosh(k*f(x, y))) + real(a/cosh(k*f(x, y))))^2 + (imag(b*tanh(k*f(x, y))) - real(a*tanh(k*f(x, y))) + imag(a/cosh(k*f(x, y))) + real(b/cosh(k*f(x, y))))^2)
while calculation by hand gives
-a*k*sech(k*f(x,y))
which is correct.
I tried options for simplification (rewrite, steps, criterion) but with no luck.
Any answer will be greatly appreciated.

Best Answer

Are you sure about your hand-calculated answer? Let's substitute one simple f(x, y) function into both the answer from Symbolic Math Toolbox and your hand-calculated answer and compare the results. I've run the code you wrote above before running any of these commands.
answer2 = -a*k*sech(k*f(x, y));
subs(yd, f, 0) % yd with f(x, y) = 0
subs(xd, f, 0) % ditto for xd
The values of xd and yd with this substitution are constants. Therefore so is chid, it has no dependency on x or y. The derivative of a constant should be 0.
subs(d_chid_dx, f, 0) % It is 0
What happens when we substitute f(x, y) = 0 into your answer?
subs(answer2, f, 0) % -a*k
As other checks, substituing f(x, y) = x into both d_chid_dx and answer2 gives answers that differ by a factor of a.
>> subs(answer2, f(x, y), x)
ans =
-(a*k)/cosh(k*x)
>> simplify(subs(d_chid_dx, f(x, y), x))
ans(x, y) =
-k/cosh(k*x)
Substituting f(x, y) = y also gives different answers.
>> subs(answer2, f(x, y), y)
ans =
-(a*k)/cosh(k*y)
>> simplify(subs(d_chid_dx, f(x, y), y))
ans(x, y) =
0
For this last check, you're taking the derivative with respect to x of a function that doesn't include x at all so it seems reasonable that the result ought to be 0.