MATLAB Answers

Save class object as struct

조회 수: 77(최근 30일)
Behnam 2021년 5월 20일
댓글: Matt J 2021년 7월 28일
I want to automatically convert class objects to structs before saving them to MAT files.
This webpage seems to explain the task that I expect. However, when I try the following, it trurn out that it is not as expected:
mySuper = MySuper;
save('m.mat', 'mySuper')
The saved file contains mySuper variable still as a class object, not a struct.
If I delete the class and load the file afterwards, I get:
Warning: Variable 'mySuper' originally saved as a MySuper cannot be instantiated as an object and will be read in as a uint32.
> In uiimport/runImportdata (line 459)
In uiimport/gatherFilePreviewData (line 438)
In uiimport (line 262)
Class MySuper could be extended by changing the saveobj method to the following:
function S = saveobj(obj)
S = struct(obj);
But this doesn't work either.
I'm using MATLAB R2020a.
  댓글 수: 4
Michael Jablecki
Michael Jablecki 2021년 6월 23일
This has been a problem for a while. Object serialization tends to have issues, and I have had parallel problems with Python pickled objects. It is a portability problem. When the class changes, the saved object will no longer be able to be loaded in many cases, making debugging challenging if the process involves saved (serialized) instances separated from the code which generated them. I'd stick with saving as structures and reconstitute as described above rather than ever saving a "native class instance". They are trouble.

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

채택된 답변

J. Alex Lee
J. Alex Lee 2021년 6월 11일
I think it means when you implement saveobj/loadobj, it will internally use a struct intermediary, but ultimately when you load the object, the intent is that the output will be an object, not a struct.
if need the struct, I guess you can just do
s = struct(obj)
or just wrap that in a "export" method for your class.
  댓글 수: 3
Matt J
Matt J 2021년 7월 28일
Yes, the loadobj/saveobj mechanism is the intended way to handle saved objects that are out of date with their class definitions.

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

추가 답변(0개)




Community Treasure Hunt

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

Start Hunting!

Translated by