Matlab中隐式符号表达式求梯度报错问题求助
Ah, I see the issue here—you're hitting a common gotcha with MATLAB's Symbolic Math Toolbox. The error happens because you're passing a symbolic equality (created with ==) to the gradient function, which expects an arithmetic symbolic expression (a scalar function, not a logical statement).
When you define Sa = sym('Ra^2==(Z-P(3))^2+(Y-P(2))^2'), you're creating a symbolic object that represents a logical equation, not a numerical function. The gradient operation only works on scalar-valued arithmetic expressions, which is why symengine throws that "Type::Arithmetical" error.
Solution 1: Rearrange the Equation into a Scalar Function
Fix this by moving all terms to one side of the equality to create a valid arithmetic expression. This gives gradient the input type it needs:
syms Y Z Ra = 51.7; P = [0 0 200]; % Rearrange the equation into a single arithmetic expression Sa = Ra^2 - (Z - P(3))^2 - (Y - P(2))^2; % Compute the gradient with respect to Y and Z G = gradient(Sa, [Y Z])
Solution 2: Use a Symbolic Function Definition
As you noticed, defining Sa directly as a symbolic function (using the Sa(Y,Z) syntax) works perfectly. This syntax automatically creates an arithmetic expression instead of a logical equality:
syms Y Z Ra = 51.7; P = [0 0 200]; % Define Sa as a symbolic function of Y and Z Sa(Y,Z) = Ra^2 - (Z - P(3))^2 - (Y - P(2))^2; % Calculate the gradient G = gradient(Sa, [Y Z])
Why This Works
The gradient function relies on the underlying symbolic engine (symengine) to compute partial derivatives, which only supports arithmetic inputs. By converting your equality into a scalar function—either by rearranging terms or using the symbolic function syntax—you provide a valid input that the engine can process.
内容的提问来源于stack exchange,提问作者tron_ccp

