How can I bypass the property SET methods when loading a MATLAB class object from a MAT-file in MATLAB 7.6 (R2008a)?
1 view (last 30 days)
Show older comments
While loading MATLAB class objects from a MAT-file, the LOAD function invokes the SET methods of the individual properties to reconstruct the objects. In my code, this procedure may lead to undesirable results: certain SET methods modify the values of multiple properties. Because the order in which the SET methods are invoked cannot be determined beforehand, I receive objects that are not reconstructed in the way I had saved them. Below is an example class:
classdef polygon
properties
Vertices = zeros(0,2);
NumPoints = 0;
end
methods
function Obj = set.NumPoints(Obj,n)
Obj.NumPoints = n;
Obj.Vertices = zeros(n,2);
end
end
end
If I execute the following code at the MATLAB command prompt:
p=polygon;
p.NumPoints=4;
p.Vertices=[-1 -1; 1 -1; 1 1; -1 1];
save test.mat
clear
load test.mat
p.Vertices
I will receive the following output:
ans =
0 0
0 0
0 0
0 0
when I expected p.Vertices to remain a matrix of 1's and -1's.
Accepted Answer
MathWorks Support Team
on 21 Jan 2010
The ability to bypass the SET and GET methods when loading an instance of a MATLAB class is not available in MATLAB.
A possible workaround is to overload the SAVEOBJ function to save the object's properties into a struct that in turn can be saved into a MAT-file. The LOADOBJ should also be overloaded to execute the SET methods in the appropriate order when reconstructing the object. The code for the above described functions can be found below:
function s = saveobj(obj)
% save properties into a struct.
% Pass that struct onto the SAVE command.
s.NumPoints = obj.NumPoints;
s.Vertices = obj.Vertices;
end
function obj = loadobj(s)
obj = polygon;
obj.NumPoints = s.NumPoints;
obj.Vertices = s.Vertices;
end
Note that LOADOBJ must be a static method. A class file incorporating the above two functions can be found attached.
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!