readMessages

Read messages from rosbag

Syntax

msgs = readMessages(bag)
msgs = readMessages(bag,rows)
msgs = readMessages(___,"DataFormat","struct")

Description

example

msgs = readMessages(bag) returns data from all the messages in the BagSelection object, bag. The messages are returned in a cell array of messages.

To get a BagSelection object, use rosbag.

example

msgs = readMessages(bag,rows) returns data from messages in the rows specified by rows. The range of the rows is [1, bag.NumMessages].

example

msgs = readMessages(___,"DataFormat","struct") returns data as a cell array of structures using either set of the previous input arguments. Using structures can be significantly faster than using message objects, and custom message data can be read directly without loading message definitions using rosgenmsg.

Examples

collapse all

Read rosbag and filter by topic and time.

bagselect = rosbag('ex_multiple_topics.bag');
bagselect2 = select(bagselect,'Time',...
[bagselect.StartTime bagselect.StartTime + 1],'Topic','/odom');

Return all messages as a cell array.

allMsgs = readMessages(bagselect2);

Return the first ten messages as a cell array.

firstMsgs = readMessages(bagselect2,1:10);

Load the rosbag.

bag = rosbag('ros_turtlesim.bag');

Select a specific topic.

bSel = select(bag,'Topic','/turtle1/pose');

Read messages as a structure. Specify the DataFormat name-value pair when reading the messages. Inspect the first structure in the returned cell array of structures.

msgStructs = readMessages(bSel,'DataFormat','struct');
msgStructs{1}
ans = struct with fields:
        MessageType: 'turtlesim/Pose'
                  X: 5.5016
                  Y: 6.3965
              Theta: 4.5377
     LinearVelocity: 1
    AngularVelocity: 0

Extract the xy points from the messages and plot the robot trajectory.

Use cellfun to extract all the X and Y fields from the structure. These fields represent the xy positions of the robot during the rosbag recording.

xPoints = cellfun(@(m) double(m.X),msgStructs);
yPoints = cellfun(@(m) double(m.Y),msgStructs);
plot(xPoints,yPoints)

Input Arguments

collapse all

All the messages contained within a rosbag, specified as a BagSelection object.

Rows of BagSelection object, specified as n-element vector, where n is the number of rows to retrieve messages from. Each entry in the vector corresponds to a numbered message in the bag. The range of the rows is [1, bag.NumMessage].

Output Arguments

collapse all

ROS message data, returned as an object, cell array of message objects, or cell array of structures. Data comes from the BagSelection object created using rosbag. You must specify 'DataFormat','struct' in the function to get messages as a cell array of structures. Using structures can be significantly faster than using message objects, and custom message data can be read directly without loading message definitions using rosgenmsg.

Introduced in R2015a