dynamicdivergent
dynamicdivergent

Reputation: 13

Data extraction from Matlab structs

I have a Matlab struct from which I would like to extract data.

I have written a few lines of code which does the job, but I am interested in a less cumbersome procedure using curly braces. How can I do this?

enter image description here

My code is copied below:

area = table2array(cell2table({result2.Area}))';
area = area';
centroid_coordinates = table2array(cell2table({result2.Centroid}));
centroid_coordinates = reshape(centroid_coordinates, 2, length(result2))';
bounding_box = (table2array(cell2table({result2.BoundingBox})))';
bounding_box = reshape(bounding_box, 4, length(result2))';

Upvotes: 1

Views: 81

Answers (1)

GleasonK
GleasonK

Reputation: 1022

It looks like you are trying to concatenate the output of struct indexing:

centroid_coordinates = table2array(cell2table({result2.Centroid}));
centroid_coordinates = reshape(centroid_coordinates, 2, length(result2))';

With that said perhaps this post on MATLAB Answers is relevant.

In this case, seeing that these are same-dimension items in the structs you are dealing with, you should be able to use [res.Centroid] in brackets to horizontally concatenate data, or vertcat(res.Centroid) to vertically concatenate data.

I'm using the following repro data which is a struct array with similarly shaped data to your image:

cent1 = [1,2];
cent2 = [3,4];
res(1).Centroid = cent1;
res(2).Centroid = cent2;

And reproduce your output with:

% Using method in question
withCurly = table2array(cell2table({res.Centroid}));
withCurly = reshape(withCurly, 2, length(res))';

% Using vertcat
withVert = vertcat(res.Centroid);

isequal(withCurly, withVert)
% ans = 1

References:

Upvotes: 1

Related Questions