bio_img_deep-learning

Artificial Intelligence

Apply machine learning and deep learning

pip & uv in MATLAB Online

MATLAB Online is a very convenient platform for working with MATLAB and Python® together. And I am not only saying this because I was part of the MATLAB Online product team until fairly recently (ok, now you know my biases). Even before joining the online product team, I was leveraging this online environment to deliver workshops at scale. The main reason why I adopted this approach is because I always used to waste up to 30 min upfront on questions like:
“Which set of Python packages do I need to make this script run on my machine?”
So, I decided to document how to build reproducible MATLAB and Python environments to facilitate the on-boarding of users of both languages. Another motivation early on was to enable the example of my book on MATLAB with Python to open in MATLAB Online.
Two tools stand out for this purpose: pip, the classic Python package manager, and uv, a modern, high-speed alternative. uv is the new cool kid in town, and I have finally invested the time to play around with it and compared it with pip. I thought you might be interested in my learnings. Buckle up, let’s install some python packages!

TL;DR

  • MATLAB Online ships with a version of Python you can use right away. You can retrieve a package manager like pip to install packages and call them from MATLAB.
  • For speed and more advanced development workflows, install uv, add it to PATH for your MATLAB session, then use uv to manage packages and virtual environments.
  • Avoid putting virtual environments under /MATLAB Drive (symlinks are not supported there). Create them under your home directory instead, more precisely /home/matlab.
  • Each ! shell call in MATLAB is a fresh non-interactive shell; use setenv inside MATLAB to persist environment changes like PATH.
 

Get started with the MATLAB Online sandbox

You can access MATLAB Online from the following shortcut in your web browser:
https://matlab.new
It will take you to MATLAB Home, where you can Open MATLAB Online or pick up from files you have been editing in previous sessions:
 
In MATLAB Online you get an ephemeral machine, on which you can experiment freely, simply because it is not your local machine, and you will be served with a new one when you quit your session with the command exit. So feel free to install things to try out new libraries, as long as you don’t persist them in your MATLAB Drive.
Something that you might already know from working on your Windows® desktop machine; you can run OS commands with the exclamation mark operator ! (also called bang). One thing to pay attention to is that each call spawns a new shell, so exported variables in one ! call don’t persist to the next. Use the MATLAB function setenv to make environment variables (like PATH) stick for your session. You might be familiar with this command to pass your API key to call LLMs with MATLAB.
Now that you are equipped with the basic concepts, let’s dive into the world of Python dependencies.
 

Option 1 – Plain old pip

pip stands for Python installs packages. It is a recursive acronym (like GNU is Not Unix). It is the default Python package manager, that ships with Python on Windows. On Linux, it typically needs to be retrieved separately, like venv (the default virtual environment manager). Here is a quick method to fetch and install pip with a simple script:
% Retrieve pip from PyPA
websave('/tmp/get-pip.py','https://bootstrap.pypa.io/get-pip.py');
% Install pip
system('python /tmp/get-pip.py');
Install Numpy (in quiet mode with flag -q) and time it
system('time python -m pip install -q numpy');
real   0m3.125s
user   0m2.041s
sys    0m0.284s

This first test is too simple, let’s take something heavier like PyTorch®:
tic; system('python -m pip install -q torch'); toc
Elapsed time is 120.127409 seconds.
As you can see it takes around 2 minutes to install PyTorch (with its dependencies).
Now, let’s try uv 🚀
 

Option 2 – uv: faster installs, nicer tooling

uv is a single, blazing-fast tool that can replace pip, pipx, virtualenv, parts of poetry/pdm, and more. It’s 10–100× faster than pip for installs, and includes uvx to run tools without installing them globally. Some might say it is “yet another Python package manager”. They wouldn’t be wrong. But I got curious about the hype, and decided to test it myself. And I have to say that I quite appreciate it, even just for the speed up.

Install uv and put it on the system PATH

Simply follow the instructions from the uv documentation:
!curl -LsSf https://astral.sh/uv/install.sh | sh
curl: /MATLAB/bin/glnxa64/libcurl.so.4: no version information available (required by curl)
downloading uv 0.8.15 x86_64-unknown-linux-gnu
curl: /MATLAB/bin/glnxa64/libcurl.so.4: no version information available (required by curl)
no checksums to verify
installing to /home/matlab/.local/bin
uv
uvx
everything's installed!

To add $HOME/.local/bin to your PATH, either restart your shell or run:
 
source $HOME/.local/bin/env (sh, bash, zsh)
source $HOME/.local/bin/env.fish (fish)
Unlike what is suggested, you will need another method to add $HOME/.local/bin to your PATH so that it persists in your !/system calls:
% 1) Point PATH to where uv was installed
setenv('PATH', getenv('HOME')+"/.local/bin:"+getenv('PATH'));
% Sanity checks
system('which uv');         % should print ~/.local/bin/uv
/home/matlab/.local/bin/uv
Why setenv? Each ! call is a fresh shell; source ~/.local/bin/env doesn’t persist across ! calls. setenv updates the environment for subsequent !/system calls.
system('uv --version');
uv 0.8.15
system('uvx --version');
uvx 0.8.15
system('python --version');
Python 3.10.17

Create and activate a virtual environment

Before installing packages, it is a good practice in Python to use a virtual environment (venv). This acts a little bit like virtualization with a docker container, but takes up less space as it works at the language level, not the operating system level. Setting the --clear flag ensures reproducibility to reset an already existing environment called env that might exist in the same location.
% 2) Create a venv OUTSIDE MATLAB Drive (symlinks are fine here)
system('uv venv --clear /home/matlab/venvs/env');
Using CPython 3.10.17 interpreter at: /usr/bin/python
Creating virtual environment at: /home/matlab/venvs/env
Activate with: source /home/matlab/venvs/env/bin/activate
% 3) "Activate" it for this MATLAB session
setenv('VIRTUAL_ENV','/home/matlab/venvs/env');
setenv('PATH', ['/home/matlab/venvs/env/bin:' getenv('PATH')]);
Once again, the “activation” of the environment won’t be done through the source command, but by adding two important variables (VIRTUAL_ENV and PATH) to the OS environment.
/!\ by default uv won’t be found
>> !uv pip install numpy
error: Broken virtual environment `/MATLAB Drive/.venv`: `pyvenv.cfg` is missing
There is a hiccup if you try to store your python environment in your MATLAB Drive. MATLAB Drive is the default file storage mechanism for MATLAB Online. It shows up as /MATLAB Drive, where your drive is mounted on the machine that is attributed to your MATLAB Online session. This mount does not create symbolic links (and symlinks may fail), which matters for virtual environments (venvs).
Instead, I would recommend you use other ephemeral locations specific to the duration of your MATLAB Online session, like /home/matlab for venvs (this directory is stored as the variable $HOME in MATLAB Online).
 

Install packages with uv

Let’s finally install PyTorch with uv.
tic;
system('uv pip install -q torch');
toc
Elapsed time is 35.361351 seconds.
As you can see, it brings a significant speedup. Now that I ‘ve tried it, I’m ready to store an install and setup script for uv in my MATLAB Drive, so I can just add uv in front of my pip install commands from now on!
 

Try it with an example: Call PyTorch from MATLAB Online

Let's use the basic quickstart tutorial from the PyTorch documentation. This is a classification example with a model that has been trained on 60000 28x28 grey pictures of clothes, called the Fashion MNIST dataset.
First connect MATLAB Online to your newly created Python environment from the command window. I recommend setting the execution mode to “OutOfProcess”. This way you can terminate the environment connection without having to restart MATLAB Online. Also make sure that the python Executable field points to the Python in your venv.
>> pyenv("ExecutionMode","OutOfProcess")
ans = 

  PythonEnvironment with properties:

          Version: "3.10"
       Executable: "/home/matlab/venvs/env/bin/python3"
          Library: "libpython3.10.so.1.0"
             Home: "/home/matlab/venvs/env"
           Status: NotLoaded
    ExecutionMode: OutOfProcess
  Once the connection with Python is established, you can retrieve the : https://drive.mathworks.com/sharing/3ebb886a-fd21-4bc8-ba94-e0ad5912c309   Next, you can use a to simply paste Python code that will be wrapped under the hood with the pyrun function.
If you unfold the > Show code you will get the following generated code.
% Python code input
pycode = [...
"import torch",...
"from fashion_model import NeuralNetwork",...
"model = NeuralNetwork().to('cpu')",...
"model.load_state_dict(torch.load(""model.pth"", map_location=torch.device('cpu')))"...
];

try
    [model] = pyrun(pycode, ...
         [ "model" ])
catch ME6
    % Clear temporary variables from workspace and from Python
    clear pycode;
    rethrow(ME6)
end
model =

  Python NeuralNetwork with properties:

    training: 1

    NeuralNetwork(
      (flatten): Flatten(start_dim=1, end_dim=-1)
      (linear_relu_stack): Sequential(
        (0): Linear(in_features=784, out_features=128, bias=True)
        (1): ReLU()
        (2): Linear(in_features=128, out_features=10, bias=True)
      )

    )
 
% Clear temporary variables from workspace and from Python
clear pycode;
test_data = pyrunfile('fashion_dataset.py','test_data')
test_data =

  Python FashionMNIST with properties:


        class_to_idx: [1×1 py.dict]
    processed_folder: [1×27 py.str]
          raw_folder: [1×21 py.str]
           test_data: [1×1 py.torch.Tensor]
         test_labels: [1×1 py.torch.Tensor]
          train_data: [1×1 py.torch.Tensor]
        train_labels: [1×1 py.torch.Tensor]
           transform: [1×1 py.torchvision.transforms.transforms.ToTensor]
                data: [1×1 py.torch.Tensor]
             targets: [1×1 py.torch.Tensor]
               train: 0
    target_transform: [1×1 py.NoneType]
          transforms: [1×1 py.torchvision.datasets.vision.StandardTransform]
                root: [1×4 py.str]


    Dataset FashionMNIST
        Number of datapoints: 10000
        Root location: data
        Split: Test
        StandardTransform
    Transform: ToTensor()

x = pyrun('x = test_data[0][0]','x',test_data=test_data)
x =

  Python Tensor with properties:
           ...

    tensor([[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
              0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
              0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
              0.0000, 0.0000, 0.0000, 0.0000], ...



clothes = [
    "T-shirt/top",...
    "Trouser",...
    "Pullover",...
    "Dress",...
    "Coat",...
    "Sandal",...
    "Shirt",...
    "Sneaker",...
    "Bag",...
    "Ankle boot",
]
 
clothes = 1×10 string

"T-shirt/top""Trouser"    "Pullover"   "Dress"      "Coat"       "Sandal"   ⋯

pred = model(x)
pred =

  Python Tensor with properties:

             ...

    tensor([[ -8.7973,  -9.9736, -10.1721, -11.8425,  -9.1262,  -2.4357,  -9.7069,
               0.0156,  -6.0885,   4.0667]], grad_fn=<AddmmBackward0>)
i = py.int(argmax(pred))
i =

  Python int with properties:


    denominator: [1×1 py.int]
           imag: [1×1 py.int]
      numerator: [1×1 py.int]
           real: [1×1 py.int]


    9
pred_label = clothes(i+1)
pred_label = "Ankle boot"
X_m = double(x.numpy());

size(X_m)
ans = 1×3

     1    28    28
imshow(squeeze(X_m(1, :, :)))

title(pred_label)
   
This “hello world” example of deep learning shows that you can call a PyTorch model from MATLAB Online.
 

Wrap-up

  • MATLAB Online + Python is not only possible—it’s practical. Start with pip for simplicity, switch to uv when speed and tighter management of your environments matter.
  • Keep your virtual environments under $HOME, not /MATLAB Drive, just for the duration of your session.
  • Use setenv for session-persistent PATH changes inside MATLAB.
  That’s it for today, thanks for following along 📦  
|
  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.