How to count number of terms in a symbolic expression?

7 ビュー (過去 30 日間)
Mehdi
Mehdi 2023 年 12 月 2 日
コメント済み: Walter Roberson 2023 年 12 月 3 日
I have a long symbolic expression composed of many terms. How is it possible to count the total number of terms of my expression and then choose the ith term?
syms x y
z=x*y+cos(x*y)*x+x*sin(x)+sin(x)*cos(x)-x-y+2;
for example here the z is composed of 7 terms and the 3rd term is x*sin(x).

採用された回答

Walter Roberson
Walter Roberson 2023 年 12 月 3 日
編集済み: Walter Roberson 2023 年 12 月 3 日
syms x y
z=x*y+cos(x*y)*x+x*sin(x)+sin(x)*cos(x)-x-y+2;
terms = children(z)
terms = 1×7 cell array
{[-x]} {[-y]} {[cos(x)*sin(x)]} {[x*y]} {[x*cos(x*y)]} {[x*sin(x)]} {[2]}
nterms = length(terms)
nterms = 7
terms{3}
ans = 
children(z, 3)
ans = 
  2 件のコメント
Walter Roberson
Walter Roberson 2023 年 12 月 3 日
Notice the "third" term as far as MATLAB is concerned is not x*sin(x)
MATLAB re-arranges terms according to algebraic equivalences, into its own preferred order. The rules for ordering are not published, and can be contextual.
Walter Roberson
Walter Roberson 2023 年 12 月 3 日
Further example:
syms x
f = 6 + x - 3 - 2 - 1
as far as the symbolic toolbox is concerned this is the same as
f = x
The toolbox always folds rational and symbolic floating point numbers
5 + 2*sqrt(sym('3.2'))
will get completely executed to scalar
5 + 2*sqrt(sym(3.2))
will execute to an expression. sym(3.2) is converted to sym(32)/sym(10) and sqrt of a rational is not fully evaluated

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

その他の回答 (1 件)

VBBV
VBBV 2023 年 12 月 3 日
編集済み: VBBV 2023 年 12 月 3 日
syms x y
z='x*y+cos(x*y)*x+x*sin(x)+sin(x)*cos(x)-x-y+2'
z = 'x*y+cos(x*y)*x+x*sin(x)+sin(x)*cos(x)-x-y+2'
C = strsplit(z,{'+','-'})
C = 1×7 cell array
{'x*y'} {'cos(x*y)*x'} {'x*sin(x)'} {'sin(x)*cos(x)'} {'x'} {'y'} {'2'}
length(C)
ans = 7
C{3} % 3rd term
ans = 'x*sin(x)'
  4 件のコメント
Walter Roberson
Walter Roberson 2023 年 12 月 3 日
編集済み: Walter Roberson 2023 年 12 月 3 日
Consider
syms x y
z='x*y+cos(x-y)*x+x*sin(x)+sin(x)*cos(x)-x-y+2'
z = 'x*y+cos(x-y)*x+x*sin(x)+sin(x)*cos(x)-x-y+2'
C = strsplit(z,{'+','-'})
C = 1×8 cell array
{'x*y'} {'cos(x'} {'y)*x'} {'x*sin(x)'} {'sin(x)*cos(x)'} {'x'} {'y'} {'2'}
length(C)
ans = 8
C{3} % 3rd term
ans = 'y)*x'
The pattern matching has to be a lot more complicated to extract expressions. Indeed, it can be proven that it cannot be done using traditional regular expressions -- not unless you are willing to impose a maximum nesting depth (and use terribly messy expressions.) Some programming languages such as perl add regexp constructs that extend the pattern capabilities to make it possible; if MATLAB has those facilities I am overlooking them.
VBBV
VBBV 2023 年 12 月 3 日

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

カテゴリ

Help Center および File ExchangeNumber Theory についてさらに検索

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by