0

enter image description here

I got a Ryacas expression like this, and I want to extract the coefficient of x^4,11. How should I write the code to get this, thanks.

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
Bean Lee
  • 33
  • 3

1 Answers1

0

Hope this helps:

x <- Sym("x")
P <- (x+1)*(x+2)*(x+3)
Expand(P)
# expression(x^3 + 6 * x^2 + 11 * x + 6)
# coefficient of x^2:
yacas("Coef((x+1)*(x+2)*(x+3), x, 2)")
# expression(6)
# or:
yacas(paste0("Coef(", P, ",x , 2)"))
# expression(6)

EDIT 2020-02

Updated for the new version of Ryacas:

library(Ryacas)
x <- ysym("x")
yac_assign((x+1)*(x+2)*(x+3), "P")
### expand the polynomial
yac_str("Expand(P)")
# [1] "x^3+6*x^2+11*x+6"
### extract coefficient of x^2:
yac_str("Coef(P, x, 2)")
# [1] "6"
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • Really appreciate your answer , although I already solved this problem by extract from character string,but I think your way is more simple and beautiful. – Bean Lee Mar 20 '19 at 15:15