nayab
nayab

Reputation: 2380

How to save array of structres in .mat file in matlab

How to save array of structures in .mat file in Matlab? Is it possible?

p(1).x=0;
p(1).y=0;

p(2).x=1;
p(2).y=1;

save('matfilename','-struct','p');
% ??? Error using ==> save
% The argument to -STRUCT must be the name of a scalar structure variable.

Upvotes: 1

Views: 6457

Answers (1)

Florian Brucker
Florian Brucker

Reputation: 10375

You can use save without the -struct parameter:

>> p(1).x = 0;
>> p(1).y = 0;
>> p(2).x = 1;
>> p(2).y = 1;
>> save('myvars.mat', 'p');
>> clear p;
>> load('myvars.mat');
>> p(1)

ans = 

    x: 0
    y: 0

>> p(2)

ans = 

    x: 1
    y: 1

If you want want to store x and y as separate arrays (as -store would if p was a scalar struct) then you'll need to do it yourself (you can use the fieldnames function to collect the names of all fields in a struct).

Upvotes: 1

Related Questions