Structure fields to variables

Versione 1.1.0.1 (2,09 KB) da Matt J
Code writing tool for importing/exporting workspace variables to or from a struct.
4,2K download
Aggiornato 29 lug 2019

Visualizza la licenza

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.

Cita come

Matt J (2024). Structure fields to variables (https://www.mathworks.com/matlabcentral/fileexchange/26216-structure-fields-to-variables), MATLAB Central File Exchange. Recuperato .

Compatibilità della release di MATLAB
Creato con R2009b
Compatibile con qualsiasi release
Compatibilità della piattaforma
Windows macOS Linux
Categorie
Scopri di più su Structures in Help Center e MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Versione Pubblicato Note della release
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