如何从.NET应用向MATLAB函数传递矩阵作为输入?
.NET调用MATLAB函数传递矩阵的报错解决
问题背景
需要从.NET应用向MATLAB函数传递矩阵作为输入,相关代码及报错如下:
MATLAB目标函数
function myfunc(info); sort(info) end
期望接收的矩阵格式:
info = [... 0 0 0; ... 0 120 0; ... 240 120 0; ... 240 0 0; ... ];
.NET初始代码及报错
MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute(@"cd C:\scripts\myfunc.m"); object result = null; int[,] input = new int[4, 3] { { 0, 0, 0 }, { 0, 120, 0 }, { 240, 120, 0 }, { 240, 0, 0 } }; matlab.Feval("myfunc", 0, out result, input);
执行Feval时报错:error using norm first argument must be single or double.
修改后的.NET代码及新报错
将输入改为三维数组:
int[,,] input = new int[4, 1, 3] { { {0, 0, 0} }, { {0, 120, 0} }, { {240, 120, 0} }, { {240, 0, 0} } };
报错变为:index in position 1 exceeds array bounds. index must not exceed 1
解决方案
1. 修复数据类型不匹配问题
MATLAB的sort函数默认仅支持单精度(single)或双精度(double)类型数组,.NET传递的int类型无法兼容,这是第一个报错的核心原因。需将.NET中的数组转换为double[,]类型。
2. 修正数组维度匹配问题
MATLAB中的二维矩阵对应.NET的二维数组([,]),无需改为三维数组。三维数组会让MATLAB接收到三维张量,与函数预期的二维矩阵不匹配,进而引发索引越界错误。
修正后的完整.NET代码
MLApp.MLApp matlab = new MLApp.MLApp(); // cd命令需指向脚本所在目录,而非.m文件本身 matlab.Execute(@"cd C:\scripts"); object result = null; // 使用double类型二维数组,匹配MATLAB数值类型要求 double[,] input = new double[4, 3] { { 0, 0, 0 }, { 0, 120, 0 }, { 240, 120, 0 }, { 240, 0, 0 } }; // 正确传递参数调用函数 matlab.Feval("myfunc", 0, out result, input);
额外注意事项
cd命令的路径必须是.m文件所在的目录,而非文件路径,否则MATLAB无法定位到目标函数。- 若需保留整数类型,可在MATLAB函数内手动转换:
sort(double(info)),但更推荐在.NET端直接传递double类型,避免额外的类型转换开销。
内容的提问来源于stack exchange,提问作者Mariam Sultan
相关产品推荐
相关产品推荐

