How to get coefficients of polynomial expression

淺唱寂寞╮ 提交于 2019-12-25 09:13:03

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/38298663/how-to-get-coefficients-of-polynomial-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!