Coding

VS Code 中的 MATLAB 环境

在VS Code Jupyter Notebook中运行MATLAB kernel

JamzumSum · ·updated 2026年6月21日 · 2 min read
math
math Photo by @dancristianpaduret.

Motivation

后续可能会使用 MATLAB,因此先配置开发环境。由于已习惯 VS Code 的操作方式,倾向于尝试将各类开发工作迁移至 VS Code。

Preparation

  • Licensed MATLAB
  • Python

需要注意的是,不同 MATLAB 版本支持的 Python 版本有所不同。笔者目前以 Python 3.10 为目标,向前兼容通常支持到 Python 3.7。MATLAB R2022b 最高仅支持 Python 3.9,最后一版支持 Python 3.7 的 MATLAB 为 R2021b。

MATLAB in JupyterLab

本文参考了这篇外文博客,不详细之处可查阅原文。

  1. 创建并激活虚拟环境
  2. 安装 pip 包 matlab_kernel 以及 jupyterjupyterlabipykernel
    pip install matlab_kernel jupyter jupyterlab ipykernel
    
  3. 安装 Jupyter 内核:
    python -m matlab_kernel install
    
  4. 在当前环境中安装 MATLAB Python Engine
    cd ${MATLAB_ROOT}/extern/engines/python    # ${MATLAB_ROOT} 为 MATLAB 安装目录
    python setup.py install
    

检查:运行 jupyter kernelspec list,若能列出 matlab 内核即可。

至此,已可在该环境的 Jupyter Notebook 或 JupyterLab 中编写并运行 MATLAB 代码。

MATLAB in VS Code

语法检查与高亮:使用插件 Gimly81.matlab。需要配置 mlint 路径以启用语法检查。

前文已实现在 Jupyter Notebook 中运行 MATLAB。VS Code 本身支持 Jupyter Notebook,但之前的一系列操作均在特定虚拟环境中完成,而 VS Code 在选择 MATLAB 内核时并未附带指定运行环境的选项。需要对已安装的 Jupyter 内核稍作修改,使其能在 VS Code 中正常运行。

运行 python -m matlab_kernel install 时,输出会显示 kernel.json 的存储位置,例如 C:\ProgramData\jupyter\kernels\matlab\kernel.json。打开后结构如下:

{
    "argv": [
        "python",
        "-m",
        "matlab_kernel",
        "-f",
        "{connection_file}"
    ],
    "display_name": "Matlab",
    "language": "matlab",
    "mimetype": "text/x-octave",
    "name": "matlab_connect"
}

可见确实没有指定 Python 环境。查阅 Jupyter Client 的文档,发现可以通过指定内核的环境变量来解决:

"env": {
    "VIRTUAL_ENV": "${KERNEL_VENV}",
    "PATH": "${KERNEL_VENV}\\Scripts;${PATH}"
}

在上述配置中添加 env 字段,即可让 VS Code 的 Jupyter Client 找到运行 matlab_kernel 的环境。${KERNEL_VENV} 为之前创建的虚拟环境路径。上述写法适用于 Windows;Linux 下分隔符为冒号,子目录为 bin 而非 Scripts

修改完成后,在 VS Code 的 Jupyter Notebook 中即可启动 MATLAB 内核。

后记

运行可通过测试任务解决,但调试方面目前尚未找到在 VS Code 内部实现的方法。调用 MATLAB 调试可参考 Stack Overflow 上的回答

分享
作者
JamzumSum

Open-source developer, major language: Python, C++.

Comments

Hook this up to your favourite commenting platform — Giscus, Disqus, or your own.

Continue reading