Structure fields to variables

Versión 1.1.0.1 (2.09 KB) por Matt J
Code writing tool for importing/exporting workspace variables to or from a struct.
4.2K descargas
Actualizado 29 Jul 2019

Ver licencia

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.

Citar como

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

Compatibilidad con la versión de MATLAB
Se creó con R2009b
Compatible con cualquier versión
Compatibilidad con las plataformas
Windows macOS Linux
Categorías
Más información sobre Structures en Help Center y MATLAB Answers.

Community Treasure Hunt

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

Start Hunting!
Versión Publicado Notas de la versión
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