Return all values of a struct parameter within a cell array.

조회 수: 11 (최근 30일)
Gregory Beale
Gregory Beale 2021년 2월 3일
댓글: Matt J 2021년 2월 4일
I have a cell array (21x1) with multiple embedded structs such that the information I want is found at myCell{1,1}.Pose.Position.X.(value_here). Each cell array has identical structure. Is there a way to return the all X values in this 21x1 cell array without having to use a for loop? I want to use the ':' operator somewhere but can't figure it out (I'm no matlab expert either, so could be something obvious I'm missing or maybe it's just not possible).
  댓글 수: 3
Gregory Beale
Gregory Beale 2021년 2월 4일
편집: Gregory Beale 2021년 2월 4일
I’m reading in ROS messages from .bag files using the ROS toolbox. I use the ‘readmessages’ function and they are automatically put into cell arrays.
Matt J
Matt J 2021년 2월 4일
Is there a way to return the all X values in this 21x1 cell array without having to use a for loop?
Is there a reason you think you need to avoid for-loops when your array is so small? I doubt you will notice differences in speed between a for-loop and any of the Answers below.

댓글을 달려면 로그인하십시오.

답변 (2개)

Matt J
Matt J 2021년 2월 4일
tmp=[myCell{:}];
tmp=[tmp.Pose];
tmp=[tmp.Position];
X=[tmp.X];

Cam Salzberger
Cam Salzberger 2021년 2월 4일
Hello Gregory,
Matt J's way works, by creating multiple struct arrays, working your way down the nested fields. It's functional, but not very fast, since you are creating new arrays each time, unless you are going to be accessing all of the data at that level.
On the other hand, this is kind perfect for cellfun:
x = cellfun(@(c) c.Pose.Position.X, myCell);
This works great when the field you are accessing always contains scalar data. If it contains vector data, or text, you'd have to use 'UniformOutput',false, which would output another cell array.
If you are concerned about performance, it may be faster to create a local function to handle the access of all data within a deeply-nested message at once. Something like:
[x, y, z] = cellfun(@extractPose, myCell);
function [x, y, z] = extractPose(msg)
% Extract pose coordinates from geometry_msgs/PoseStamped message
pos = msg.Pose.Position;
x = pos.X;
y = pos.Y;
z = pos.Z;
end
This is the case for deeply-nested message objects. I'm not as certain if it holds true for message structs.
-Cam

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by