gpt4 book ai didi

c# - 从 C# 向 MATLAB 写行

转载 作者:太空狗 更新时间:2023-10-29 23:23:13 24 4
gpt4 key购买 nike

我想通过 C# 方法在 MATLAB 命令窗口中写入一行。这是 .NET 代码:

using System;

namespace SharpLab {
public class Test {
public void Run() {
dynamic Matlab = Activator.CreateInstance(Type.GetTypeFromProgID("Matlab.Application"));
Matlab.Execute("clc"); // This line does work.
Matlab.Execute("disp('Hello world!')"); // This line does not work.
}
}
}

现在我加载库,创建类实例并运行该方法。这是 MATLAB 代码:

disp('This message goes to the command window. Can .NET call clc?');
NET.addAssembly('SharpLab.dll');
Test = SharpLab.Test;
Test.Run();

这确实会运行,命令窗口会被 clc 清除。第二个调用“Hello world!”不起作用。

如何在 MATLAB 命令窗口中打印来自 C# 的消息?

编辑:我收到一条链接到 http://www.mathworks.nl/support/solutions/en/data/1-C9Y0IJ/index.html?product=SL&solut= 的消息.该解决方案将所有书面信息收集到一个变量中以供使用,但是我正在运行的实际功能确实工作了大约一分钟,其间有很多消息。在抛出一堵文字墙之前等待一分钟并不是我所追求的。

最佳答案

如何使用 .NET events通知听众发生了一个事件,你在哪里register an event handler in MATLAB进行实际打印。

这是一个玩具示例,可以找到 10000 以内的所有质数。首先,我们创建 C# 库:

我的类.cs

using System;

namespace MyLibrary
{
public class MyClass
{
// function that does some work and notify listeners of occurred events
public void FindPrimes()
{
// Primes between 1 and 10000
for (int i = 1; i < 10000; i++)
{
if (MyClass.isPrime(i))
{
//System.Console.WriteLine(i);
onPrimeFound(i);
}
}
}

// helper function to determine if number is prime
public static bool isPrime(int x)
{
if (x == 1) return false;
if (x == 2) return true;
for (int i = 2; i <= Math.Ceiling(Math.Sqrt(x)); i++)
{
if (x % i == 0) return false;
}
return true;
}

// event broadcasted
public event EventHandler PrimeFound;
protected void onPrimeFound(int x)
{
var handler = this.PrimeFound;
if (handler != null)
{
handler(this, new PrimeEventArgs(x));
}
}
}

// event data passed to listeners
public class PrimeEventArgs : EventArgs
{
public readonly int number;
public PrimeEventArgs(int x)
{
this.number = x;
}
}
}

MATLAB

接下来我们在 MATLAB 中使用我们的类库:

>> NET.addAssembly('C:\path\to\MyLibrary.dll');
>> c = MyLibrary.MyClass();
>> lh = addlistener(c, 'PrimeFound', @(o,e) fprintf('Prime: %d\n', e.number));
>> c.FindPrimes()
Prime: 2
Prime: 3
Prime: 5
...
Prime: 9973

C# 函数 FindPrimes() 执行一个冗长的操作,同时发出事件让感兴趣的观察者知道发生的事件(基本上是在您想要将某些内容打印到 MATLAB 控制台时)。它应该立即打印而无需缓冲。

关于c# - 从 C# 向 MATLAB 写行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19181573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com