How to count number of terms in a symbolic expression?
Show older comments
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).
Accepted Answer
More Answers (1)
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 Comments
VBBV
on 3 Dec 2023
yes, the order of precedence for the operators is what Matlab considers in the symbolic expression. @Walter Roberson is correct.
Walter Roberson
on 3 Dec 2023
Edited: Walter Roberson
on 3 Dec 2023
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.
VBBV
on 3 Dec 2023
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!