Search code examples
matlabstructurefield

How to Save 1 Structure Field Inside another Saved Structure with its Fields


While there are similar postings, I have not seen this scenario for saving a structure within a structure.

Here is my goal: to save one structure field inside an already defined, saved structure.

My fruit structure has already been saved in its folder (.mat) and inside it is:

fruit = 

  struct with fields:

  apples: 5
  oranges: 2
  pineapple: 1

My goal is to add one grapes field to an already saved structure.

fruit = 

      struct with fields:

     apples: 5
     oranges: 2
     pineapple: 1

     grapes: 13

Here is my code:

clc;
clear all;

fruit.apples = 5
fruit.oranges = 2
fruit.pineapple = 1

save('fruit.mat', '-struct', 'fruit')
clear all;
load('fruit.mat')
fruit.grapes = 13
save('fruit.mat', '-struct', 'fruit')

OUTPUT: Only the grapes field is saved without the other fields: apples, oranges, and pineapple.

GOAL OUTPUT: How do I save all 4 fields in the same structure of fruit?


Solution

  • You either need to omit the '-struct' argument when saving to the mat file:

    ...
    save('fruit.mat', 'fruit');
    clear all;
    load('fruit.mat');
    fruit.grapes = 13;
    save('fruit.mat', 'fruit');
    

    Or place the structure output from load into a variable fruit:

    ...
    save('fruit.mat', '-struct', 'fruit');
    clear all;
    fruit = load('fruit.mat');
    fruit.grapes = 13;
    save('fruit.mat', '-struct', 'fruit');
    

    When you add the '-struct' argument before a variable containing a structure, the save function will store the fields of that structure as individual variables in the file instead of storing the structure as one variable. So, in the second option above, the file "fruit.mat" will contain three variables: apples, oranges, and pineapple. Calling load with no output will simply create these three variables in the workspace, not contained in a structure. You can collect all of the variables in a file into a structure by specifying an output for load.