在C#datagrid中显示MATLAB数组

问题描述 投票:0回答:1

我正在使用MATLAB中的一些函数制作一个C#应用程序。我在MATLAB中开发了一些.dll,我在Visual Studio上运行它,其中一个函数返回一个数组,我想用C#在数据网格中显示这些数据,但我不知道如何实现集成。我会帮助你,谢谢。

c# visual-studio matlab
1个回答
0
投票

这是创建2D数组的Matlab函数示例:

MATLAB代码:

function result = mymatrix()
result = [[2,3,4]; [12,13,14];  [22,33,44]];
return;
end

接下来使用编译器/编译器SDK工具箱将函数转换为.NET dll

接下来引用那些创建的DLL并在C#中引用MWArray.dll

这是你要求的C#代码:在GridView中将2d数组转换为datagrid

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

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //create Object from your dll
            mymatrix.Class1 MyObject = new mymatrix.Class1();

            //run the method which gets the data and save in a MWArray object
            MWArray MatlabData= MyObject.mymatrix();

            //cast the data to MWNumericArray
            MWNumericArray TableValuesMat = (MWNumericArray)MatlabData;

            // now cast to a double array   
            double[,] TableValues = (double[,])TableValuesMat.ToArray();

            // now convert 2d array to a table in gridview:
            int height = TableValues.GetLength(0);
            int width = TableValues.GetLength(1);
            this.dataGridView1.ColumnCount = width;
            for (int r = 0; r < height; r++)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(this.dataGridView1);

                for (int c = 0; c < width; c++)
                {
                    row.Cells[c].Value = TableValues[r, c];
                }

                this.dataGridView1.Rows.Add(row);
            }


        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.