0
votes

I am trying to save and load structure arrays in a MAT-file, but the structure array keeps changing every time I reload it. If save the following and reload it, it keeps adding struct in front.

struct.field1
struct.field2

save data.mat struct

struct = load('data.mat');

I know that this is happening because I load the file in a variable which makes it a struct and that it won't if I use only:

load('data.mat')

However I am calling the load command within a function and therefore I cannot use this. Does anyone have an idea how to solve this, so that I don't get:

struct.struct.struct.struct.struct.field1;
struct.struct.struct.struct.struct.field2;

after couple of times reloading the data.mat file, but just this:

struct.field1;
struct.field2;

Kind regards,

Romano

1
You mean that you don't know the name of the variable that will be loaded via the load command? - houtanb
I do know the name, because I saved it myself, but I do not know how to solve not getting struct.struct.struct.struct. etc... - Romano
Then why can't you simply have load('data.mat','structure_name') in the function and return structure_name? Why do you even have to assign it to a variable? - houtanb
Because just simple load('data.mat'); does not work inside a function. But load('data.mat','structure_name'); works. Thank you ;) - Romano
load('data.mat') works inside a function as well, FYI - houtanb

1 Answers

1
votes

To avoid adding deeper nested structs you could choose to save all fields as individual variables using the content option -struct

MystructName.field1 = 0
MystructName.field2 = 1

save('data.mat', '-struct', 'MystructName')

Then load the data to a variable and I'll see that the structure hasn't changed

MyStructName = load('data.mat')
MyStructName = 
    field1: 0
    field2: 1

Ps. Perhaps this is only in your example, but naming your struct to struct is bad since it overwrites the Matlab built-in function named struct.