Save Structure Fields as Separate Variables

If any of the variables in your current workspace are structure arrays, the default behavior of the save function is to store the entire structure. To store fields of a scalar structure as individual variables, use the -struct option to the save function.

For example, consider structure S:

S.a = 12.7;  S.b = {'abc', [4 5; 6 7]};  S.c = 'Hello!';

Save the entire structure to newstruct.mat with the usual syntax:

save('newstruct.mat', 'S')

The file contains the variable S:

  Name      Size                   Bytes  Class
  S         1x1                      550  struct

Alternatively, save the fields individually with the -struct option:

save('newstruct.mat', '-struct', 'S')

The file contains variables a, b, and c, but not S:

  Name      Size                   Bytes  Class
  a         1x1                        8  double
  b         1x2                      158  cell
  c         1x6                       12  char

To save only selected fields, such as a and c:

save('newstruct.mat', '-struct', 'S', 'a', 'c')
Was this topic helpful?