C#My ArrayList仅包含最后一项

时间:2016-05-29 09:25:48

标签: c# matlab

我在C#Visual Studio中有以下代码。我正在尝试使用MATLAB通过COM服务器绘制数据。我能够做到这一点,但是使用我的代码,MATLAB输出控制台只显示变量“数字”的最后一个值,当它绘制时,它会覆盖所有以前的值。另外,如何使变量大小动态化?我的目标是实时绘制数据。任何建议将不胜感激!

     using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Text;
     using System.Threading.Tasks;

     namespace ConsoleApplication4
      {
         class Program
         {
    static void Main(string[] args)
    {
        ////// Create the MATLAB instance 
        MLApp.MLApp matlab = new MLApp.MLApp();

        for (int j = 1; j <= 10; j++)
        {
            int[] numbers = new int[11];
            numbers[j] = j * 15;
            matlab.Execute("numbers");
            matlab.PutWorkspaceData("A", "base",numbers);
            matlab.Execute("plot(A);");
        }
        //    //Console.WriteLine(j*15);
        //}
        //Console.ReadKey();
    }
}

}

更新:

  var numbers = new List<int>();
        for (int j = 1; j <= 10; j++)
        {
            //numbers[j] = j * 15;
           int val= j * 15;
            numbers.Add(val);
            var array = numbers.ToArray();
            matlab.Execute("array");
            matlab.PutWorkspaceData("A", "base", array);
            matlab.Execute("plot(A);");
         }

2 个答案:

答案 0 :(得分:1)

不要在循环内初始化numbers。这样每次都会创建一个新实例。

试试这个:

int[] numbers = new int[11];
for (int j = 1; j <= 10; j++){
  numbers[j] = j * 15;
  //double vIn = Convert.ToDouble(numbers);
  matlab.Execute("numbers");
  matlab.PutWorkspaceData("A", "base",numbers);
  matlab.Execute("plot(A);");
}

<强>更新

制作动态大小的数组。使用List<>。 然后你必须改变循环:

List<int> numbers = new List<int>();
for (int j = 1; j <= 10; j++){
  int val = j * 15;
  numbers.Add(val);
  ....
}

答案 1 :(得分:1)

你必须移动这一行     int[] numbers = new int[11];  在for for循环之前

并将其放在

之后
'MLApp.MLApp matlab = new MLApp.MLApp();'
相关问题