File Exchange Pick of the Week

Our best user submissions

Struct2Vars 2

Posted by Sean de Wolski,

Sean‘s pick this week is struct2vars by Matthew Eicholtz.

I was recently asked by a colleague: “How do I get all of the fields of a struct into their own variable?”. In general, although it is very doable with assignin, “poofing” a variable a bad idea because you could overwrite existing variables and the language execution engine may lose some of its efficiencies. That’s why I like Matthew’s submission. It gives you the option to get back specific fields as outputs to a function, or to avoid the best practice and poof them into the workspace with a warning if it’s overwriting something.

Here’s it in use:

clearvars
x = 1;
s = struct('a', pi, 'b', exp(1), 'x', 2);
whos
  Name      Size            Bytes  Class     Attributes

  s         1x1               552  struct              
  x         1x1                 8  double              

Now if I just want b back

b = struct2vars(s, {'b'});
whos
  Name      Size            Bytes  Class     Attributes

  b         1x1                 8  double              
  s         1x1               552  struct              
  x         1x1                 8  double              

Or if I want all of them:

struct2vars(s)
Warning: The following variables already exist
in the caller workspace and will be
overwritten:
	b
	x
 
whos
disp("x is now: " + x)
  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double              
  b         1x1                 8  double              
  s         1x1               552  struct              
  x         1x1                 8  double              

x is now: 2

You’ll see I get a warning; x is now 2, the value from the struct.

The other place you’ll often see this type of behavior is with the load command. By default, load will poof all of the variables in a MAT file into your workspace.

save('ExampleMATFile.mat')
clearvars
whos
load('ExampleMATFile.mat')
whos
  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double              
  b         1x1                 8  double              
  s         1x1               552  struct              
  x         1x1                 8  double              

Instead, I try to always get a structure back and then grab the fields I care about.

clearvars
whos
M = load('ExampleMATFile.mat')
M = 
  struct with fields:

    a: 3.1416
    b: 2.7183
    s: [1×1 struct]
    x: 2

Comments

Give it a try and let us know what you think here or leave a comment for Matthew.

Published with MATLAB® R2019a

20 views (last 30 days)  | |

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.