MATLAB Answers

Could not save custom class objects in a particular combination but why?

3 views (last 30 days)
Kouichi C. Nakamura
Kouichi C. Nakamura on 23 Apr 2021
I want to use save function to save variables as a cache file cachefile.
When I do so, I receive this error message:
save(cachefile, 'Tbhv', 'rec', 'Ttrialcounts', 'obj');
Error using save
Unable to save file '\\**\**\*****.mat'. The file could not be closed, and might now be corrupt.
Among them, Tbhv and Ttrialcounts are table data, whereas rec and obj are objects of two different custom classes. They are pretty complicated.
Initially, the problem appeared to be related to obj. Because I could not save it alone
save(cachefile, 'obj');
So I implemented saveobj and loadobj methods to the class; the properties of the obj are saved as struct by saveobj, and when loading, the struct is used to re-construct the obj by the static loadobj method. With that, the above line works without error.
Now all the three commands below work. Yet, I cannot save all of the four in one file.
save(cachefile, 'Tbhv');
save(cachefile, 'rec');
save(cachefile, 'Ttrialcounts');
And the following combinations work as well.
save(cachefile,'Tbhv', 'Ttrialcounts', 'rec')
save(cachefile,'Tbhv', 'Ttrialcounts', 'obj')
However, these combinations end up with an error.
save(cachefile,'obj', 'rec')
save(cachefile,'rec', 'obj')
How on earth each objects can be saved properly, but they cannot be saved together? Is it expected in some cases? Or is it a bug?
Futher digging this deeper, it appears to be related to the saveobj method of obj and rec.
Properties of obj look like this:
stage_id: '*******'
rec: [1×1 Record]
Tbhv: [126147×26 table]
Sbhv: [1×1 struct]
openEphysTimeBhv: [126147×1 double]
prm: '\\***\****.prm'
Tclu: [49×14 table]
Laser_t_s: [0×1 double]
Laser_onoff: [0×1 logical]
Laser_color: "none"
As you can see one of obj property holds rec, a Record object.
When I removed this, like
obj2 = obj;
obj2.rec = []
then the following worked.
save(cachefile,'obj2', 'rec')
save(cachefile,'rec', 'obj2')
OK, but why???

Answers (0)

Community Treasure Hunt

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

Start Hunting!