How to count number of terms in a symbolic expression?
조회 수: 9 (최근 30일)
이전 댓글 표시
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).
댓글 수: 0
채택된 답변
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)
nterms = length(terms)
terms{3}
children(z, 3)
댓글 수: 2
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
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
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'
C = strsplit(z,{'+','-'})
length(C)
C{3} % 3rd term
댓글 수: 4
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'
C = strsplit(z,{'+','-'})
length(C)
C{3} % 3rd term
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.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!