Call flywheel-sdk from MATLAB
MATLAB SDK Deprecation Notice
The dedicated Flywheel MATLAB software development kit (SDK) is deprecated and will reach end of life (EOL) on August 30th, 2026. Use the approach described in this guide to call the Flywheel Python SDK directly from MATLAB instead. See Migrate from the MATLAB SDK for a comparison and migration steps.
MATLAB provides built-in support for calling Python libraries using the py. prefix. This allows you to use the Flywheel Python SDK (flywheel-sdk) directly from your MATLAB environment without needing a separate MATLAB-specific SDK.
This guide covers:
- Installing and configuring the SDK for MATLAB
- Translating common Python SDK operations into MATLAB syntax
- Helper utilities to reduce boilerplate
- Common patterns and performance tips
- Data type conversions and troubleshooting
- Migrating from the dedicated MATLAB SDK
Prerequisites
- MATLAB R2019b or later (R2023a or later recommended)
- Python 3.8 through 3.11 (3.12 and later have limited MATLAB support)
- A Python architecture (64-bit or 32-bit) that matches your MATLAB installation
Set up the environment
Step 1: Install the Flywheel Python SDK
Install flywheel-sdk into your Python environment:
For a dedicated environment (recommended), create a virtual environment:
Step 2: Configure MATLAB to use Python
Check which Python installation MATLAB uses:
If Python is not configured or you need a different version:
Note
Once Python initializes in a MATLAB session, you cannot change versions without restarting MATLAB. Configure pyenv before making any py. calls.
Step 3: Verify the setup
Run a quick import test:
For a comprehensive check that validates your MATLAB version, Python configuration, SDK installation, authentication, and basic operations, download and run the full verification script:
Download verify_matlab_python_setup.m
The script outputs a pass/fail status for each check with actionable troubleshooting steps for any failures.
Translate Python SDK calls to MATLAB
The following examples show common Python SDK operations and their MATLAB equivalents. MATLAB syntax closely mirrors Python for most SDK calls, with differences primarily in module imports, dictionary construction, and iteration.
Tip
The helper utilities section provides convenience functions that reduce the verbosity of dictionary creation, list conversion, and pagination.
Create a client and authenticate
In MATLAB, you first import the module with py.importlib.import_module(). After that, client creation follows the same pattern as Python.
Retrieve user information
You can access Python object properties directly with dot notation. Wrap Python strings in string() when displaying them with fprintf.
Look up objects by path
Path-based lookups use identical syntax in both languages.
Retrieve objects by ID
Direct retrieval by ID uses identical syntax in both languages.
Update objects
MATLAB requires py.dict() to create Python dictionaries and pyargs() for keyword arguments. Use explicit numeric types like int32() for integer values.
Find objects with filters
Filter syntax is identical. To iterate over results in MATLAB, convert the Python generator to a list with py.list(), then use cell array indexing {}.
Iterate over large result sets
MATLAB does not handle Python generators natively. Converting with py.list() loads all results into memory.
Tip
For very large datasets, use manual pagination to avoid loading everything into memory at once:
Upload files
Simple uploads use identical syntax. Adding metadata requires constructing a py.dict() object.
Download files
File iteration requires list conversion. The download call itself uses identical syntax.
Handle exceptions
Python exceptions are wrapped in MATLAB's MException object. You cannot catch specific Python exception types by name. Instead, inspect the error message for HTTP status codes.
Helper utilities
The flywheel_matlab_helpers class provides convenience functions that reduce boilerplate when working with the Python SDK from MATLAB.
Download flywheel_matlab_helpers.m
Add the file to your MATLAB path, then use its static methods:
| Method | Purpose |
|---|---|
create_client(api_key) | Initialize a Flywheel client (one-liner) |
to_py_dict(key1, val1, ...) | Create a Python dictionary from key-value pairs |
to_py_list(array) | Convert a MATLAB array or cell array to a Python list |
from_py_list(py_list) | Convert a Python list or generator to a MATLAB cell array |
safe_string(py_obj) | Convert a Python object to a string, returning '' for None |
iter_all(iterator) | Consume a Python iterator into a cell array |
paginated_find(container, filter, page, size) | Fetch one page of results |
find_all_paginated(container, filter, size) | Fetch all results using automatic pagination |
try_get_property(obj, name, default) | Access a property with a fallback for missing or None values |
setup_check() | Print diagnostic information about the environment |
Create clients and convert types
The helpers simplify the most verbose MATLAB-Python patterns:
Paginate large result sets
Use find_all_paginated to fetch all matching items without loading everything into memory at once:
Access properties safely
Python objects may return None for optional fields. Use try_get_property and safe_string to avoid errors:
Common patterns
Iterate and process containers
A common workflow is to iterate over containers and process each one:
Apply batch updates
To update multiple containers in a loop, construct the update dictionary once per iteration and pass the container ID as a string:
Handle missing or null properties
Python SDK objects may return None for optional fields. Check before converting:
Build nested metadata
Some application programming interface (API) calls require nested dictionaries. Build them from the inside out:
Performance tips
-
Import the module once and reuse the handle. Calling
py.importlib.import_module('flywheel')on every operation adds unnecessary overhead. -
Convert result lists once, then iterate. Avoid calling
py.list()repeatedly on the same data. -
Use pagination instead of
iter()for large datasets. Loading thousands of items withpy.list(fw.subjects.iter())consumes significant memory. Usefind()withlimitandskipparameters, or thefind_all_paginatedhelper. -
Pre-convert types outside loops. If you apply the same update to many containers, build the dictionary once:
-
Batch your queries. Retrieve all containers you need in a single
find()call, then process locally. Avoid callingget_session()inside a loop whenfw.sessions.find()can return all results at once.
Data type conversion reference
Automatic conversions
| Python Type | MATLAB Type | Notes |
|---|---|---|
str | char / string | Bidirectional |
int | double | Python to MATLAB automatic |
float | double | Bidirectional |
bool | logical | Bidirectional |
None | py.NoneType | Check with isa(obj, 'py.NoneType') |
Manual conversions
| Conversion | Syntax |
|---|---|
| MATLAB to Python dict | py.dict(pyargs('key', 'value')) |
| MATLAB cell to Python list | py.list({'a', 'b', 'c'}) |
| MATLAB array to Python list | py.list(num2cell([1, 2, 3])) |
| Python list to MATLAB cell | cell(py.list(python_obj)) |
| MATLAB to Python integer | int32(365) or int64(1024) |
Problematic conversions
Some conversions require special attention:
- Python generators have no MATLAB equivalent. You must convert them to a list with
py.list(), which loads the entire result set into memory. - Complex nested structures are verbose to construct. Build inner dictionaries first, then wrap them in outer ones (see Build nested metadata).
- MATLAB numeric arrays do not convert to Python lists automatically. Use
num2cell()first:py.list(num2cell([1, 2, 3])).
Troubleshoot common issues
ModuleNotFoundError: No module named 'flywheel'
Verify that flywheel-sdk is installed in the Python environment MATLAB uses:
Unable to resolve the name py.flywheel.Client
Restart MATLAB after installing flywheel-sdk. MATLAB caches the Python module list at startup and does not detect newly installed packages.
Python version not supported
Use Python 3.8 through 3.11 for best compatibility. Python 3.12 and later have limited MATLAB support. Check your version:
If you need to switch versions, restart MATLAB and configure pyenv before any py. calls:
Type conversion errors
Use explicit types for integers:
Authentication failed
Migrate from the MATLAB SDK
The dedicated Flywheel MATLAB SDK is deprecated. This section helps you transition existing scripts to the Python SDK interop approach described in this guide.
Syntax comparison
The following table compares common operations between the old MATLAB SDK and the new Python SDK approach:
| Operation | MATLAB SDK (deprecated) | Python SDK via MATLAB |
|---|---|---|
| Create client | fw = flywheel.Flywheel(key) | fw = py.getattr(py.importlib.import_module('flywheel').Client(key), '_fw') |
| Read a property | project.label | string(project.label) |
| Update an object | project.update(...) | fw.modify_project(id, py.dict(...)) |
| Create a dictionary | struct('key', value) | py.dict(pyargs('key', value)) |
| Iterate over results | Direct for loop | cell(py.list(...)) then index with {} |
| Handle exceptions | Native MATLAB exceptions | Wrapped in MException, parse message strings |
What changes
- Import pattern: You import the Python module with
py.importlib.import_module('flywheel')instead of calling MATLAB-native constructors. - Dictionary construction: Replace MATLAB structs with
py.dict(pyargs(...))or theto_py_dicthelper. - List iteration: Convert Python generators to lists before iterating with
py.list(). - String display: Wrap Python strings in
string()when passing them tofprintfor other MATLAB functions. - Exception handling: Catch
MExceptionand inspect the message for HTTP status codes instead of catching typed exceptions.
Tip
Download flywheel_matlab_helpers.m to reduce migration effort. The helper methods closely match the ergonomics of the old MATLAB SDK for common operations like client creation, dictionary construction, and pagination.
Resources
- Download
flywheel_matlab_helpers.m— Helper utilities for common operations - Download
verify_matlab_python_setup.m— Comprehensive setup verification script - Call Python Libraries from MATLAB (MathWorks documentation)
- MATLAB Python Version Compatibility
- Flywheel Python SDK documentation