mcpField
M
matlab-symbolic-math

matlab-symbolic-math

github.com/matlab開発19267 回インストール2 週間前に更新
リポジトリ

matlab-symbolic-math について

Symbolic Math Toolbox を使った MATLAB コードの作成ガイドとパターンを提供するスキルです。記号代数、微積分、方程式の求解や関連するモデリングを行う 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® コードを生成するためのガイドライン、正しい構文、一般的なパターンを紹介します。

このスキルを使用する場面

  • シンボリック変数、式、関数を作成または操作する
  • シンボリック微分、積分、極限、総和を計算する
  • シンボリック式を簡約、因数分解、展開、整理する
  • ラプラス変換、フーリエ変換、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 — 新しいシンボリック変数を作成し、以前の仮定をすべてクリアします。対話型スクリプトやライブスクリプトで使用します。
  • x = sym('x') — シンボリック変数を参照します。既存の仮定を引き継ぎます。syms はワークスペース変数を動的に作成するため、MATLAB 関数内(スクリプトではなく)で必要です。
  • 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') を使う

各リファレンスファイルにある、アプリケーション固有の間違いも参照してください。

シンボリックコードを生成する前のチェックリスト

  • スクリプトで変数を作成する際、文字列ベースの sym('...') ではなく syms を使っている
  • 方程式には = ではなく == を使っている
  • 導関数には D 記法ではなく diff(y, t, n) を使っている
  • diff、int、laplace で独立変数を明示している
  • subs(...) の出力を変数に代入している
  • 式にすでにシンボリック変数が含まれている場合、数値リテラルを sym() で囲んでいない
  • assume/assumeAlso で仮定を設定し、syms または assume(x,'clear') でクリアしている

トラブルシューティング

問題:solve が空の結果、または予期しない結果を返す

  • 確認:定義域を制限する仮定が設定されていませんか?assumptions を使って確認してください。
  • 試す:solve(eqn, x, 'ReturnConditions', true) を使い、解の条件を確認してください。
  • 試す:閉じた形の解が存在しない場合は、数値解を求めるために vpasolve を使ってください。

問題:古い仮定が原因で誤った結果になる

  • 修正:スクリプトの先頭に syms <varname> を追加して、仮定をクリアしてください。
  • 最終手段:reset(symengine) ですべてをクリアします。

各リファレンスファイルにある、アプリケーション固有のトラブルシューティングも参照してください。

コメント