⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 form1.cs

📁 C#调用Matlab2008b的两个例子
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using MathWorks.MATLAB.NET.Arrays;
using MatMagic;

namespace CShaprMatlabDemo
{
    public partial class Form1 : Form
    {
        //创建Matlab的访问对象,new这个对象非常耗时,建议new一次反复用
        MatMagic.MatMagic theMagic;
        TextBox[,] 输出矩阵控件数组;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            theMagic = new MatMagic.MatMagic();
        }

        void 清除控件(Control[,] controls, Control 容器控件)
        {
            if (controls == null) return;
            for (int i = 0; i < controls.GetLength(0); i++)
                for (int j = 0; j < controls.GetLength(1);j++ )
                {
                    if (controls[i, j] != null)
                    {
                        容器控件.Controls.Remove(controls[i, j]);
                        controls[i, j] = null;
                    }
                }
            controls = null;
        }

        TextBox[,] 产生控件数组(int n, int m, Control 容器控件)
        {
            TextBox[,] 结果 = new TextBox[n, m];
            int w = 容器控件.ClientSize.Width / (m + 1);
            int h = 容器控件.ClientSize.Height / (n + 1);

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    TextBox control = new TextBox();
                    control.Visible = false;
                    control.Multiline = true;
                    control.Size = new Size(w - 3, h - 3);
                    control.Location = new Point(j * w + w / 2, i * h + h / 2);
                    control.Parent = 容器控件;
                    control.Visible = true;
                    结果[i, j] = control;
                }
            }
            return 结果;
        }

        private void button产生幻方_Click(object sender, EventArgs e)
        {
            MWNumericArray x = new MWNumericArray(new double[] { (double)numericUpDown1.Value });
            MWArray[] agrsOut = new MWArray[1];
            MWArray[] agrsIn = new MWArray[] { x };
            theMagic.mymagic(1, ref agrsOut, agrsIn);
            MWNumericArray y = agrsOut[0] as MWNumericArray;
            //逐个访问结果,注意下标从1开始

            int n=y.Dimensions[0];
            int m=y.Dimensions[1];

            清除控件(输出矩阵控件数组, groupBox输出矩阵1);
            输出矩阵控件数组 = 产生控件数组(n, m, groupBox输出矩阵1); 
            for (int i = 0; i <n ; i++)
            {
                for (int j = 0; j <m; j++)
                {
                    输出矩阵控件数组[i , j ].Text = y[i+1, j+1].ToString();
                }
            }
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -