直线无所谓空间的,直线都在一平面上。如果您说的是曲线,那就比较麻烦。

最小二乘法直线拟合程序。

最小二乘法直线拟合如下:

%Created by Safirst C. Ke 2009.3.27 Wed 14:51

function drawgraph(coords)

%传入的参数为两行向量,第一行为x坐标,第二行为坐标。

%axis ([0 100 0 100]);

grid on;

hold on;

%显示欲拟合的点的位置

plot(coords(1,:), coords(2,:), '*');

%分解x,y坐标

x = coords(1,:)

y = coords(2,:)'

b = size(coords);

c = ones(1, b(2));

MT = [c; x];

M = MT';

%f为直线函数,f = mx + b;

f = inv(MT * M) * MT * y

['y = ', num2str(f(2)), 'x + ', num2str(f(1))]

%显示最终拟合的直线

x = -max(x):max(x);

y =   f(1) + f(2) * x;

plot(x, y);

xlabel('X轴');

ylabel('Y轴');

title('最小二乘法直线拟合 by Safirst C. Ke');

legend(['y = ', num2str(f(2)), 'x + ', num2str(f(1))]);

然后将这个文件包含在.NET的类库工程中,并进行编译。

这里需要理解它的过程,毕竟.NET不能编译.m文件。怎么做到的呢?

通过设置这个工程的生成事件属性,添加为

call PlotDemoBuild.bat

然后在PlotDemoBuild.bat这个文件里面写好用Matlab编译器mcc编译的命令行,最重要的部分就是

mcc -M -silentsetup -vg -B "dotnet:PlotDemoComp,Plotter,2.0,private" -d ..\..\src ..\..\drawgraph.m

这样的话,点击生成,就会通过mcc产生dll,即我们需要的类库。

然后建立我们真正的C#工程,添加引用为刚才的类库,并开始写程序program.cs

using System;

using System.Collections.Generic;

using System.Text;

using MathWorks.MATLAB.NET.Utility;

using MathWorks.MATLAB.NET.Arrays;

//这两个引用显然要添加,不过好在这两个命名空间属于一个库MWArray.dll

//C:\Program Files\MATLAB\R2007a\toolbox\dotnetbuilder\bin\win32\v2.0\MWArray.dll

using PlotDemoComp;

namespace ConsoleApplication2

{

class Program

{

//[STAThread]

static void Main(string[] args)

{

try

{

Console.WriteLine("Please Input the points you want to fit:");

string[] y = Console.ReadLine().Trim().Split();

int size = y.Length;

double[] x = new double[size];

for(int i = 0; i < size; i++)

{

x[i] = Convert.ToDouble(y[i]);

}

double[,] pointValues = new double[2, size / 2];

//从开头算起,相邻的两个数为一个点,所以x和y都是间隔一个的。如1,2,3,4代表两点(1,2),(3,4)

for(int i = 0; i < size; i += 2)

{

int index = i / 2;

pointValues[0, index] = x[i];

}

for(int i = 1; i < size; i += 2)

{

int index = (i - 1) / 2;

pointValues[1, index] = x[i];

}

Plotter plotter = new Plotter();

plotter.drawgraph((MWNumericArray)pointValues);

Console.ReadLine();

}

catch(Exception exception)

{

Console.WriteLine("Error: {0}", exception);

}

}

}

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐