Code covered by the BSD License  

Highlights from
Structure Fields To Variables

4.0

4.0 | 1 rating Rate this file 20 Downloads (last 30 days) File Size: 2.08 KB File ID: #26216

Structure Fields To Variables

by Matt J

 

28 Dec 2009

Tool for importing/exporting workspace variables to or from a struct.

| Watch this File

File Information
Description

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;
etc...

Solutions based on assignin() have often been tried, but are hazardous, for reasons discussed, for example, in this thread:

http://www.mathworks.com/matlabcentral/newsreader/view_thread/244639#628695

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

Given a structure, it will print a set of assignment commands that, if executed, would assign fields of a structure to individual variables of the same name (or vice versa). The expression produced by structvars() 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.

MATLAB release MATLAB 7.9 (R2009b)
Tags for This File  
Everyone's Tags
export, field, import, pack, poofing, structure(2), unpack, variable
Tags I've Applied
Add New Tags Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (6)
09 Oct 2012 Matt J

@Geoffrey,

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.

26 Sep 2012 Geoffrey

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;

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

13 Feb 2011 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.

12 Nov 2010 Gert Kruger

Hi,

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:

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

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;

31 Dec 2009 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.

31 Dec 2009 us

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

%...
fields=fieldnames(S);
sname=inputname(idx);
if isempty(sname), sname='S'; end
nf=numel(fields);
nr=ceil(nf/nCols);
assigns=repmat({' '},nr,nCols);
if RHS
assigns(1:nf)=cellfun(@(f) [f ' = ' sname '.' f '; '],fields,'uni',0);
else
assigns(1:nf)=cellfun(@(f) [sname '.' f ' = ' f '; '],fields,'uni',0);
end
assigns=reshape(char(assigns.').',[],nr).';

just a thought...
us

Contact us