我想在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.
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我加载库,创建一个类实例并运行该方法.这是MATLAB代码:
disp('This message goes to the command window. Can .NET call clc?');
NET.addAssembly('SharpLab.dll');
Test = SharpLab.Test;
Test.Run();
Run Code Online (Sandbox Code Playgroud)
这确实运行,命令窗口由clc清除.第二个电话,"Hello world!",不起作用.
如何在MATLAB命令窗口中打印来自C#的消息?
编辑:我收到一条链接到http://www.mathworks.nl/support/solutions/en/data/1-C9Y0IJ/index.html?product=SL&solut=的消息.此解决方案将所有写入的信息收集到要使用的变量中,但是我正在运行的实际功能大约需要一分钟,其间有很多消息.在扔墙壁之前等待一分钟并不是我所追求的.
如何使用.NET 事件通知侦听器发生了事件,在 MATLAB 中注册事件处理程序来执行实际的打印。
这是一个查找 10000 以内所有素数的玩具示例。首先我们创建 C# 库:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
接下来我们在 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
Run Code Online (Sandbox Code Playgroud)
C# 函数FindPrimes()执行冗长的操作,同时发出事件让感兴趣的观察者了解发生的事件(基本上是在您想要将某些内容打印到 MATLAB 控制台时)。它应该立即打印而无需缓冲。