user2144308
user2144308

Reputation: 1

Structures in matlab: save load and work

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

Upvotes: 0

Views: 6205

Answers (1)

Shai
Shai

Reputation: 114966

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

Upvotes: 6

Related Questions