Search code examples
ryacas

extract coefficient of x^k from Ryacas calculated expression


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.


Solution

  • 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"