使用Matlab从C#控制台应用程序创建图形或绘图?

Con*_*ngo 6 .net c# matlab graph matlab-deployment

如果我在C#中有一个二维数组,我如何在Matlab中绘制这个数组的内容,作为二维图?我正在使用扩展方法,即

my2DArray.PlotInMatlab();
Run Code Online (Sandbox Code Playgroud)

Con*_*ngo 9

我最终搞定了这个.下面是一个示例图,由调用Matlab .m文件的.NET 4.0 C#控制台应用程序生成:

在此输入图像描述

好消息是我们可以使用Matlab的所有功能来绘制图形,只需几行.NET.

如何在.NET中执行此操作:

  1. 在Visual Studio 2010中为C#创建一个新的.NET控制台应用程序,并将其更改为.NET 4.0(右键单击该项目,选择"属性").

    1. .NET Main():

      using System;
      using System.Diagnostics;
      
      namespace MyPlotGraphUsingMatlabRuntimes
      {
          /// <summary>
          /// Display a graph in Matlab, from a .NET console app.
          /// </summary>
          class Program
          {
              static void Main(string[] args)
              {
                  var x = new double[100];
                  var y = new double[100];
                  for (int i = 0; i < 100; i++) {
                      x[i] = i;
                      y[i] = 2 ^ i;
                  }
                  MyHelper.MyMatlab.MyGraph2D(x,y);
                  Console.Write("[any key to exit]");
                  Console.ReadKey();
              }
          }
      }
      
      Run Code Online (Sandbox Code Playgroud)
    2. .NET类,提供扩展方法以在Matlab中进行互操作(命名文件MyMatlab.cs).

      using System;
      using System.Collections.Generic;
      using MathWorks.MATLAB.NET.Arrays;
      namespace MyHelper
      {
          /// <summary>
          /// Collection of chained classes to make Matlab access easier.
          /// </summary>
          public static class MyMatlab
          {
              /// <summary>
              /// Returns a double in a format that can be passed into Matlab.
              /// </summary>
              /// <param name="toMatlab">Double to convert into a form we can pass into Matlab.</param>
              /// <returns>A double in Matlab format.</returns>
              public static MWNumericArray MyToMatlab(this double toMatlab)
              {
                  return new MWNumericArray(toMatlab);
              }
              /// <summary>
              /// Converts an array that contains a single Matlab return parameter back into a .NET double.
              /// </summary>
              /// <param name="toDouble">MWArray variable, returned from Matlab code.</param>
              /// <returns>.NET double.</returns>
              public static double MyToDouble(this MWArray toDouble)
              {
                  var matNumericArray = (MWNumericArray)toDouble;
                  return matNumericArray.ToScalarDouble();
              }
              /// <summary>
              /// Converts an array that contains multiple Matlab return parameters back into a list of .NET doubles.
              /// </summary>
              /// <param name="toList">MWArray variable, returned from Matlab code.</param>
              /// <returns>List of .NET doubles.</returns>
              public static List<double> MyToDoubleList(this MWArray toList)
              {
                  var matNumericArray = toList;
                  var netArray = (MWNumericArray)matNumericArray.ToArray();
      
                  var result = new List<double>();
                  // Console.Write("{0}", netArray[1]);
                  for (int i = 1; i <= netArray.NumberOfElements; i++) // Matlab arrays are 1-based, thus the odd indexing.
                  {
                      result.Add(netArray[i].ToScalarDouble());
                  }
                  return result;
              }
              /// <summary>
              /// Converts an array that contains multiple Matlab return parameters back into a list of .NET ints.
              /// </summary>
              /// <param name="toList">MWArray variable, returned from Matlab code.</param>
              /// <returns>List of .NET ints.</returns>
              public static List<int> MyToMWNumericArray(this MWArray toList)
              {
                  var matNumericArray = toList;
                  var netArray = (MWNumericArray)matNumericArray.ToArray();
      
                  var result = new List<int>();
                  // Console.Write("{0}", netArray[1]);
                  for (int i = 1; i <= netArray.NumberOfElements; i++) // Matlab arrays are 1-based, thus the odd indexing.
                  {
                      result.Add(netArray[i].ToScalarInteger());
                  }
                  return result;
              }
              /// <summary>
              /// Converts an int[] array into a Matlab parameters.
              /// </summary>
              /// <param name="intArray">MWArray variable, returned from Matlab code.</param>
              /// <returns>List of .NET ints.</returns>
              public static MWNumericArray MyToMWNumericArray(this int[] intArray)
              {
                  return new MWNumericArray(1, intArray.Length, intArray); // rows, columns int[] realData
              }
              /// <summary>
              /// Converts an double[] array into parameter for a Matlab call.
              /// </summary>
              /// <param name="arrayOfDoubles">Array of doubles.</param>
              /// <returns>MWNumericArray suitable for passing into a Matlab call.</returns>
              public static MWNumericArray MyToMWNumericArray(this double[] arrayOfDoubles)
              {
                  return new MWNumericArray(1, arrayOfDoubles.Length, arrayOfDoubles); // rows, columns int[] realData
              }
              /// <summary>
              /// Converts an List of doubles into a parameter for a Matlab call.
              /// </summary>
              /// <param name="listOfDoubles">List of doubles.</param>
              /// <returns>MWNumericArray suitable for passing into a Matlab call.</returns>
              public static MWNumericArray MyToMWNumericArray(this List<double> listOfDoubles)
              {
                  return new MWNumericArray(1, listOfDoubles.Count, listOfDoubles.ToArray()); // rows, columns int[] realData
              }
              /// <summary>
              /// Converts a list of some type into an array of the same type.
              /// </summary>
              /// <param name="toArray">List of some type.</param>
              /// <returns>Array of some type.</returns>
              public static T[] MyToArray<T>(this List<T> toArray)
              {
                  var copy = new T[toArray.Count];
                  for (int i = 0; i < toArray.Count; i++) {
                      copy[i] = toArray[i];
                  }
                  return copy;
              }
              static private readonly MatlabGraph.Graph MatlabInstance = new MatlabGraph.Graph();
              /// <summary>
              /// Plot a 2D graph.
              /// </summary>
              /// <param name="x">Array of doubles, x axis.</param>
              /// <param name="y">Array of doubles, y axis.</param>
              /// <param name="title">Title of plot.</param>
              /// <param name="xaxis">X axis label.</param>
              /// <param name="yaxis">Y axis label.</param>
              static public void MyGraph2D(List<double> x, List<double> y, string title = "title", string xaxis = "xaxis", string yaxis = "yaxis")
              {
                  MatlabInstance.Graph2D(x.MyToMWNumericArray(), y.MyToMWNumericArray(), title, xaxis, yaxis);
              }
              /// <summary>
              /// Plot a 2D graph.
              /// </summary>
              /// <param name="x">Array of doubles, x axis.</param>
              /// <param name="y">Array of doubles, y axis.</param>
              /// <param name="title">Title of plot.</param>
              /// <param name="xaxis">X axis label.</param>
              /// <param name="yaxis">Y axis label.</param>
              static public void MyGraph2D(double[] x, double[] y, string title = "title", string xaxis = "xaxis", string yaxis = "yaxis")
              {
                  MatlabInstance.Graph2D(x.MyToMWNumericArray(), y.MyToMWNumericArray(), title, xaxis, yaxis);
              }
              /// <summary>
              /// Unit test for this class. Displays a graph using Matlab.
              /// </summary>
              static public void Unit()
              {
                  {
                      var x = new double[100];
                      var y = new double[100];
                      for (int i = 0; i < 100; i++) {
                          x[i] = i;
                          y[i] = Math.Sin(i);
                      }
                      MyGraph2D(x, y);                
                  }
      
                  {
                      var x = new double[100];
                      var y = new double[100];
                      for (int i = 0; i < 100; i++) {
                          x[i] = i;
                          y[i] = 2 ^ i;
                      }
                      MyGraph2D(x, y);
                  }
              }
          }
      }
      
      Run Code Online (Sandbox Code Playgroud)
  2. 接下来,我们将.m文件导出到.NET程序集中.我使用了Matlab 2010a(这也适用于2010b).使用32位版本的Matlab(当Matlab启动时,在启动画面中显示32位或64位).

    1. 以下Matlab代码显示图表.保存为 Graph2D.m.

      function Graph2D (x,y, titleTop, labelX, labelY)
      
      % Create figure
      myNewFigure = figure;
      
      plot(x,y)
      
      title({titleTop});
      xlabel({labelX});
      ylabel({labelY});
      
      Run Code Online (Sandbox Code Playgroud)
    2. 通过在控制台中键入以下内容在Matlab中进行测试(确保 Current Folder 将Matlab工具栏中的更改为相同的目录Graph2D.m):

      x = 0:.2:20;
      y = sin(x)./sqrt(x+1);
      Graph2D(x,y,'myTitle', 'my x-axis', 'my y-axis')
      
      Run Code Online (Sandbox Code Playgroud)
    3. 在Matlab部署工具中,添加一个类 Graph,然后添加该文件Graph2D.m,然后将其 打包到 MatlabGraph.dll (将组件名称更改为 MatlabGraph 设置,这将确定生成的.dll的名称).

    4. 在.NET项目中,添加对MatlabGraph.dll (我们刚刚编译的.NET .dll) 的引用 Graph2D.m.这将是 32-bit ,如果它与编译 32-bit Matlab的释放.

    5. 在.NET项目中,添加对32位版本的引用MWArray.dll.您可以通过搜索Matlab安装目录找到它.
    6. 再次确保一切都是一致的 32-bit或一致的 64-bit.
      1. 如果您选择 32-bit,您的.NET应用程序必须编译 x32,您必须使用 32-bit Matlab版本(它将 32-bit 在启动屏幕中显示)导出.NET .dll,您必须将该32-bit 版本导入 MWArray.dll 到您的.NET项目中.
      2. 如果您选择 64-bit将.NET应用程序编译为 All CPU,则必须使用 64-bit Matlab版本(它将 64-bit 在启动屏幕中显示)来导出.NET .dll,并且必须将该64-bit 版本 导入 MWArray.dll 到.NET项目中.
    7. 运行.NET应用程序,它将通过调用Matlab运行时显示上面的图形.
  3. 如果要将其部署到新PC,则必须在此PC上安装.NET运行时(这些是免版税的).
  4. 关于这一点的好处是你可以使用Matlab的所有功能,在Matlab中根据你的内容自定义图形.你可以做3-D图:在Matlab中创建一个新图,使用 File..New..Figure它来定制它Insert,然后使用 生成.m代码 File..Generate M file.它很明显新生成的.m文件中的行,你可以将它们复制到原始 Graph2D.m 文件中,然后重新生成 MatlabGraph.dll.例如,向图中添加标题会title({'My new title});在自动生成的.m文件中添加一行.
  5. 如果有兴趣,我可以在.NET中提供完整的C#示例项目.