我有matlab脚本textcreator.m,用于创建一些结果文件output.txt。
并且有一些matlab.aplication()
引用将matlab函数“翻译”为c#,并且有些代码很难转换为c#,因此我决定只运行我编写的脚本。
using System;
using System.Collections.Generic;
using System.Text;
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(@"cd d:\textcreator.m");
当我单击装有Matlab的计算机上的按钮时,如何运行matlab脚本textcreator.m?
答案 0 :(得分:1)
您几乎可以理解,但是应该先matlab.Execute("cd d:\textcreator.m")
,然后再matlab.Execute("cd d:\")
,而不是matlab.Execute("run textcreator.m")
。因此您的代码应为:
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute("cd d:\");
matlab.Execute("run textcreator.m");
我还挖出了我一段时间前写的一个简单的MLApp包装器。认为对您有用。
class MLWrapper
{
private readonly MLApp.MLApp _mlapp;
public MLWrapper(bool visible = false)
{
_mlapp = new MLApp.MLApp();
if (visible)
ShowConsole();
else
HideConsole();
}
~MLWrapper()
{
Run("close all");
_mlapp.Quit();
}
public void ShowConsole()
{
_mlapp.Visible = 1;
}
public void HideConsole()
{
_mlapp.Visible = 0;
}
/// <summary>
/// Run a MATLAB command.
/// </summary>
/// <returns>Text output displayed in MATLAB console.</returns>
public string Run(string cmd)
{
return _mlapp.Execute(cmd);
}
/// <summary>
/// Run a MATLAB script.
/// </summary>
/// <returns>Text output displayed in MATLAB console.</returns>
public string RunScript(string scriptName)
{
return Run($"run '{scriptName}'");
}
/// <summary>
/// Change MATLAB's current working folder to the specified directory.
/// </summary>
public void CD(string directory)
{
Run($"cd '{directory}'");
}
public object GetVariable(string varName)
{
_mlapp.GetWorkspaceData(varName, "base", out var data);
return data;
}
public void SetVariable(string varName, object value)
{
_mlapp.PutWorkspaceData(varName, "base", value);
}
}