Math.Net数值-拟合窦函数 [英] Math.Net Numerics - Fitting sinus function

查看:96
本文介绍了Math.Net数值-拟合窦函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这里的新手,我希望也许那里的专家可以为我提供帮助: 我想通过C#中的"math.net数字"库来拟合窦函数f(x) = a *sin(b* (x+c))+d.

I'm new here and I hope that perhaps the experts outthere can help me: I want to fit the sinus function f(x) = a *sin(b* (x+c))+d via the library "math.net numerics" in C#.

在一开始,我尝试了以下示例代码:

At the beginning I tried the following example code:

// data points: we compute y perfectly but then add strong random noise to it
var rnd = new Random(1);
var omega = 1.0d
var xdata = new double[] { -1, 0, 0.1, 0.2, 0.3, 0.4, 0.65, 1.0, 1.2, 2.1, 4.5, 5.0, 6.0 };
var ydata = xdata.Select(x => 5 + 2 * Math.Sin(omega*x + 0.2) + 2*(rnd.NextDouble()-0.5)).ToArray();

// build matrices
var X = DenseMatrix.OfColumns(new[] {
new DenseVector(1),
new DenseVector(xdata.Select(t => Math.Sin(omega*t)).ToArray()),
new DenseVector(xdata.Select(t => Math.Cos(omega*t)).ToArray())});
var y = new DenseVector(ydata);

// solve
var p = X.QR().Solve(y);
var a = p[0];
var b = SpecialFunctions.Hypotenuse(p[1], p[2]);
var c = Math.Atan2(p[2], p[1]); 

但是结果是,程序返回了以下错误:

But the result was, that the program returned the following error:

矩阵尺寸必须一致:1x3".

"Matrix dimensions must agree: 1x3".

您能给我一个提示,我可以做些什么来解决这个问题?

Could you give me a hint what I can do to solve the problem ?

推荐答案

您正在向矩阵(X)添加3个长度不同的列.

You are adding 3 columns to the matrix (X) that have different lengths.

第一个向量的长度为1,而第二和第三个向量的长度为xdata.Length.

The first vector has length 1, while the second and third vectors have lengths of xdata.Length.

如果您要使第一个向量的长度为xdata.Length,但要填充1s,则请执行以下操作:

If you intend for the first vector to have the length of xdata.Length but to be filled with 1s then do the following:

var X = DenseMatrix.OfColumns(new[]
{
    new DenseVector(Enumerable.Repeat(1d , xdata.Length).ToArray()),
    new DenseVector(xdata.Select(t => Math.Sin(omega*t)).ToArray()),
    new DenseVector(xdata.Select(t => Math.Cos(omega*t)).ToArray())
});

这篇关于Math.Net数值-拟合窦函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆