Substitute symbolic sub-expression in expression

조회 수: 4 (최근 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 CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by