猿问

在 C# 中运行 Matlab 脚本

我有创建一些结果文件 output.txt 的 matlab 脚本 textcreator.m。


并且有一些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?


一只甜甜圈
浏览 123回答 1
1回答

神不在的星期二

你几乎已经明白了,但matlab.Execute("cd d:\textcreator.m")你应该,而不是matlab.Execute("cd d:\"),然后matlab.Execute("run textcreator.m")。所以你的代码应该是:MLApp.MLApp matlab = new MLApp.MLApp();&nbsp;matlab.Execute("cd d:\");matlab.Execute("run textcreator.m");我还挖出了我很久以前写的一个简单的 MLApp 包装器。认为它会对你有用。class MLWrapper{&nbsp; &nbsp; private readonly MLApp.MLApp _mlapp;&nbsp; &nbsp; public MLWrapper(bool visible = false)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _mlapp = new MLApp.MLApp();&nbsp; &nbsp; &nbsp; &nbsp; if (visible)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ShowConsole();&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HideConsole();&nbsp; &nbsp; }&nbsp; &nbsp; ~MLWrapper()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Run("close all");&nbsp; &nbsp; &nbsp; &nbsp; _mlapp.Quit();&nbsp; &nbsp; }&nbsp; &nbsp; public void ShowConsole()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _mlapp.Visible = 1;&nbsp; &nbsp; }&nbsp; &nbsp; public void HideConsole()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _mlapp.Visible = 0;&nbsp; &nbsp; }&nbsp; &nbsp; /// <summary>&nbsp; &nbsp; /// Run a MATLAB command.&nbsp; &nbsp; /// </summary>&nbsp; &nbsp; /// <returns>Text output displayed in MATLAB console.</returns>&nbsp; &nbsp; public string Run(string cmd)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return _mlapp.Execute(cmd);&nbsp; &nbsp; }&nbsp; &nbsp; /// <summary>&nbsp; &nbsp; /// Run a MATLAB script.&nbsp; &nbsp; /// </summary>&nbsp; &nbsp; /// <returns>Text output displayed in MATLAB console.</returns>&nbsp; &nbsp; public string RunScript(string scriptName)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return Run($"run '{scriptName}'");&nbsp; &nbsp; }&nbsp; &nbsp; /// <summary>&nbsp; &nbsp; /// Change MATLAB's current working folder to the specified directory.&nbsp; &nbsp; /// </summary>&nbsp; &nbsp; public void CD(string directory)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Run($"cd '{directory}'");&nbsp; &nbsp; }&nbsp; &nbsp; public object GetVariable(string varName)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _mlapp.GetWorkspaceData(varName, "base", out var data);&nbsp; &nbsp; &nbsp; &nbsp; return data;&nbsp; &nbsp; }&nbsp; &nbsp; public void SetVariable(string varName, object value)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _mlapp.PutWorkspaceData(varName, "base", value);&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答