Tutorials

MQTT in MATLAB and Simulink: Subscribe, Publish and Analyze Data

Use MQTT in MATLAB with mqttclient from Industrial Communication Toolbox: connect, subscribe, publish, read messages into a timetable and analyze live data.

Updated · 8 min read

MQTT in MATLAB and Simulink: Subscribe, Publish and Analyze Data

MATLAB can talk to any MQTT broker with one function: mqttclient, part of Industrial Communication Toolbox. It connects, subscribes, publishes and buffers incoming messages in a timetable, which is exactly the shape MATLAB wants for analysis. This tutorial walks through a complete workflow: connect to a broker, collect sensor data, publish commands, analyze the result, and what to do in Simulink or when you do not have the toolbox.

What you need

  • MATLAB with Industrial Communication Toolbox (the former OPC Toolbox, which gained MQTT support in R2022a). Check with ver or which mqttclient.
  • A broker. The examples use the shared test endpoint broker.connectmq.com (TCP 1883, TLS 8883).
  • A second client to watch traffic, such as the online MQTT client or mosquitto_sub.

Use a unique topic prefix such as testmqtt/matlab/<your-name>/... so your test data does not mix with other users of a shared broker.

Connect to the broker

mqttclient takes the broker address with a scheme (tcp://, ssl://, ws:// or wss://) and options as name-value arguments:

connect.m
client = mqttclient("tcp://broker.connectmq.com", ...
    Port=1883, ...
    ClientID="matlab-" + string(randi(1e6)), ...
    KeepAliveDuration=seconds(60));

client.Connected   % true when the CONNECT was accepted

For an authenticated broker, add the credentials from environment variables instead of hard-coding them in a script you might share:

connect_auth.m
client = mqttclient("ssl://broker.connectmq.com", ...
    Port=8883, ...
    Username=getenv("MQTT_USER"), ...
    Password=getenv("MQTT_PASS"), ...
    CARootCertificate="ca.pem");

CARootCertificate points to a PEM file with the CA that signed the broker's certificate. For mutual TLS add ClientCertificate and ClientKey. If the connection fails, verify the certificate chain outside MATLAB first; see testing an MQTT TLS connection.

Subscribe: callback or buffer

There are two ways to receive messages, and choosing the right one matters more in MATLAB than in other languages.

Buffered mode (no callback) stores incoming messages inside the client object. You pull them later with read. This is ideal for data analysis because you get a timetable in one call:

buffer.m
subscribe(client, "testmqtt/matlab/sensors/+/temp", QualityOfService=1);
pause(30)                        % collect for 30 seconds
msgs = read(client);             % timetable: Time, Topic, Data
head(msgs)

Callback mode runs a function for every message. Use it for live reactions, like updating a plot or triggering an alarm:

live.m
subscribe(client, "testmqtt/matlab/alarms/#", Callback=@onAlarm);

function onAlarm(topic, data)
    fprintf("%s  %s -> %s\n", string(datetime("now")), topic, data);
end

The callback receives the topic and the payload. Keep it short: it runs on the MATLAB thread, so heavy computation inside the callback delays every following message. Topic filters follow normal MQTT rules (+ matches one level, # the rest); test a filter against real topics with the topic matcher before you wonder why nothing arrives.

Other useful functions: peek(client) shows the newest buffered messages without removing them, unsubscribe(client, topic) stops a subscription, flush(client) empties the buffer, and client.Subscriptions lists what is active.

Publish from MATLAB

write sends a message. Encode structured data with jsonencode so any other client can parse it:

simulate_sensors.m
for k = 1:60
    for id = ["s1" "s2" "s3"]
        msg = jsonencode(struct( ...
            "value", 20 + 2*randn(), ...
            "ts", posixtime(datetime("now"))));
        write(client, "testmqtt/matlab/sensors/" + id + "/temp", msg, ...
            QualityOfService=1);
    end
    pause(1)
end

Pass Retain=true for state that late subscribers should see immediately, such as a setpoint or a model version. QoS 1 guarantees at-least-once delivery between MATLAB and the broker; see MQTT QoS levels for the trade-offs.

Watch the result from a second window: open the online client, subscribe to testmqtt/matlab/#, and you should see three topics updating every second.

Watch your MATLAB messages in the browser

Analyze the data

This is where MATLAB shines. read returns a timetable whose Data variable holds payloads as strings. Decode them, build a clean timetable and resample:

analyze.m
msgs = read(client);

value = arrayfun(@(s) getfield(jsondecode(s), "value"), msgs.Data);
sensor = extractBetween(msgs.Topic, "sensors/", "/temp");

tt = timetable(msgs.Time, categorical(sensor), value, ...
    VariableNames=["Sensor" "Value"]);

% One-minute average per sensor
perMinute = groupsummary(timetable2table(tt), ...
    ["Sensor" "Time"], {"none" "minute"}, "mean", "Value");

% Smooth and plot
figure; hold on
for s = categories(tt.Sensor)'
    t = tt(tt.Sensor == s{1}, :);
    plot(t.Time, smoothdata(t.Value, "movmean", 10), DisplayName=s{1});
end
legend; ylabel("Temperature (°C)"); title("MQTT sensor data")

A few practical notes:

  • msgs.Time is the time the message arrived at MATLAB, not when the device measured it. If timing matters, include a timestamp in the payload (as above) and use that instead. Clock skew between devices is a classic source of confusing plots.
  • Decoding fails on malformed JSON. Wrap jsondecode in try/catch for real device data, or filter with startsWith(msgs.Data, "{") first.
  • The buffer grows while you are not reading. For long runs, call read periodically and append to a file with writetimetable, or store data on disk from the start (see logging MQTT to CSV for the same pattern in Python).

Payload design makes this step easy or painful. Short, flat JSON with explicit units and timestamps is the friendliest format for analysis; see payload design best practices.

For models that should exchange signals with real devices, recent releases of Industrial Communication Toolbox provide MQTT Publish and MQTT Subscribe blocks, and hardware support packages (for example the one for Raspberry Pi) include their own MQTT blocks for code generation on the target. The exact block set and options depend on your release, so check the block library in your installation.

Typical uses:

  • Hardware-in-the-loop: a plant model in Simulink subscribes to actuator commands from a real controller and publishes simulated sensor values.
  • Digital twin dashboards: a running model publishes its states so that a web dashboard can display them.
  • Parameter tuning: a subscriber block receives setpoints published from MATLAB or a browser while the simulation runs.

Simulink runs as fast as it can by default. When you connect it to MQTT, enable simulation pacing (or use a real-time target) so the model does not flood the broker with thousands of messages per second of simulated time.

Without the toolbox: use Python from MATLAB

If Industrial Communication Toolbox is not available, MATLAB's Python interface can call paho-mqtt directly. Install it in the Python environment that pyenv reports (pip install paho-mqtt), then use paho's blocking helpers:

paho_from_matlab.m
% Publish one message
py.paho.mqtt.publish.single("testmqtt/matlab/cmd", "start", ...
    pyargs("hostname", "broker.connectmq.com", "port", int32(1883), "qos", int32(1)));

% Wait for 5 messages and return them
msgs = py.paho.mqtt.subscribe.simple("testmqtt/matlab/sensors/#", ...
    pyargs("hostname", "broker.connectmq.com", "msg_count", int32(5)));

for k = 1:length(msgs)
    m = msgs{k};
    fprintf("%s: %s\n", string(m.topic), string(m.payload.decode()));
end

This is fine for scripts and batch jobs. For continuous streams, run a small Python or Node.js bridge outside MATLAB that writes to a file or database and analyze that with MATLAB; it survives MATLAB restarts and keeps your analysis code simple.

Troubleshooting

SymptomLikely causeFix
mqttclient is undefinedToolbox not installed or not licensedInstall Industrial Communication Toolbox or use the Python fallback
Connection error right awayWrong scheme/port pair (ssl:// on 1883, tcp:// on 8883)Match tcp→1883, ssl→8883, ws→8083, wss→8084
Connects, then disconnects repeatedlyDuplicate client IDUse a random ClientID per session
Subscribed but read returns nothingTopic filter does not match, or publisher on another brokerTest the filter with the online client and the topic matcher
Authentication refusedWrong credentials, or the user lacks ACL permissionVerify with mosquitto_sub -d, check broker ACLs

Wrap-up

mqttclient turns MATLAB into a first-class MQTT client: connect with tcp:// or ssl://, subscribe in buffered mode for analysis or with a callback for live reactions, publish JSON with write, and turn messages into timetables with read. Validate topics and payloads with a second client before writing analysis code, include device timestamps in payloads, and move long-running collection to a file or database once the experiment becomes a pipeline. For industrial architectures around this, see MQTT in IIoT and Industry 4.0.

Frequently asked questions

Which MATLAB toolbox includes MQTT?

The mqttclient function ships with Industrial Communication Toolbox (formerly OPC Toolbox). Without that toolbox you can call the Python paho-mqtt library from MATLAB through the py interface, or use a small external bridge.

How do I read MQTT messages into a MATLAB timetable?

Subscribe without a callback and call read(client). It returns all buffered messages as a timetable with the arrival time, the topic and the payload, which you can decode with jsondecode and resample with retime.

Can MATLAB connect to an MQTT broker over TLS?

Yes. Use an ssl:// broker address with port 8883 and pass the CA certificate file through the CARootCertificate option. For mutual TLS, also pass ClientCertificate and ClientKey.