Converting structs within cells to cells

1 view (last 30 days)
I have a 20x1 cell (X) where each cell element contains a 16x1 struct. There is only one field throughout any of the structs ('Coordinates', a matrix with 3 columns but varying number of rows). I would like to convert this into a 20x16 cell, where each cell element is the Coordinate matrix. I've tried many different things and nothing gives me quite what I want.
1. squeeze(struct2cell(X{1})) gives me a 16x1 cell where each cell containts a Coordinate matrix. I tried looping through the contents all 20 rows of cell X in hopes of horizontally concatenating the output, and no luck. This also doesn't work:
A = cell(16,20)
for i = 1:20
[A{:,i}] = squeeze(struct2cell(X{i}));
end
The resulting error: Error using squeeze Too many output arguments.
2. Also tried the following:
B = cell2mat(X);
C = cell(16,20);
[C{:}] = B.Coordinates;
This actually did give me a 16x20 cell, but the contents aren't right! I checked the dimensions of the matrices within the cells against the dimensions in the original structs within cells (Variable X), and they don't match!
If anyone could explain what I am doing wrong here, I would really appreciate it!

Accepted Answer

Layla
Layla on 3 May 2012
Mistake found. Method #2 would work as long as my preallocated cell C was the right size. It should've been cell(20,16). Then transposing the output of [C{:}] = B.Coordinates gives me the answer I need.
Thank you again for your help Walter. This isn't the first question of mine you've helped me on!

More Answers (1)

Walter Roberson
Walter Roberson on 3 May 2012
cellfun(@(C) horzcat(C.coordinates), X)
  1 Comment
Layla
Layla on 3 May 2012
No luck there either:
Error using horzcat
CAT arguments dimensions are not consistent.
Error in @(C)horzcat(C.ClusterCoordinates)

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!