File Exchange

image thumbnail

Map fields of a structure to output variables

version (553 Bytes) by Hoi Wong
The program assigns each field of a structure into output arguments.


Updated 30 Mar 2009

No License

This is made in response to one of the comments in:

The program assigns each field of a structure into output arguments.

s =
a: 1
b: [1 2 4]
c: [5x2 double]
d: 'test'
e: {[3]}

>> [a b c d e]=struct2vars(s)

a =

b =
1 2 4

c =
0.8147 0.0975
0.9058 0.2785
0.1270 0.5469
0.9134 0.9575
0.6324 0.9649

d =

e =

A even better usage if you're trying to dump all your struct into the current workspace:

Cite As

Hoi Wong (2020). Map fields of a structure to output variables (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (3)

Note that this is very fragile code because it completely ignores the field _names_ and yet assumes that the structure fields are in a particular order. Fields can be sorted or their order changed when processing a structure, therefore the user will have to separately confirm if the field order is correct.

The only reliable way to access structure fields is to ensure that the field names are sorted into a known order, or to access the fields by name (in which case the order is irrelevant). This submission does neither of these things (it ignores the field names totally).

User Beware!

Hoi Wong

Thanks jos for the alternative approach that use deal(). The reason that I made this wrapper is to avoid using deal() and make the code self-documenting.

I wish Mathworks can consider allowing syntaxes like [a,b,c]=(struct2cell(S)){:}, then my submission has no reason to be here. :)

Jos (10584)

A superfluous combination of two basic ML commands. Simply using
C = struct2cell(S) ; [a,b,c] = deal(C{:}) ; in your code is clear enough.


Added this usage case in comments file:


Modified tag to be more sensible. I mistakenly tagged it with a URL

MATLAB Release Compatibility
Created with R2007b
Compatible with any release
Platform Compatibility
Windows macOS Linux