Structure fields to variables

Version 1.1.0.1 (2.09 KB) by Matt J
Code writing tool for importing/exporting workspace variables to or from a struct.
4.3K Downloads
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;
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 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 (2024). Structure fields to variables (https://www.mathworks.com/matlabcentral/fileexchange/26216-structure-fields-to-variables), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2009b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Structures in Help Center and MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.1.0.1

Description update

1.1.0.0

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.
Edit title

1.0.0.0