I have a class which has some properties that they are objects of other classes, when I convert the class to a struct and check the data, the full information of all properties exist. but after storing it to a .mat file, when I load the data, the properties which are instances of other classes are disappeared! the data field is empty for that. can anybody help by this, please?
Asked
Active
Viewed 776 times
1 Answers
1
To do this Matlab recommends the Object Save and Load Process. This requires defining two methods for each class, that handle storing the data as a structure and then later re-converting this structure into the class type.
The Mathworks documentation show an example of a basic saveObj & loadObj pattern, with storing the result in a .mat file, before reloading the data back.
You will need to do this for every class you wish to save the properties for.
For reference :
classdef GraphExpression
properties
FuncHandle
Range
end
methods
function obj = GraphExpression(fh,rg)
obj.FuncHandle = fh;
obj.Range = rg;
makeGraph(obj)
end
function makeGraph(obj)
rg = obj.Range;
x = min(rg):max(rg);
data = obj.FuncHandle(x);
plot(data)
end
end
methods (Static)
function obj = loadobj(s)
if isstruct(s)
fh = s.FuncHandle;
rg = s.Range;
obj = GraphExpression(fh,rg);
else
makeGraph(s);
obj = s;
end
end
end
end
This can be used as :
>>> h = GraphExpression(@(x)x.^4,[1:25])
>>> h =
>>>
>>> GraphExpression with properties:
>>>
>>> FuncHandle: @(x)x.^4
>>> Range: [1x25 double]
And then stored and re-loaded with :
>>> save myFile h
>>> close
>>> load myFile h

WoodyDev
- 1,386
- 1
- 9
- 19