wxyz
wxyz

Reputation: 35

How to get coefficients of polynomial expression

I used rSymPy and obtained following expression:

"1 - 0.7*B - 0.3*B**2"

Now I want to extract the coefficients of B and Coefficients of B^2, and stored in a matrix. I tried gsub function in R, any suggestions?

Upvotes: 0

Views: 727

Answers (2)

wxyz
wxyz

Reputation: 35

x <- "1 - 0.72*B - 0.3*B**2 + 0.4*B**3"
m <- gregexpr("(\\+|-)\\s+[0-9]+\\.[0-9]+",x)
out <-(unlist(regmatches(x,m) ))
out2<-as.numeric(gsub("\\s","",out))
out2

Upvotes: 1

Philip Parker
Philip Parker

Reputation: 639

Do you mean like:

> x <- "1 - 0.7*B - 0.3*B**2"
> m <- gregexpr("[0-9]+\\.[0-9]+",x)
> out <- unlist(regmatches(x,m) )
> out
[1] "0.7" "0.3"

A more complex example:

> x <- c("1 - 0.7*B - 0.3*B**2", "1 - 0.3*B - 0.7*B**2","1 - 1.3*B - 0.6*B**2")
> m <- gregexpr("[0-9]+\\.[0-9]+",x)
> out <- unlist(regmatches(x,m) )
> out.mat <- matrix(as.numeric(out), ncol=2,nrow=length(x), byrow = TRUE,
+                 dimnames = list(paste0("exp_",seq_along(x)),c("B", "B^2")))
> out.mat
        B B^2
exp_1 0.7 0.3
exp_2 0.3 0.7
exp_3 1.3 0.6

Upvotes: 1

Related Questions