一、添加dll
二、直接运行Matlab语句
MLApp.MLApp matlab = null;
Type matlabAppType = System.Type.GetTypeFromProgID("Matlab.Application");
matlab = System.Activator.CreateInstance(matlabAppType) as MLApp.MLApp;
string command;
command = "t=2:0.2:4*pi;y=sin(t);h = plot(t,y)";
String path = Directory.GetCurrentDirectory();//获取当前路径
matlab.Visible = 0;
matlab.Execute(command);
command = @"print(gcf, '-djpeg', '" + path + "\\Test1');close all";//保存图片
matlab.Execute(command);
三、C#调用.m文件
1、MATLAB函数如下
function s = add( n )
% calculate the sum of 1..n
s = 0;
for i = 1:n
s = s + i;
end
2、C#代码如下:
MLApp.MLApp matlab = null;
Type matlabAppType = System.Type.GetTypeFromProgID("Matlab.Application");
matlab = System.Activator.CreateInstance(matlabAppType) as MLApp.MLApp;
string path_project = @"C:\Users\pll\Desktop\Matlab"; //自定义matlab工作路径
//string path_project = Directory.GetCurrentDirectory(); //工程文件的路径,如bin下面的debug
string path_matlab = "cd('" + path_project + "')";
matlab.Execute(path_matlab);
matlab.Execute("clear all");
string command;
command = @"s=Add(10)";
matlab.Execute(command);
try
{
var result = matlab.GetVariable("s", "base");//获取结果,就是传入base字符串,而不是其他的。
Console.WriteLine("result:" + result);
}
catch (Exception)
{
throw;
}
四、注意事项
1、MATLAB文件命名不能是数字开头。
2、在向MATLAB传递字符串时,记得加单引号。
3、matlab.Execute(command),command相当于在命令窗口内容,“clear all”就是保证现在MATLAB内的变量不会影响之后的操作,但是要记得利用这个方法进行c#与MATLAB传参时,只能用标量,不能涉及到数组和矩阵,否则会报错;
4、调用的是MATLAB文件名,和函数名没有关系。