Substitute symbolic sub-expression in expression

2 ビュー (過去 30 日間)
Martin Androvich
Martin Androvich 2020 年 6 月 3 日
コメント済み: Valeri Aronov 2021 年 6 月 27 日
I have an equation
eq = Tnext - 2*Tn + Tprev == - sigma*Tinf^4*h^2 - alpha*Tinf*h^2 + sigma*Tn^4*h^2 + alpha*Tn*h^2
in which I want to replace the sub-expression
sigma*Tinf^4*h^2 - alpha*Tinf*h^2
with
C = sigma*Tinf^4*h^2 - alpha*Tinf*h^2
such that it becomes
eq = Tnext - 2*Tn + Tprev == - C + sigma*Tn^4*h^2 + alpha*Tn*h^2
I have tried the following:
eq_to_sub = sigma*Tinf^4*h^2 - alpha*Tinf*h^2;
syms C
eq = subs(eq, eq_to_sub, C)
subsx = @(u,w0,w0str) feval(symengine,'subsex',u,[char(w0) '=' w0str]);
eq = subsx(eq, eq_to_sub, 'C')
which doesnt change the equation at all. Weirdly, both methods work if the sub-expression (to substitute) is limited to
eq_to_sub = sigma*Tinf^4;
resulting in
Tnext - 2*Tn + Tprev == Tn*h^2*alpha - C*h^2 + Tn^4*h^2*sigma + (-h^2)*Tinf*alpha
  1 件のコメント
Valeri Aronov
Valeri Aronov 2021 年 6 月 27 日
Note that the monomials in C have different signs, but the same monomials in eq have the same sign. C is not found in eq because of it.

サインインしてコメントする。

採用された回答

Jyotsna Talluri
Jyotsna Talluri 2020 年 6 月 8 日
Enclose the subexpresssion in braces as it contains more than one term.
eq = Tnext - 2*Tn + Tprev == - (sigma*Tinf^4*h^2 + alpha*Tinf*h^2) + sigma*Tn^4*h^2 + alpha*Tn*h^2;
C = sigma*Tinf^4*h^2 + alpha*Tinf*h^2;
q = feval(symengine,'subsex',eq,[char(C) '=C']);
  2 件のコメント
Martin Androvich
Martin Androvich 2020 年 6 月 8 日
That's tricky, haha! But it works, so thanks a bunch 😊
Martin Androvich
Martin Androvich 2020 年 6 月 8 日
編集済み: Martin Androvich 2020 年 6 月 8 日
But what if the expression is generated from some other function, e.g. simplify(), where I cannot simply manually enclose it in braces?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by