Saveobj and Loadobj for arrays of objects
7 次查看(过去 30 天)
显示 更早的评论
I am trying to customize the save() and load() process for a classdef. Cuurrently, I am using old-style saveobj() and loadobj() methods, as I am still trying to get familiar with the newer approach.
Unlike most class methods, calling saveobj and load obj on an array of objects,
saveobj(objArray)
loadobj(objArray)
does not result in the entirety of objArray being passed to the user-provided code. Instead, there is some background Matlab process that invokes them one element at a time, equivalent to,
for i=1:numel(objArray)
saveobj(objArray(i))
loadobj(objArray(i))
end
However, my saveobj() and loadobj needs to know things about the entire array being saved, and calling them one element at a time hides this information. Is there any way to overcome this problem? As I said, I am still getting acquainted with the newer custom serialization and deserialization tools. Is there any chance that could hold a solution?
2 个评论
采纳的回答
Benjamin Kraus
2025-5-27
编辑:Benjamin Kraus
2025-5-27
It sounds like you may benefit from switching to an object that "fakes" its size. Some examples of objects that do this (that ship with core MATLAB) include table, string, datetime, duration, and others.
For example: a "vector" of duration objects is really a scalar object that "fakes" its size, you can see this by calling builtin to access the size:
d = hours(1:10);
size(d)
builtin('size',d)
You can see that while size reports [1x10], this is really a single object that pretends to be a vector.
The reason this would help you is that because this is really a scalar object, calling save on that "vector" will only call saveobj once with the entire "vector".
Making an object like this used to be quite complicated, but MATLAB recently (R2021b) introduced matlab.mixin.indexing.RedefinesParen which makes this substantially easier. In fact, the example on the documentation page of how to use the class is an example of a class that is a scalar object that behaves like a matrix. You can start with that base example and add a saveobj and loadobj method to test how this works and if it will satisfy your requirements.
2 个评论
Benjamin Kraus
2025-5-27
编辑:Benjamin Kraus
2025-5-27
As an aside, the newer approach you mention is awesome and worth learning about, but from the perspective of arrays of objects, the behavior is the same as the old approach.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Object Save and Load 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!