C#.NET 調用 MatlabBP神經網絡工具箱——通過調用matlab引擎實現


【這是筆者上一篇博客,本文提供另一種方式去解決調用matlab工具箱的問題】http://www.cnblogs.com/Erma/p/9349185.html

啥也不說了,上主要代碼!

using DoSmoothPro;
using MathWorks.MATLAB.NET.Arrays;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test_BPnetApp
{
    public partial class Form1 : Form
    {
        List<double[]> specList1 = new List<double[]>();

        List<double[]> specList2 = new List<double[]>();

        List<double[]> trainList = new List<double[]>();

        List<double[]> testList = new List<double[]>();

        double[] origenalX, origenalY,smoothedY;

        int femaleCount, maleCount;

        //DoNetClass doNetClass = new DoNetClass();
        MLApp.MLApp matlab = null;

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 導入數據
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_loadTranData_Click(object sender, EventArgs e)
        {
            specList1.Clear();
            femaleCount = 0;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.txt)|*.txt|(*.*)|*.*";
            ofd.RestoreDirectory = true;
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                String[] names = ofd.FileNames;
               // List<Double> arr1 = new List<Double>();
                List<Double> arr2 = new List<Double>();
                for (int i = 0; i < names.Length; i++)
                {
                    arr2.Clear();
                    femaleCount++;
                    FileStream fs = new FileStream(names[i], FileMode.Open);
                    StreamReader sr = new StreamReader(fs);
                    
                    try
                    {
                        string line = sr.ReadLine();
                        while (line != null)
                        {
                            
                            String[] a = line.Split(' ');
                            
                            //arr1.Add(double.Parse(a[0]));
                            arr2.Add(double.Parse(a[1]));
                            
                            line = sr.ReadLine();
                        }
                        //double[] bfwavelength = arr1.ToArray();
                        double[] bfspec = arr2.ToArray();
                        specList1.Add(bfspec);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message.ToString());
                    }
                    finally
                    {
                        sr.Close();
                        fs.Close();
                    }
                }
            }
            ofd.Dispose();
        }

       /// <summary>
       /// 導入數據
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            specList2.Clear();
            maleCount = 0;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.txt)|*.txt|(*.*)|*.*";
            ofd.RestoreDirectory = true;
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                String[] names = ofd.FileNames;
                //List<Double> arr1 = new List<Double>();
                List<Double> arr2 = new List<Double>();
                for (int i = 0; i < names.Length; i++)
                {
                    arr2.Clear();
                    maleCount++;
                    FileStream fs = new FileStream(names[i], FileMode.Open);
                    StreamReader sr = new StreamReader(fs);
                    try
                    {
                        string line = sr.ReadLine();
                        while (line != null)
                        {

                            String[] a = line.Split(' ');
                            //arr1.Add(double.Parse(a[0]));
                            arr2.Add(double.Parse(a[1]));
                            

                            line = sr.ReadLine();
                        }
                        //double[] bfwavelength = arr1.ToArray();
                        double[] bfspec = arr2.ToArray();
                        specList2.Add(bfspec);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message.ToString());
                    }
                    finally
                    {
                        sr.Close();
                        fs.Close();
                    }
                }
            }
            ofd.Dispose();
        }

        /// <summary>
        /// 導入測試數據
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_loadTestData_Click(object sender, EventArgs e)
        {
            testList.Clear();
            //maleCount = 0;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.txt)|*.txt|(*.*)|*.*";
            ofd.RestoreDirectory = true;
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                String[] names = ofd.FileNames;
                //List<Double> arr1 = new List<Double>();
                List<Double> arr2 = new List<Double>();
                for (int i = 0; i < names.Length; i++)
                {
                    arr2.Clear();
                    //maleCount++;
                    FileStream fs = new FileStream(names[i], FileMode.Open);
                    StreamReader sr = new StreamReader(fs);
                    try
                    {
                        string line = sr.ReadLine();
                        while (line != null)
                        {

                            String[] a = line.Split(' ');
                            //arr1.Add(double.Parse(a[0]));
                            arr2.Add(double.Parse(a[1]));


                            line = sr.ReadLine();
                        }
                        //double[] bfwavelength = arr1.ToArray();
                        double[] bfspec = arr2.ToArray();
                        testList.Add(bfspec);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message.ToString());
                    }
                    finally
                    {
                        sr.Close();
                        fs.Close();
                    }
                }
            }
            ofd.Dispose();
        }

        /// <summary>
        /// 開始測試
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_test_Click(object sender, EventArgs e)
        {
            double[,] simdata = new double[512,testList.Count];
            double[,] simdataIm= new double[512,testList.Count];
            for (int i = 0; i < testList.Count; i++)
            {
                for (int j = 0; j < 512; j++)
                {
                    simdata[j, i] = testList[i][j];
                }
            }

            matlab.PutFullMatrix("simdata", "base", simdata, simdataIm);
            matlab.Execute(@"sim_Ren = doSim(simdata)");


            double[,] result = matlab.GetVariable("sim_Ren", "base");
            for(int i=0;i<result .Length;i++)
            {
                richTextBox1.AppendText(result[0,i].ToString("f5")+"\r\n");
            }
           

        }

        /// <summary>
        /// 初始化matlab環境和工作路徑,一定要先安裝matlab才行。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            
            Type matlabAppType = Type.GetTypeFromProgID("Matlab.Application");
            matlab = Activator.CreateInstance(matlabAppType) as MLApp.MLApp;
            string command;
            command = "clear all;";
            matlab.Execute(command);
            matlab.Visible = 0;
            string path_project = Directory.GetCurrentDirectory();   //工程文件的路徑,如bin下面的debug  
            command = "cd('" + path_project + "')";     //自定義matlab工作路徑       
            matlab.Execute(command);
        }

        /// <summary>
        /// 關閉matlab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            string command2 = @"close all";
            matlab.Execute(command2);

            matlab.Quit();
        }

        /// <summary>
        /// 初始化matlab,有時候有緩存在matlab環境中,用此方法清理。
        /// 神經網絡訓練不好時,清理也沒用,要關掉程序重新開始才訓練的好效果。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void init_matlab_Click(object sender, EventArgs e)
        {
            string command2 = @"close all";
            matlab.Execute(command2);
            matlab.Quit();

            Type matlabAppType = Type.GetTypeFromProgID("Matlab.Application");
            matlab = Activator.CreateInstance(matlabAppType) as MLApp.MLApp;
            string command;
            command = "clear all;";
            matlab.Execute(command);
            matlab.Visible = 0;
            string path_project = Directory.GetCurrentDirectory();   //工程文件的路徑,如bin下面的debug  
            command = "cd('" + path_project + "')";     //自定義matlab工作路徑       
            matlab.Execute(command);

        }

        /// <summary>
        /// 導入數據后,開始訓練
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_tran_Click(object sender, EventArgs e)
        {
            
            trainList.AddRange(specList1);
            trainList .AddRange(specList2);
            double[,] arraydata = new double[512, femaleCount + maleCount];
            double[,] arraydataIm = new double[512, femaleCount + maleCount];
            for (int i=0;i<femaleCount +maleCount;i++)
            {
                for(int j=0;j<512;j++)
                {
                    arraydata[j,i] = trainList[i][j];
                }
            }
            double[] femaleCountnum = { femaleCount };
            double[] femaleCountIm = { 0 };
            double[] maleCountnum = { maleCount };
            double[] maleCountIm = { 0 };

            matlab.PutFullMatrix("arraydata", "base", arraydata, arraydataIm);//第一個data表示存儲的數據,第二個參數表示工作空間,第三個參數data表示輸入數據的實部,第四個參數表示輸入數據的虛部
            matlab.PutFullMatrix("femaleCount", "base", femaleCountnum, femaleCountIm);
            matlab.PutFullMatrix("maleCount", "base", maleCountnum, maleCountIm);

            string command1;
            command1 = "t=0:0.01:2*pi;y=sin(t);h=plot(t,y)";//matlab腳本命令行
            String path = Directory.GetCurrentDirectory();//獲取當前路徑
            matlab.Execute(command1);
            matlab.Execute(@" createNet(arraydata, femaleCount, maleCount)");

        }
    }
}

  一些需要注意的地方:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM