How to load, update and save data neatly

조회 수: 15 (최근 30일)
Adam
Adam 2014년 9월 3일
댓글: Adam 2014년 9월 3일
I have a variable saved to a .mat file which I wish to load in, update (extend) and save out again to the same file.
Obviously I can just call load with no output argument and then save. But people generally seem to say that
s = load( someFilename );
is far better than using the no output argument form. This I understand.
What I am finding difficult to do neatly is the saving back of my updated data. I can update easily as:
s.myVar = someFunction( s.myVar );
but then I can't just do:
save( someFilename, 's' )
as that will leave me with a structure in my file which would not then match the original format. I also can't do:
save( someFilename, 's.myVar' )
as this is clearly nonsense.
So do I really have to do the following?:
myVar = s.myVar;
save( someFilename, 'myVar' )
If so this seems to obviate the purpose of calling load with an output argument in the first place.

채택된 답변

Star Strider
Star Strider 2014년 9월 3일
See if the matfile function does what you want. (I’m not certain when it was introduced, but it’s in R2014a.)
  댓글 수: 3
Adam
Adam 2014년 9월 3일
m = matfile( someFilename, 'Writable', true );
myVar = m.myVar;
myVar = update( myVar );
m.myVar = myVar;
does work and does at least relieve me of the need to have potentially unknown variables arriving in my workspace as I would with the no output form of 'save'.
Sadly, just updating the variable where it sits, in the matfile, does not work since it is of a custom class and I am resizing it.
Star Strider
Star Strider 2014년 9월 3일
Yes, according to the documentation, it doesn’t support user-defined classes. Sorry.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2014년 9월 3일
편집: Guillaume 2014년 9월 3일
save(someFilename, '-struct', 's');
Will save the fields as individual variables (it's in the documentation of save!)
You can even specify which fields you want to save:
save(someFilename, '-struct', 's', 'fieldname1', 'fieldname2, ...);
  댓글 수: 1
Adam
Adam 2014년 9월 3일
Ah yes, so it is. I never expanded the 'variables' hyperlink as it didn't seem promising and I thought I knew what variables are! I also didn't notice the example lower down the page with the rather obvious titling :(

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by