Nasser
Nasser

Reputation: 13173

How to extract all terms in x^n from an expression

Given any arbitrary expression, I wanted to extract list of all occurrences of x^m that show up anywhere in the expression.

For example, expr:=x^7+1/sqrt(x)+sin(y+x^19)+20-3*x^8/sin(x^20)+x+xz;

Mathematica graphics

Then the output should be

{x^7,x^(-1/2),x^19,x^8,x^20,x}

or I will be happy with just the powers on x, as I can add x later:

{7,-(1/2),19,8,20,1}

main tool is use is patmatch over operands of the expression, but this does not work for all cases.

restart;
expr:=x^7+1/sqrt(x)+sin(y+x^19)+20-3*x^8/sin(x^20)+x+xz;
T:=op(expr);
for current_item in T do
    n:='n';
    if patmatch(current_item,x^(n::anything),'la') then
       print(la);
    fi;
od:

                        [n = 7]
                        [n = -1/2]
                        [n = 1]

So it missed few. And since I do not know where these x will show, it is really hard to write a pattern match for every possible case where is can show up.

Is there a easier way to do this in Maple?

One thing I could do if all is lost, is convert it to a string, and use string matching, as this seems easier actually, but this seems like cheating when using computer algebra system.

expr_as_string:=convert(expr,string);

#expr_as_string := "x^7+1/(x^(1/2)+5)+sin(x^19+y)+20-3*x^8/sin(x^20)+x+xz"

res1:='res1';
StringTools:-RegMatch("(x\\^.)", expr_as_string,res1);
res1;

       "x^7"

I am not good at regexpr, so need to learn how to make it match all x^n in the string if to use the above method. Is there better way to do this string matching in Maple other than using RegMatch?

Upvotes: 2

Views: 200

Answers (1)

maplemathmatt
maplemathmatt

Reputation: 176

I suggest using the indets() command instead:

expr := x^7 + 1 / sqrt(x) + sin( x^19 + y ) + 20 - 3 * x^8 / sin( x^20 ) + x + x * z;
P := indets['flat']( expr, 'Or'(`^`('identical'(x),algebraic),'identical'(x)) );

Upvotes: 4

Related Questions