0

I am trying to work with structures in matlab. I have a code which looks like this :

for i=1:10
    a(i).p=some value;
    a(i).q=some other value
end

I saved it to a mat file, but it didn't seem successful. Can anyone tell me, how do I save and load this structure to a file/from a file and read a particular type of data? for example, how can I read the field a(i).q after loading the structure? Thanks

Shai
  • 111,146
  • 38
  • 238
  • 371
user2144308
  • 1
  • 1
  • 2

1 Answers1

6

For saving and loading use save and load:

for ii=1:10
    a(ii).p = rand(1);
    a(ii).q = rand(1);
end
save( 'myMatFile.mat', 'a' ); % note that the variable name is passed as a STRING

clear a; % remove a from workspace. it is gone...
exist( 'a', 'var' ), % make sure a is gone

load( 'myMatFile.mat' ); % load 
exist( 'a', 'var' ), % a now exists! Ta-da!!

a(5).q, % access the fifth element of a

PS
It is best not to use i and j as variables in Matlab

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • Just be aware that MATLAB can't handle `save('file.mat','a.p')` . You need to do `foo=a.p; save('file.mat','foo')` – Carl Witthoft Nov 03 '15 at 14:09
  • @CarlWitthoft you can `save('file.mat','a','-struct')` to get the variable `p` in the saved file. – Shai Nov 03 '15 at 14:24
  • 1
    Well, yes, `save('file.mat',-struct,'a','p')` will work, but why should the user have to do what the parser should handle? – Carl Witthoft Nov 03 '15 at 15:54