I have a symbolic expressions as below
y1 = (1/a)-(b/a^2)+x*a*b-x/b
y2 = a*b+a*x+b*sqrt(x)
now I need to get the partial expressions which
listOfTerms = op(expression); # y1 or y2
numberOfSubExpressions=nops(expression); # for y1 or y2
requiredTerm = 0;
for i 1 to numberOfSubExpressions do
if has(listOfTerms [i], x) then # x is our required term
requiredTerm := requiredTerm +listOfTerms [i]
end if
end do
Above code does my requirement. But, if are there any bugs for special expressions please let me know. Because op function behaves differently when we have functions like(sin,cos Log ..etc)
restart;
y1 := (1/a)-(b/a^2)+x*a*b-x/b:
y2 := a*b+a*x+b*sqrt(x):
K := (ee,x) -> `if`(ee::`+`,select(depends,ee,x),ee):
K( y1, x );
x
x a b - -
b
K( y2, x );
(1/2)
a x + b x
#
# Leave alone an expression which is not a sum of terms.
#
K( sin(x+4)*x^3, x );
3
sin(x + 4) x
#
# Don't select subterms in which `x` is a just dummy name.
#
K( x^3 + sin(x) + Int(sqrt(x), x=a..b), x );
3
x + sin(x)
[edited]
y1 := (1/a)-(b/a^2)+x*a*b-x/b;
1 b x
y1 := - - -- + x a b - -
a 2 b
a
op(3,y1);
x a b
depends(op(3,y1), x);
true
The select
command maps its first argument over
all the operands of its second argument.
select( s->depends(s,x), y1 );
x
x a b - -
b
A more terse syntax, where select
maps its first
argument depends
over the operands of its second
argument, and passes its third argument as additional
options (to the selector).
select( depends, y1, x );
x
x a b - -
b
Now create a procedure to do it. Use a conditional test, so that it returns the first argument itself whenever that is not a sum of terms.
K1 := proc(ee, x)
if type(ee,`+`) then
select( depends, ee, x );
else
# leave it alone
ee;
end if;
end proc:
K1( y1, x);
x
x a b - -
b
Using a more terse syntax for that type-check.
K2 := proc(ee, x)
if ee::`+` then
select( depends, ee, x );
else
# leave it alone
ee;
end if;
end proc:
K2( y1, x);
x
x a b - -
b
Using a more terse syntax for that if..then..end if.
This is the so-called operator form of if
. The word
if
is within name-quotes, to distinguish it from the
language keyword within an if...then...end if .
K3 := proc(ee, x)
`if`( ee::`+` , select( depends, ee, x ), x );
end proc:
K3( y1, x);
x
x a b - -
b
Since the body of the procedure K3 has only a single statement then we can make it more terse, using the so-called operator form.
K4 := (ee, x) -> `if`( ee::`+` , select( depends, ee, x ), x ):
K4( y1, x);
x
x a b - -
b