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

如何在MATLAB中导入numpy与scipy并运行Python的ADtest函数

问题解决步骤

一、修复Python函数的导入问题

原代码中numpy和scipy.stats的导入仅在脚本直接运行时(if __name__ == "__main__"代码块)执行,当MATLAB调用ADtest函数时,这些依赖并未被加载,因此触发NameError: name 'np' is not defined报错。修改方式如下:

将导入语句移至函数定义前,确保任何调用场景下都能加载依赖:

import numpy as np
from scipy import stats

def ADtest(a,b):
    rng = np.random.default_rng()
    method = stats.PermutationMethod(n_resamples=9999, random_state=rng)
    res = stats.anderson_ksamp([a,b], method=method)
    print(a)
    print(b)
    print(res.statistic)
    print(res.critical_values)
    print(res.pvalue)
    
if __name__ == "__main__":
    import sys
    input_list1 = list(map(int, sys.argv[1].strip('[]').split(',')))
    input_list2 = list(map(int, sys.argv[2].strip('[]').split(',')))
    a = np.array(input_list1)
    b = np.array(input_list2)
    ADtest(a,b)

二、切换MATLAB至Anaconda的Python环境

当前MATLAB使用的是系统自带的Python 3.9(路径/Library/Developer/CommandLineTools/usr/bin/python3),而你的Anaconda base环境(Python 3.12)才是预装numpy和scipy的环境,需按以下步骤切换:

  • 关闭MATLAB:必须完全退出MATLAB才能修改Python环境配置。
  • 配置终端环境变量:
    打开终端,执行命令将Anaconda的Python路径优先级设为最高:
    export PATH="/opt/anaconda3/bin:$PATH"
    
    若需永久生效,将上述命令添加到shell配置文件(如~/.zshrc或~/.bash_profile),再执行source ~/.zshrc(对应你的shell类型)使配置生效。
  • 重启MATLAB并验证:
    打开MATLAB,输入pyenv命令,检查Executable路径是否变为/opt/anaconda3/bin/python3,Version是否为3.12.4。
    若路径未自动切换,可手动指定:
    pyenv('Version','/opt/anaconda3/bin/python3')
    
    再次执行pyenv确认切换成功。

三、验证依赖可用性

在MATLAB命令行执行以下代码,确认Anaconda环境中的numpy和scipy可正常导入:

py.importlib.import_module('numpy')
py.importlib.import_module('scipy.stats')

无报错即表示依赖加载正常。

四、重新调用Python函数

完成上述修改后,重新运行你的MATLAB代码即可正常执行ADtest函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:07:24