Cell array as structure field - why is retrieving contents so difficult?

Hi, im working with Matlab R2012a. I have a structure with a cell array as one of the fields. I would like to simply assign the entire cell array to a variable in the workspace in one line, however this is apparently impossible:
When i try "var=struct.field" it only assigns the first cell of "field" to "var".
When i try "var=struct.field{:}" it throws up an error, apparently any indexing after a field specifier is an error.
When i try "[var{1},var{2},var{3},var{4},var{5}]=struct.field" it assigns all 5 cells of "field" to each cell of "var", leaving me with an unnecessarily large and nested cell array:
[ie "var{1}={field{1},field{2},...,field{5}}, var{2}={field{1},field{2},...,field{5}}, ..., var{5}={field{1},field{2},...,field{5}}". This behaviour seems very odd and for some ungodly reason scales homogenously between "var" and "field", so "[var{1},var{2}]=struct.field" results in "var{1}={field{1},field{2}}, var{2}={field{1},field{2}}"].
I have also tried using the "getfield" command in every way i can think of, but this invariably throws up an error too. The ONLY way i have found to do this is to first do "[a,b,c,d,e]=struct.field" and then assemble the cell array seperately [ie "var={a,b,c,d,e}"]. This seems like a remarkably inelegant way of doing it considering the usual silky smooth programming functionality of Matlab. Is there a way to do this in one line, and i'm just being obtuse? I appreciate that this is a very specific and pernickety little thing, but it's just bugging me.

3 Comments

Your posting would be easier to read if you broke it up into paragraphs and isolated the code.
Apologies, i did try, but it didnt seem to work. I tried various newlines and none showed up on the preview.
there we go i've at least managed to get it paragraphed.

Sign in to comment.

 Accepted Answer

[var{1:length(YourStruct)}] = deal(YourStruct.field);
or
var = {YourStruct.field};

1 Comment

face palm it really is that easy. I guess even matlab isn't entirely free of cyptic-ness yet :) Many thanks Walter, apologies for spamming the boards with such trivialities.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!