【发布时间】:2018-12-31 16:27:39
【问题描述】:
我有一个类,它具有一些属性,它们是其他类的对象,当我将类转换为结构并检查数据时,所有属性的完整信息都存在。但是在将其存储到 .mat 文件后,当我加载数据时,作为其他类实例的属性消失了!为此,数据字段为空。有人可以帮忙吗?
【问题讨论】:
标签: matlab mat mat-file matlab-struct matlab-class
我有一个类,它具有一些属性,它们是其他类的对象,当我将类转换为结构并检查数据时,所有属性的完整信息都存在。但是在将其存储到 .mat 文件后,当我加载数据时,作为其他类实例的属性消失了!为此,数据字段为空。有人可以帮忙吗?
【问题讨论】:
标签: matlab mat mat-file matlab-struct matlab-class
为此,Matlab 推荐使用Object Save and Load Process。这需要为每个类定义两个方法,将数据存储为结构,然后再将此结构重新转换为类类型。
Mathworks documentation 展示了一个基本的 saveObj 和 loadObj 模式示例,在重新加载数据之前将结果存储在 .mat 文件中。
您需要为每个要为其保存属性的类执行此操作。
供参考:
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
这可以用作:
>>> h = GraphExpression(@(x)x.^4,[1:25])
>>> h =
>>>
>>> GraphExpression with properties:
>>>
>>> FuncHandle: @(x)x.^4
>>> Range: [1x25 double]
然后存储并重新加载:
>>> save myFile h
>>> close
>>> load myFile h
【讨论】: