C#调用Matlab引擎详细方法以及注意事项

本文详细介绍了如何使用C#调用Matlab,包括添加dll、直接运行Matlab语句、调用.m文件及注意事项。通过具体示例,演示了如何在C#中执行Matlab代码、获取结果及处理数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、添加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文件名,和函数名没有关系。
在这里插入图片描述在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值