File Exchange

image thumbnail

Structure fields to variables

version (2.09 KB) by Matt J
Code writing tool for importing/exporting workspace variables to or from a struct.


Updated 29 Jul 2019

View License

Structures are a convenient way of carrying around many variables as a single object and of passing those variables to a function packed in a single argument.
Once a structure has been passed to a function, however, many users (according to various Newsgroup posts) find it tiresome to have to access its fields repeatedly through dot-indexing notation and have sought automated ways to take a structure and assign all of its fields to separate variables, as in
a = myStruct.a;
b = myStruct.b;
c = myStruct.c;
Solutions based on assignin() have often been tried, but are hazardous, for reasons discussed, for example, in this thread:

The structvars() tool in this FEX submission does something virtually as good and far safer.

Given a structure, it will print the lines of code needed to assign structure fields to separate variables (or the reverse). The lines of code can be conveniently copy/pasted from the command window to the file editor at the location in the file where the variables need to be unpacked.

Examples: Given structure myStruct, with fields a,b,c, & d

(1) structvars(myStruct) %assign fields to variables

ans =

a = myStruct.a;
b = myStruct.b;
c = myStruct.c;
d = myStruct.d;

(2) structvars(3,myStruct) %split the last result across 3 columns

ans =

a = myStruct.a; c = myStruct.c; d = myStruct.d;
b = myStruct.b;

(3) structvars(3,myStruct,0) %assign variables to fields

ans =

myStruct.a = a; myStruct.c = c; myStruct.d = d;
myStruct.b = b;

The commands can obviously be regenerated if you add/remove structure fields later on. On the other hand, the effort of just making these incremental edits manually is typically minimal.

Cite As

Matt J (2020). Structure fields to variables (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (15)

tim coon

Hette de Vlieger

Hette de Vlieger

@ Matt J
Thanks for your swift reply

Matt J

@Hette de Vlieger,
structvars is not meant to execute the assignments for you (that would be bad, as you have noted). Instead, you are meant to copy/paste the commands to the place in your code where they are needed and let them be executed as normal lines of code.

Hette de Vlieger

When I'd like to actually execute the command, I have to use eval, which everyone discourages. Is there an alternative?

amin ya


Stephen Cobeldick

A neat concept elegantly executed. Tidy code, clear explanations and examples. Does exactly what it says on the box!

Worth mentioning is that accessing the data directly from the structure is also an alternative option.

Dan Boschen

The following change in the "assigns=" line allows for matrix extraction (using x = [S.x] instead of x = S.x):

assigns= cellfun(@(f) [f ' = [' sname '.' f ']; '],fields,'uniformoutput',0);

Matt J


Not a good idea. Using EVAL has the same poofing hazards as ASSIGNIN, hazards which the tool expressly tries to avoid. Using a script also forces you to gamble that variables named 'assign_field', etc... don't already exist in your workspace.


This is a very static solution. An alternative is to use a script to evaluate the structure fields. For example:

%File name assign.m
%This script requires that you have a structure called assignments.
%This script takes the structure: assignments.fieldname
% and writes the variable: fieldname = assignments.fieldname;
%A typical call looks like >> assignments = variablestruct; assign;

for assign_i=1:1:length(assign_field)
eval([ assign_field{assign_i} '=' ...,
'assignments.(assign_field{assign_i});' ]);
clear assign_field assign_i assignments

Matt J

@Gert, Didn't notice your message sooner. I can see the variable scope alternator idea as useful on occasion, but I think it would be controversial in terms of code readability.

Gert Kruger


wouldn't it be useful if the variable scope could be temporarily switched programmatically to that of the structure and switching it programmatically back off (or automatically if the scope of the structure is no longer visible such as when exiting a function) ? e.g. treating the structure as a namespace:

>> = 1;
>> bar = 2;
>> using foo;
>> bar = 3
bar =
>>notusing foo;
bar =
>> =

Ofcourse, if there was no variable defined before the scope of the structure was entered, then trying to use the variable after exiting the scope, would simply give the error:

??? Undefined function or variable 'bar'.

Just remembering, in Pascal there is the 'with' keyword, which does the same thing.

I'm strugling with this very problem as described in description: Need to use variables in function body, which are passed on inside a structure. Don't wont to modify the code to use the structure variables, i.e. bar.a instead of a, so the variables have to be 'unpacked' by reassingning it before used in function:
a = bar.a;

Matt J

Hi urs, Thanks for the feedback. I need the loop to prevent large spacings between columns that can result when the fieldnames are of very different lengths. I also need the extra variables you mention to ensure that there will be no empty columns (a semantic point mainly). If you try your suggested code with nCols=3 and

myStruct.a=1; myStruct.b=4; myStruct.cccccccc=7; myStruct.dddddddd=9;

you will see what I mean.


an interesting decoder...
however, the code could be simplified as shown below
in particular, there is no need for
- various temporary vars
- a loop

if isempty(sname), sname='S'; end
assigns=repmat({' '},nr,nCols);
if RHS
assigns(1:nf)=cellfun(@(f) [f ' = ' sname '.' f '; '],fields,'uni',0);
assigns(1:nf)=cellfun(@(f) [sname '.' f ' = ' f '; '],fields,'uni',0);

just a thought...


Description update

Edit title

When called with no output arguments, structvars now simply prints the assignment statements to the screen. This is for compatibility with new display conventions in R2017.

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