mcpField
M
matlab-symbolic-math

matlab-symbolic-math

github.com/matlab开发19267 次安装2 周前更新
代码仓库

关于 matlab-symbolic-math

此技能提供使用 MATLAB Symbolic Math Toolbox 编写 MATLAB 代码的指南和模式,面向进行符号代数、微积分、方程求解及相关建模的用户,并着重说明语法和常见错误的预防。

主要功能

  1. 01创建符号变量和表达式
  2. 02求解方程并执行微积分运算
  3. 03管理假设和变量替换
  4. 04执行符号矩阵运算
  5. 05生成函数和模型方程
  6. 06排查符号代码常见错误

适用场景

  1. 01推导方程的符号解
  2. 02对表达式求导或积分
  3. 03从微分方程构建传递函数
  4. 04将符号表达式转换为 MATLAB 函数

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/matlab/agent-skills-playground --skill matlab-symbolic-math

安装后在 Claude Code 中输入/matlab-symbolic-math确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
control-systems.md
matlabFunction-patterns.md
ode-solving.md
plotting-and-display.md
simplification-and-polynomials.md

详细介绍

MATLAB Symbolic Math Toolbox

此技能提供指南、正确语法和常见模式,帮助生成使用 Symbolic Math Toolbox 的 MATLAB® 代码。

何时使用此技能

  • 创建或操作符号变量、表达式和函数
  • 执行符号微分、积分、极限或求和
  • 化简、因式分解、展开或合并符号表达式
  • 计算 Laplace、Fourier 或 Z 变换及其逆变换
  • 根据微分方程推导传递函数或状态空间方程
  • 显示或绘制符号表达式
  • 使用可变精度运算(VPA)
  • 根据符号表达式生成 MATLAB 函数、Simulink 函数模块、Simscape 方程和 C 代码

关键规则

1. 切勿向符号函数传递字符串或字符向量

错误(已弃用——目前会发出警告,未来版本中将报错;solve 中的单个 = 现在就会报错):

solve('x^2 + 2*x - 3 = 0')
dsolve('Dy = -a*y')

正确:

syms x
solve(x^2 + 2*x - 3 == 0, x)

syms y(t) a
dsolve(diff(y,t) == -a*y)
2. 交互式工作使用 syms,函数和常量使用 sym
  • syms x y z — 创建新的符号变量并清除之前的所有假设。用于交互式脚本和 Live Script。
  • x = sym('x') — 引用符号变量。继承已有假设。在 MATLAB 函数(而非脚本)中必须使用,因为 syms 会动态创建工作区变量。
  • sym(pi) — 将数值转换为精确符号值。用于符号常量。
  • sym('pi') — 创建名为 pi 的符号变量,而非数学常数 π。这是一个常见的困惑来源。

错误:

% Inside a function:
function result = myFunc()
    syms x          % Error or unreliable in compiled/nested functions
    result = x^2;
end

% Creating symbolic constant pi:
p = sym('pi');      % Creates variable named "pi", NOT the constant

正确:

% Inside a function:
function result = myFunc()
    x = sym('x');   % Use sym inside functions
    result = x^2;
end

% Creating symbolic constant pi:
p = sym(pi);        % Converts numeric pi to exact symbolic π
3. 假设管理

即使执行 clear 后,假设仍会保留在符号引擎中。这是造成微妙错误的常见原因。

% Setting assumptions
syms x real                  % x is real (clears prior assumptions)
syms n positive integer      % n is a positive integer
assume(x > 0)                % x is positive (REPLACES all prior assumptions on x)
assumeAlso(x < 10)           % ADDS assumption: 0 < x < 10

% Checking assumptions
assumptions(x)               % Shows assumptions on x
assumptions                  % Shows ALL assumptions in workspace

% Clearing assumptions — THREE ways (know the differences):
syms x                       % Recreate with syms: clears assumptions
assume(x, 'clear')           % Explicitly clear assumptions on x
reset(symengine)             % Nuclear option: clears EVERYTHING

% DANGER: clear x does NOT clear assumptions!
clear x                      % Removes variable from workspace
x = sym('x');                % x INHERITS old assumptions from engine!

最佳实践: 在脚本开头使用 syms 创建变量,以清除过时的假设。在脚本中途需要重置特定变量时,使用 assume(x, 'clear')。

4. subs 不会原地修改

subs 函数会返回一个新表达式,不会修改原表达式。

错误:

syms x
f = x^2 + 3*x;
subs(f, x, 2);         % Result is discarded!
disp(f)                % Still x^2 + 3*x

正确:

syms x
f = x^2 + 3*x;
f_val = subs(f, x, 2);    % Assign the result
% or: f = subs(f, x, 2);  % Overwrite f
5. 不要在符号表达式中用 sym() 包装数值字面量

AI 工具经常会过度使用 sym() 包装每个数值字面量。 当算术表达式中的任一操作数为符号值时,MATLAB 会自动将该表达式中的所有数值字面量转换为符号值。用 sym() 包装字面量会造成冗余,还可能导致错误。 确实需要 sym() 的情况: 仅当创建独立的符号数值,且表达式中不存在符号变量时。

% No symbolic variable involved — sym() IS needed:
half = sym(1/2);                % Exact 1/2, not 0.5 double
half = sym(1)/2;                % Exact 1/2, declaring sym(1) promotes all numeric literals to symbolic
piExact = sym(pi);              % Exact π, not 3.14159...

% Symbolic variable already present — sym() is NOT needed:
syms x
f = x/2 + 1/3;                 % Automatically exact: x/2 + 1/3
g = exp(-x^2/2) / sqrt(2*pi);  % All literals promoted by x
6. 变量命名:符号到数值的转换

替换为数值或将符号表达式转换为数值形式时,请保留基本变量名,并添加后缀以指明转换类型:

  • Val — 在 subs() 或 double() 之后(数值)
  • Vpa — 在 vpa() 之后(可变精度运算)
syms m g L

% Substituting numeric values
mVal = double(subs(m, 5));         % or: mVal = 5;
gVal = 9.81;
LVal = 0.5;

% Evaluating a symbolic expression numerically
omega = sqrt(g/L);
omegaVal = double(subs(omega, [g L], [gVal LVal]));

% Variable-precision arithmetic
piVpa = vpa(sym(pi), 50);
omegaVpa = vpa(subs(omega, [g L], [gVal LVal]), 32);

理由: 这种约定可让工作区中的符号变量和数值变量在视觉上清晰区分,避免意外用数值覆盖符号表达式,并便于快速判断哪些变量是精确符号值、哪些是求值后的数值。

核心工作流模式

创建变量和表达式
% Multiple variables at once
syms a b c

% Variables with assumptions
syms a b c real
syms n positive integer
syms x
assume(x > 2)


% Symbolic matrices with auto-generated elements
syms A [3 3]                 % Creates A = [A1_1 A1_2 A1_3; ...]

% Symbolic vector
syms a [1 3]                 % Creates row vector a = [a1 a2 a3]

% Symbolic numbers (exact)
a = sym(1/3);           % Exact 1/3
piSym = sym(pi);        % Exact π
求解代数方程
syms x y

% Single equation
sol = solve(x^2 - 5*x + 6 == 0, x);   % Returns [2; 3]

% System of equations
[solx, soly] = solve(x + y == 10, x - y == 2, x, y);

% Return all solutions along with the parameters in the solution and the conditions on the solution
[sol, params, conds] = solve(sin(x) == 0, x, 'ReturnConditions', true);

% Numerical solutions when analytic not possible
solN = vpasolve(x^5 - 3*x^4 + x - 1 == 0, x);
微积分
syms x t n

% Differentiation
diff(sin(x), x)             % cos(x)
diff(x^3, x, 2)             % 6*x  (second derivative)

% Integration
int(x^2, x)                 % x^3/3  (indefinite)
int(x^2, x, 0, 1)           % 1/3    (definite, from 0 to 1)

% Limits
limit(sin(x)/x, x, 0)       % 1
limit(1/x, x, 0, 'right')   % Inf
limit(1/x, x, 0, 'left')    % -Inf

% Summation
symsum(1/n^2, n, 1, Inf)     % pi^2/6

% Taylor series
taylor(exp(x), x, 0, 'Order', 6)   % x^5/120 + x^4/24 + x^3/6 + x^2/2 + x + 1 
矩阵运算
syms a b c d
A = [a b; c d];

% Determinant
det(A)                   % a*d - b*c

% Inverse
inv(A)                   % Symbolic inverse

% Eigenvalues and eigenvectors
[V, D] = eig(A)

% Characteristic polynomial
charpoly = det(A - sym('lambda')*eye(2))

% Jacobian
syms x y
f = [x^2*y; 5*x + sin(y)];
J = jacobian(f, [x, y])    % [2*x*y, x^2; 5, cos(y)]

% Jacobian of a coordinate change
syms r(t) phi(t) theta(t);  % polar coordinates that are a function of time
R = [r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)] % coordinate transform from spherical to Cartesian
jacobian(R,[r,phi,theta])

应用模式

有关详细工作流,请参阅以下参考文件。用户的任务符合相关文件的内容时,请阅读该文件:

  • references/simplification-and-polynomials.md — simplify/expand/factor/collect/partfrac/rewrite、sym2poly 与 coeffs 的区别、可变精度算术(VPA)
  • references/control-systems.md — 从 ODE 推导传递函数、从基本原理推导 tf/ss、拉普拉斯变换/傅里叶变换/Z 变换、根据符号模型绘制波特图
  • references/ode-solving.md — dsolve 语法、odeToVectorField + matlabFunction + ode45 工作流、参数化 ODE 求解
  • references/plotting-and-display.md — fplot/fsurf/fmesh/fcontour/fimplicit/fanimator 系列、disp() 与 pretty() 的区别、为什么不应使用 linspace+subs+plot
  • references/matlabFunction-patterns.md — 将符号表达式转换为函数句柄/文件、'Vars'/'Optimize'/'File' 选项、分段函数处理、关键错误预防规则

常见错误及修正方法

错误修正方法
solve('x^2=1')syms x; solve(x^2 == 1, x)
dsolve('Dy = y')syms y(t); dsolve(diff(y,t) == y)
使用 subs(f,x,2),但未赋值f = subs(f,x,2)
使用 clear x 清除假设syms x 或 assume(x,'clear')
在函数中使用 syms在函数中使用 x = sym('x')

另请参阅:各参考文件中的特定应用错误。

生成符号代码前的检查清单

  • 在脚本中使用 syms(而非基于字符串的 sym('...'))创建变量
  • 使用 == 表示方程,而不是 =
  • 使用 diff(y, t, n) 表示导数,而不是 D 记号
  • 在 diff、int、laplace 中明确指定自变量
  • 将 subs(...) 的输出赋给变量
  • 当表达式中已有符号变量时,不要将数值字面量包装在 sym() 中
  • 使用 assume/assumeAlso 设置假设,使用 syms 或 assume(x,'clear') 清除假设

故障排查

问题:solve 返回空结果或意外结果

  • 检查:是否有假设限制了定义域?使用 assumptions 检查。
  • 尝试:使用 solve(eqn, x, 'ReturnConditions', true) 查看解的条件。
  • 尝试:不存在闭式解时,使用 vpasolve 求数值解。

问题:过期的假设导致结果错误

  • 修正:在脚本顶部添加 syms <varname> 以清除假设。
  • 终极方案:reset(symengine) 会清除所有内容。

另请参阅:各参考文件中的特定应用故障排查。

评论

支持 Markdown