# Converting variables to structures, and vice versa

Jiro's pick this week is v2struct by Adi Navve.

I have a special liking for convenience/utility functions, because they make my life easier. For example, here's something that many users have probably learned to do early on:

  plot(x, y, 'ro:')

Did you know that plot is a high-level, convenience function for a much more flexible, low-level function line?

  line(x, y, 'Color', 'r', 'Marker', 'o', 'LineStyle', ':')

Adi's v2struct is a function that makes converting between structures and individual variables easier.

Variables to a Structure

Suppose you have a bunch of variables that you want to combine into a single structure:

aString = 'August 5, 2011';
aScalar = pi;
aVector = rand(1, 5);

v2struct automatically uses the names of the variables as the field names:

s = v2struct(aString, aScalar, aVector)
s =
aString: 'August 5, 2011'
aScalar: 3.1416
aVector: [0.8407 0.2543 0.8143 0.2435 0.9293]


Structure to Variables

The function works the other way also. Suppose you have a structure like this:

s2 = struct('var1', 1, 'var2', [1 2 3], 'var3', 'hello')
s2 =
var1: 1
var2: [1 2 3]
var3: 'hello'


You can create variables from the fields of the structure:

v2struct(s2)
whos var*
  Name      Size            Bytes  Class     Attributes

var1      1x1                 8  double
var2      1x3                24  double
var3      1x5                10  char



In addition to these basic uses, v2struct provides advanced functionalities, such as

• creating structures with field names different from variable names
• updating fields of an existing structure
• extracting only specific fields of a structure
• extracting fields with a different variable name

What I also like about Adi's function is that there is a very extensive help section with lots of examples. I can see he has put in a lot of effort in making this easy to use.