MATLAB: Reshape structure fields to a new array

structuresvectorization

Hi, I have a structure variable, X, which contains fields with variable size. Each field, contains x,y,z coordinates of some random number of points. For example, numel(X(1).coord) is 255 and this means that X(1).coord contains the cartesian coordinates for 85 points. X(1).coord(1) = x coordinate of the first point X(1).coord(2) = y coordinate of the first point X(1).coord(3) = z coordinate of the first point
I need to build a new matrix that has 3 columns corresponding to x,y, and z. The number of rows for this new matrix equals to the summation of numel of all fields in X divided by 3.
I did this:
Y = [];
for k=1:length(X)
Y = [Y; reshape(X(k).coord,3,numel(X(k).coord)/3)'];
end
and it works but it takes a long time to be done. I wonder if anyone knows a faster way to do this.
Thank you,

Best Answer

Here is a quick example if I understand your question correctly
X = struct('coord',{[1 2 3 3 2 1],[2 3 4]})
xcoord = [X.coord]
reshape([x.Coord]',3,[])'
HTH