본문으로 건너뛰기
cccskills
무료GitHub에 공개

matlab-call-python

Call Python libraries from MATLAB using the py. interface, pyrun, pyrunfile, or pyenv. Use when writing or executing MATLAB code that calls Python functions or passes data between MATLAB and Python. REQUIRED when triaging Python errors from MATLAB (ModuleNotFoundError, ImportError, "Unable to resolve the name 'py.*'"). REQUIRED when setting up Python environments for MATLAB, creating virtual environments, or installing Python packages for use with MATLAB.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(3)

  • SKILL.md7.0 KB
  • manifest.yaml413 B
  • references/environment-setup.md3.1 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Call Python from MATLAB

Call Python libraries from MATLAB using modern APIs, correct environment setup, and structured error recovery.

When to Use

  • Writing MATLAB code that calls Python via py.*, pyrun, or pyrunfile
  • MATLAB code fails with ModuleNotFoundError, Python is not configured, or other Python-related errors
  • User asks to set up Python for MATLAB or create a virtual environment
  • User asks to install a Python package for use in MATLAB

When NOT to Use

  • Calling MATLAB from Python (MATLAB Engine API for Python — different direction)
  • Building MEX files or Python C extensions
  • Pure Python development with no MATLAB involvement
  • MATLAB Compiler or MATLAB Production Server deployment

Rules

NEVER use pyargs

Use MATLAB name=value syntax for Python keyword arguments. pyargs is outdated (name=value available since R2021a).

% TEMPLATE — not executable (requires scikit-learn)
rfc = py.sklearn.ensemble.RandomForestClassifier(n_estimators=int32(100), random_state=int32(42));

NEVER use pyversion

pyversion is not recommended. Use pyenv, which supports terminate, ExecutionMode, and environment switching.

ALWAYS use the Bash tool for pip installs and venv creation

Do not use MATLAB system(). The Bash tool provides streaming output and avoids complex string escaping.

ALWAYS follow recovery procedure before any pip install or venv creation

BEFORE running pip install or creating virtual environments, follow references/environment-setup.md. Do NOT infer Python paths from error tracebacks — those paths show importlib internals, not the correct install target.

ALWAYS ask user confirmation before calling terminate(pyenv)

terminate(pyenv) restarts the Python process and clears all Python state (imported modules, variables, open connections). Always inform the user what will be lost and get explicit consent before calling terminate.

ALWAYS wrap with integer types when Python expects int

MATLAB passes double by default. Python functions expecting int receive float, causing TypeError. Use int32() for counts, indices, and size arguments. If the value won't fit in 32 bits, use int64() or uint64() to prevent overflow.

ALWAYS use pystringarray for string arrays (R2026a or later)

When passing MATLAB string arrays to Python in R2026a or later, use pystringarray. Requires NumPy 2.0 or later. In R2025b and earlier, or when NumPy < 2.0, use py.list(cellstr(...)).

% R2026a and later:
names = ["Alice", "Bob", "Charlie"];
pyNames = pystringarray(names);

% R2025b and earlier:
names = ["Alice", "Bob", "Charlie"];
pyNames = py.list(cellstr(names));

Workflow

When calling Python from MATLAB, follow this workflow.

1. Write the Python code using modern syntax

result = py.module.function(arg1, arg2, kwarg1="value", kwarg2=42);

Prefer py.module.function(...) for direct function calls — it's readable, integrates with the MATLAB workspace, and supports tab completion. Reserve pyrun for multi-statement scripts where variables and imports persist in Python memory across calls (REPL-like execution). Reserve pyrunfile for running a standalone .py file (equivalent to running from the command line; no state carries over).

2. Run the code

Execute via mcp__matlab__evaluate_matlab_code (for inline code) or mcp__matlab__run_matlab_file (for script files).

3. If it succeeds — done

4. If it fails with a Python error — triage

Follow references/environment-setup.md ONLY for environment-related errors:

  1. ModuleNotFoundError
  2. MATLAB error about unresolved py.* name (e.g., "Unable to resolve the name 'py.numpy'")
  3. pyenv().Executable is empty
  4. py or pyenv calls error stating environment is not supported
  5. Any other error suggesting a missing library or unconfigured environment

For all other Python errors (ValueError, TypeError, logic errors in the Python code itself) — debug the code directly. These are code bugs, not environment issues.

Key Functions

FunctionPurposeAvailable From
pyenvQuery/configure Python environmentR2019b
pyrunExecute Python statements; variables persist across callsR2021b
pyrunfileExecute a standalone .py fileR2021b
pystringarrayPass MATLAB string array to PythonR2026a

InProcess vs OutOfProcess

  • OutOfProcess: Launches Python in a separate process. Mitigates third-party library conflicts between MATLAB and Python, therefore works with most Python packages without conflict. terminate(pyenv) restarts Python without restarting MATLAB. Can switch environments freely.
  • InProcess: (default) Launches Python within the same MATLAB process. PREFER for better performance. Cannot terminate. If Python is already loaded in InProcess mode, the user must restart MATLAB entirely to change Python configuration.

In ExecutionMode="OutOfProcess", when working on a custom Python module and you need to make changes after loading the module, or when you install packages mid-session, ALWAYS call terminate(pyenv) before calling the module again.

In ExecutionMode="InProcess", when working on a custom Python module and you need to make changes after loading the module, ALWAYS reload the module by running:

clear all;
clear classes;
mod = py.importlib.import_module("<module_name>");
py.importlib.reload(mod);

Patterns

Calling a Python function with keyword arguments

rfc = py.sklearn.ensemble.RandomForestClassifier(n_estimators=int32(100), random_state=int32(42));
rfc.fit(XTrain, yTrain);
predictions = double(rfc.predict(XTest));

Configuring MATLAB to use a virtual environment

After creating a virtual environment (venv) using the Bash tool, point MATLAB at it:

% Terminate current Python if loaded
terminate(pyenv);

% Point at venv executable
pyenv(Version="/path/to/.venv/Scripts/python.exe");

% Verify
disp(pyenv().Executable);
py.numpy.array([1, 2, 3]);

Conventions

  • When a keyword argument name conflicts with a MATLAB variable, append Val (e.g., py.complex(imag=imagVal) not py.complex(imag=imag))
  • AVOID "activating" a virtual environment — MATLAB doesn't use activation scripts. Point pyenv(Version=...) at the venv executable directly.

Copyright 2026 The MathWorks, Inc.


리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Guide for accessing financial and economic data in MATLAB using the Datafeed Toolbox. Covers Bloomberg (market data via bloomberg/blp/bloombergHypermedia), FRED (Federal Reserve economic data via fredrs), Haver Analytics (economic data via haver/haverdirect/haverview), and LSEG Datastream (historical data via datastreamws). Use when connecting to any of these data providers from MATLAB.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

Read BEFORE writing any code that adds Additive White Gaussian Noise (AWGN) to signals and converts between SNR, Eb/No, Es/No, and per-subcarrier SNR for communications simulations, using awgn(), convertSNR(), berawgn(). The default MATLAB patterns for AWGN (e.g., 'measured' option, manual SNR formulas) produce subtly incorrect results. This skill specifies the correct calling conventions, required function usage, and critical anti-patterns that must be avoided.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

Analyze AMS waveform data using Mixed-Signal Blockset utilities: phase noise measurement, clock jitter, anti-aliased resampling, timing measurements, lock time, INL/DNL, ADC/DAC calibration, HSpice import. Use when analyzing time-domain voltage from PLL/VCO/clock simulations, measuring phase noise from variable-step solver output, computing jitter, or resampling non-uniform data.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

Design and analyze electrically large antenna structures using MATLAB Antenna Toolbox. Covers reflector antennas (parabolic, Cassegrain, Gregorian, offset, corner, cylindrical, spherical, custom STL), reflectarrays and reconfigurable intelligent surfaces (RIS), antennas installed on platforms (vehicles, aircraft, ships, satellites), and radar cross section (RCS) analysis. Includes solver selection (MoM-PO, PO, MoM, FMM), mesh control, and GPU acceleration. Use when the user wants to design a dish/reflector antenna, reflectarray, analyze an antenna on a platform, or compute RCS.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

Analyze data using MATLAB. Use when the task involves tables, timetables, time-series data, numeric arrays, sensor matrices, or gridded data — including but not limited to exploring, row filtering, sorting, cleaning, transforming, aggregating, smoothing, padding, trimming, and answering questions about data. MATLAB provides extensive, easy-to-use built-in functions for these workflows with no additional products required.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

S-parameters, insertion loss, fields, currents, mesh control, and solver selection for RF PCB performance validation. TRIGGER: user asks to compute S-parameters, analyze insertion/return loss, extract fields or currents, compare MoM vs FEM, or control mesh for any RF PCB component. Invoke BEFORE writing sparameters() or solver code — API is non-obvious. SKIP: designing or creating components (use the specific matlab-design-pcb-* skill), material/stackup setup only (use matlab-manage-pcb-material), optimization sweeps (use matlab-optimize-pcb-design), PDN/IR-drop analysis (use matlab-analyze-pcb-pdn).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

matlab의 스킬 모두 보기

이 스킬의 문제 신고