天天看点

NET与Matlab结合 —— 最小二乘法直线拟合(C#)

NET与Matlab结合 —— 最小二乘法直线拟合(C#)  首先是一个.m文件drawgraph.m,确保它能够在Matlab里运行。

我这里是最小二乘法直线拟合程序。

%最小二乘法直线拟合

%Created by Safirst C. Ke 2007.8.29 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);

            }

        }

    }

}

运行结果如下:

Please Input the points you want to fit:

1 2 3 4 5 6 -1 -2 -3 -4 -5 -6

NET与Matlab结合 —— 最小二乘法直线拟合(C#)

*号标记欲拟合的点,直线为拟合直线!

就写这么多,以后再加入一个曲线拟合的程序。

特别声明:在下学习.NET C#和Matlab的时间均不超过1个月,

望高手不要批评指责,照顾一下新手学习钻研的积极性!