File Exchange

image thumbnail


version 1.4 (293 KB) by MathWorks Internet of Things Team
Connect to MQTT brokers and publish/subscribe to topics on the broker.


Updated 29 Jul 2019

View Version History

View License

Connect to MQTT compliant brokers over TCP or websocket protocols. After connection, subscribe to topics or wildcards on the broker. Define custom functions to evaluate on receiving messages on subscribed topics. Publish messages to topics on the broker. All QoS levels supported for both publish and subscribe functions.

You can also establish a secure connection to a broker using TLS v1.2 over both TCP and websocket.

Cite As

MathWorks Internet of Things Team (2021). MQTT in MATLAB (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (56)

zain ahmad

Michele Gensicke

Hey guys,
I had some troubles to use this Package due to the missing Documentation, but managed to link to the subscribe() function a Callback Function to read the data of each received message.
This code is based on "Example 6: Subscribe to topic at QoS 2".
Below you can see my simplified code.

global connection;
global receive;

connection = mqtt(connect.destinationAdress, 'ClientID', connect.clientID, 'Port', connect.destinationPort);
subscribe(connection, subscribe.topic, 'QoS', subscribe.options.Qos, 'Callback', @receive_callback);

%% CALBACK Functions
function receive_callback(topic, msg)

% Make Variables available within Function
global receive;
global connection;

% Read Data
fprintf('Received MQTT message: "%s": "%s"\n', topic, msg);
receive.topic = topic;
receive.msg = convertStringsToChars(msg);

Cherif Dekari

Cherif Dekari

hi all,
is it mqtt in matlab supported for code generation?
i did simulink model using mqtt commands it worked fine
when i deployed the model into my android it didnt work even if i uploaded it without any error. can anyone help ?

Trendy Wijaya

Please help me! Can I connect to Google Cloud IoT by using this library. The documentation are not so clear to me and I can't open the library files to learn how they work on building MQTT communication (I need to know that because I read the documentation on Google Cloud IoT require MQTT Client to fill some parameters such as Project-ID, Region, Registry-ID, and Device-ID). Please, can anybody help me?

Trendy Wijaya

Valerio Trobiani

Thanakorn Khamvilai

Is there a Simulink version of this?

Fredrik Malmsten

I also experience the problem with string encoding making it impossible to send binary messages. Too bad :-(((


Very useful API. I would however like to second Sinan Kalafat's comment on infinite buffering. As Wolfgang Preindl is also experiencing slow-downs, this is a real problem with real-time applications or higher data rates. Could you add a function to clear buffers for both subscriptions and the connection in a future version?

Peter Gamma

Great to have MQQT in Matlab
I only miss an example for ANT+ sensors:
and for Bluetooth low energy sensors:
I m looking since a long time for a solution to stream ANT+ and Bluetooth low energy sensor data do Matlab. MQTT is the most promising solution for building this bridge.

Oshan Niroula

Sinan Kalafat

Unfortunately the subscriptions buffer the received data infinitely and there is no way to clear the data.. Since there is also no way to edit the .p files this ist almost useless for realtime purposes.

Wolfgang Preindl

Hello, i'm using the tool für real time data exchange in an HiL-environment. My Simulink model get's json-encoded values from different topics (aprox. 10 different topics) every 1 second. After a few hours of exchanging data over mqtt, the Model is slowing down. It seems like the mqtt-function ist storing all data in the internal function workspace which slows down the whole process. Stopping the Simulink model from the matlab command window results to the following error:

Warning: Error occurred while evaluating listener callback.
Operation terminated by user during tabular/vertcat (line 164)
In mqttio.DataManager/storeData
In mqttio.Mqtt/dataAvailable
In mqttio.Mqtt>@(varargin)obj.dataAvailable(varargin{:})
In hgfeval (line 62)
In javaaddlistener>cbBridge (line 52)
hgfeval(response, java(o), e.JavaEvent)
In javaaddlistener>@(o,e)cbBridge(o,e,response) (line 47)
@(o,e) cbBridge(o,e,response));
Warning: Error occurred while evaluating listener callback.

The only possibility to work around is to disconnect and reinitiate the Mqtt-connection periodically. Is there any different solution?

Khalid Rajab

I'm getting the same issue as Torbjørn Hergum. Python decodes the data correctly, so I'm certain it's a Matlab issue. I've tried as many decoding schemes as possible, such as:
unicode2native(data, 'Windows-1252')
I've tried changing the System and Matlab regions, enabling UTF-8 in Windows, etc.
Is there a solution for this problem? It's a shame, because it works well otherwise, but as is it's not usable.

Stijn Helsen

Sorry for this low rating, but I get a warning "mqtt.p is older than MATLAB file mqtt…." and errors like "Undefined function or variable 'Create'. ".
I was just trying to see if this code could be something for me, without knowing anything about MQTT. (I'm using R2018b. - Maybe the statement "Compatible with any release" is not correct?)



Abhishek Pokhrel

Torbjørn Hergum

Encoding issues: I'm transmitting an array of uint8-values from another client and want to get the numerical data in Matlab. Note that I'm transmitting "raw" integers, not strings. The received message on matlab is a string. How do I decode this properly to numerical values?

The output of double(char(message)) works well for values below 128 and above 159, which I believe is due to matlab interpreting the nubers using an encoding, for instance UTF-8. I just want access to the raw data. Please advice.

Here's an experpt of expected data (left) and obtained data (right).
125 125
126 126
127 127
128 8364
129 65533
130 8218
131 402
132 8222
133 8230
134 8224
135 8225
136 710
137 8240
138 352
139 8249
140 338
141 65533
142 381
143 65533
144 65533
145 8216
146 8217
147 8220
148 8221
149 8226
150 8211
151 8212
152 732
153 8482
154 353
155 8250
156 339
157 65533
158 382
159 376
160 160
161 161
162 162


Pretty straight forward to handle, you need to know your IP adresses (not sure if the "localhost" is recognized). Of course you need to know the port of your broker

If you need to read a topic you suscribed, make sure you pause a minimum of time before reading the topic (use pause (0.1))
I am publishing a sinus at 2Hz on my MQTT broker using an Arduino UNO, so data are consistently generated. I am using the suscribe function in MATLAB, in a while loop (combined with an animated line).
Overall, It does the job partly . It seems to keep running once the script is finished, and freeze MATLAB.

Haihong Huang

How to receive msgs in real time?

Antonio Catalano

I'm using this tool to communicate with AWS IoT, the problem is that when I try to create the MQTT object with the mqtt() function it is disconnected from the broker so I can't use the publish() function.

PC Chen

provide no p-code pleeeeease...
need to compile the program to .exe....

eman karim

Hello ,I already use publish and it is work but I have a problem with subscribe I use [ mySub = subscribe(myMQTT,'/topic/out');
readall(mySub);} it is return a comment of (There are no messages.) , why ? any advice please?

shahbaz Imran

François DELOYE

Hi, is it possible de reconnect after a disconnection with the broker without having to invoke the mqtt(broker ip) creation command so that it would not be necessary to perform again the topic subsciptions

Toby Ong

Teja Emmey

Hi. Is it possible to save the messages published into a struct variable using 'Callback' function?
Is it possible to read only certain number of old messages (for ex: only 10 latest messages). And also how to use 'msgArrivedEvent' function and 'notify' function

Patryk Kostrzewa


Hi, thanks for the client. I was able to set it up with, but have issues to subscribe to a topic. I basically used the example provided by Sven<-thanks! Error msg is "Invalid QoS value 128 returned by broker. Subscription failed." Any help greatly appreciated.

Chien-Hsi Chen

I just contacted the MathWorks Support regarding my issue and I solved the problem by following their tips.
The solution was to include every file in the "MQTT in Matlab" toolbox (see the screenshot below) in the Matlab Compiler.
The compiler may show a warning sign during packaging but the compiled program works just fine.
I hope if someone has the same problem will find it helpful.

Chien-Hsi Chen

Hello everyone,
I'm using R2018b and I also got the error of "Undefined variable "com" or class "com.mathworks.mqttclient.client.Client"". In my case is that I try to use this MQTT in a GUI made by GUIDE, but somehow it only works in normal Matlab but not in the compiled standalone version (all the .p files in MQTT in Matlab have been added manually).
I also tried to include both .jar files before compiling them, but it doesn't work and Matlab will complain that these two files have been already specified.
Does anyone maybe have a solution in detailed steps?
Thank you in advance!

Carlos Rodriguez

I can't find on the documentation how to set the Last Will and Testament (LWT) when connecting to a MQTT broker. Is this feature supported?

Alicia Lotz

Has anyone tested the toolbox with a RabbitMQ broker, does this work?

Kyle Huggins

I solved the "Undefined variable "com" or class "com.mathworks.mqttclient.client.Client" by adding the following paths to my javaclasspath (I have R2018a and it didn't work):
The second one may not be needed.

Steven Yeh

Ismail Faruqi

I installed MATLAB R2018a and still getting this error : Undefined variable "com" or class "com.mathworks.mqttclient.client.Client"


Just a small example how to use the callback ...

% callback function
function myMQTT_Callback(topic, msg)
fprintf('MQTT callback topic "%s": "%s"\n', topic, msg)

% code to connect to broker and register callback function:
myMQTT = mqtt('tcp://');
mySub = subscribe(myMQTT,'myTopic', 'QoS', 2)
% methods(mySub)
% readall(mySub)
mySub.Callback = @myMQTT_Callback;
% send a test message to check callback
publish(myMQTT, 'myTopic', 'testMessage03');

suriya pinitkan

Abdullah Shah

FYI: My issue is solved. I was using MATLAB R207b and I was getting the error shown in my previous comment. I installed MATLAB R2018a and now the tool is working properly.

Abdullah Shah

same problem, I keep getting the following error:
Undefined variable "com" or class "com.mathworks.mqttclient.client.Client".

i investigated several documentations, checked the function's source, 3rd part software documentation, the community topics, forum, others questions. unfortunately, nothing helped with this specific error.



Hi, may I know how do I define the callback function for subscribe? I have tried with function handle and function file but both gives the error 'Invalid function defined with input parameter type 'string'

Clemens Schartmüller

Hi Adarsh, can we expect support for R2015a ? Since this is a closed-source project, I sadly can't do much more than ask, but maybe you are willing to share thecode as it seems to be just an interface to a java client anyway. Please contact me, as soon as possible.

Note that this functionality is only supported in MATLAB R2017b and later. Thanks!

Hi Tobias, Thanks for the feedback. Regarding instantiating with options inputs, the mqtt function does accept the parameters you mentioned. Refer to the examples in the function help - you can access this by evaluating "help mqtt" in MATLAB or by visiting the 'Functions' tab. Thanks!

Andrey Kravchenko

Hello eveyone.

Also recenly installed the "MQTT in MATLAB" add-on.
Unfortunately, i keep getting the following error :
>> myMQTT = mqtt('tcp://')
Error: File: Mqtt.p Line: 127 Column: 0
Unbalanced or unexpected parenthesis or bracket.

It seems that the package works for everybody else, so it should be something I am doing wrong.
Could you please Support? i am using Matlab2014b
Thx and have a good weekend

Tobias Schmocker

Hi, until now, tho only useful MQTT-Client i could find to use MQTT out of the box. Works fine on R2017b.

Request: It would be nice to in instantiate the class directly without using the function mqtt(). Also it would be helpful to instantiate with separate or optional inputs like protocoll, port, qos, username, pw, client id, etc.


Hi, i recently installed MQTT in MATLAB but sadly always get this error message:
>> myMQTT = mqtt('tcp://');
Error: File: Mqtt.p Line: 127 Column: 0
Unexpected MATLAB expression.

Can you help me?

Max Person

Hi, how to get subscribe msg in real-time ?

Hello, use the read or readall functions on the subscription to retrieve the messages from the subscription. For eg: mySub = subscribe(myMQTT, 'TestTopic'); read(mySub)

Tommy Langers

Hello. Everything works fine but how can I retrieve the message from a subscription? The counter increases after a message is published, but the message itself I don't find


Does this MQTT toolbox support older version of Matlab (e.g R2016a)?

Hans Scharler

MATLAB Release Compatibility
Created with R2019a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Tags Add Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!