【问题标题】:How to get coefficients of polynomial expression如何获得多项式表达式的系数
【发布时间】:2016-07-11 03:18:22
【问题描述】:

我使用了rSymPy,得到了如下表达式:

“1 - 0.7*B - 0.3*B**2”

现在我想提取 B 的系数和 B^2 的系数,并存储在一个矩阵中。我在 R 中尝试了 gsub 函数,有什么建议吗?

【问题讨论】:

  • 我不知道 rSymPy,但是在 Python SymPy 中你可以使用 Poly(expr).coeffs()

标签: r sympy gsub


【解决方案1】:

你的意思是:

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

一个更复杂的例子:

> 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

【讨论】:

  • 第一个表达式的B系数为-0.7,B^2系数为-0.3。如何获得正确的标志?
【解决方案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

【讨论】:

  • 抱歉错过了。你也可以这样做:m &lt;- gregexpr("-? [0-9]+\\.[0-9]+",x)
  • 非常感谢
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2015-12-01
相关资源
最近更新 更多