You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过matlab.engine在Python中调用用户输入的字符串型Matlab函数?

解决Python调用Matlab函数的MatlabExecutionError问题

核心问题1:字符串变量调用Matlab函数的方式错误

你当前代码里的eng.function_name是直接把function_name当作固定函数名调用,而非使用变量存储的字符串值。正确做法是用getattr从Matlab引擎对象中获取对应函数:

import matlab.engine
eng = matlab.engine.start_matlab()
# 通过getattr获取字符串对应的Matlab函数对象
matlab_func = getattr(eng, function_name)
res = matlab_func(input1, input2, nargout=2)

核心问题2:函数未找到或参数类型不匹配

错误提示Undefined function 'chsn_agthm' for input arguments of type 'uint8',还需排查以下几点:

  • 确认chsn_agthm.m文件所在目录已添加到Matlab搜索路径,可在Python中调用eng.addpath('函数所在文件夹路径')手动添加。
  • 检查输入参数类型:若input1/input2是Python的numpy uint8数组,需转换为Matlab兼容类型,比如用matlab.uint8()包装,或转为函数支持的其他类型(如double)。
  • 核对Matlab函数chsn_agthm的定义,确认其确实支持uint8类型输入,若函数本身不接受该类型,需调整输入参数格式。

内容的提问来源于stack exchange,提问作者rarush

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:45:40