提问人:Kieran 提问时间:11/16/2023 最后编辑:Kieran 更新时间:11/17/2023 访问量:54
计算复函数与包含实部和虚部的数据之间的复残差的方法
Method to calculate complex residuals between a complex function and data containing real and imaginary parts
问:
我正在 RStudio 中构建一个脚本,该脚本可以拟合 Z = a + ib 形式的复阻抗数据,以对旨在描述 Z 如何随频率变化的公式进行建模。我已经看到,对于其他语言来说,一个很好的方法是最小化预测的复数值和记录为数据的复数值之间的残差。我对如何在 R 中实际实现这一点有点困惑。在 R 中是否有执行此操作的一般途径?
很抱歉没有提供更多示例代码 - 我已经对函数进行了编码并加载了我的数据,但除此之外,我真的不确定该怎么做。
典型函数的格式如下:
ZRC <- function(R2, C1)((R2)/(1+1*i*R2*w*C1))
其中 w 是从数据中记录的。 我尝试形成一个函数,这是它与数据 Z 之间的差异,然后使用 nls() 将其最小化:
diff <- function(R1, R2, C1)(Z - (R2)/(1+1*i*R2*w*C1))
model1 <- nls(diff~0, start = list(R1 = 10, R2 = 100, C1 = 1E-6))
但这给出了一个错误消息,说对象不是矩阵
答:
0赞
Ben Bolker
11/17/2023
#1
未经测试,但您可能最好编写一个函数来计算模量之和(或模量的平方和)并将其传递给最小化,例如:optim()
## Z, w are global variables in this example
sum_mod_fun <- function(p) {
## parameters must be specified as a vector; unpack them
R1 <- p[1]; R2 <- p[2]; C1 <- p[3]
pred <- R1 + R2/(1+(1i*R2*w*C1)) ## check formula!
return(sum(Mod(pred-Z)^2))
}
optim(fn = sum_mod_fun,
par = c(R1 = 10, R2 = 10, C1 = 0.00001))
## note, in this example parameter vector must be in the right order - not checked!
评论
0赞
Kieran
11/17/2023
谢谢!我认为这几乎有效。即使我输入的初始参数大致正确,我也得到“无法在初始参数下计算函数”-这是有明显原因吗?另外,我真的不明白将参数指定为向量步骤 - 这段代码是这样做还是我需要这样做: ''' p <- c(“R1”, “R2”, “C1”)?抱歉,感谢您迄今为止的所有帮助!
0赞
Kieran
11/17/2023
谢谢!我认为这奏效了,我太愚蠢了。
评论
w
dput()
sum(Mod(predicted-observed))
optim()
sumsq <- sum(Mod(function(R1, R2, C1)(R1 + ((R2)/(1+((1i)*R2*w*C1)))) - Z))) optim(par = list(R1 = 10, R2 = 10, C1 = 0.00001), fn = sumsq)
sumsq <- function(R1, R2, C1) { Mod( ...... ) }
Re
Im