0

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

5
  • You mean that you don't know the name of the variable that will be loaded via the load command? Commented Oct 12, 2016 at 9:50
  • 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... Commented Oct 12, 2016 at 10:14
  • 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? Commented Oct 12, 2016 at 10:15
  • Because just simple load('data.mat'); does not work inside a function. But load('data.mat','structure_name'); works. Thank you ;) Commented Oct 12, 2016 at 10:29
  • load('data.mat') works inside a function as well, FYI Commented Oct 12, 2016 at 10:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this answer. Yes piece of code is just an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.