Saving a struct property within a class object
15 次查看(过去 30 天)
显示 更早的评论
I'm trying to save an instance of a class object I've made for later reference. Some of my properties are structs. I can set and manipulate them as expected, but when I save, the saved object reverts to their default values (or empty if there was no default). Do I need to initialize structs in a special way? Or is there an Attribute I need to set?
This is an example of my class:
classdef testclass
properties
S = struct('d', 0, 'e', 1);
number = 1;
end
methods
function obj = set.S(obj, val)
obj.S.d = val + 1;
obj.S.e = val + 3;
end
end
end
My test output - the save function saves the integer value, but doesn't save changes to the struct:
>> t = testclass
t =
testclass with properties:
S: [1×1 struct]
number: 1
>> t.number = 10;
>> t.S = 3;
>> t.S
ans =
struct with fields:
d: 4
e: 6
>> save test.mat t
>> clear
>> load test.mat
>> t.S
ans =
struct with fields:
d: 0
e: 1
>> t.number
ans =
10
The reason my struct set function is written this way is I'd like to give my function a few parameters to calculate trajectory arrays, and then I save those trajectories for reference. This works fine until I try to save my class object, so I've been saving my structs as separate variables outside the class object, i.e.:
S = t.S; save test.mat t S
Is there a cleaner way to do this instead?
0 个评论
回答(1 个)
Jeremy
2020-3-31
编辑:Jeremy
2020-3-31
classdef testclass
properties (GetAccess=public, SetAccess=public)
S
number
end
methods
function obj = testclass(num,val)
obj.number = num;
obj.S.d = val + 1;
obj.S.e = val + 3;
end
end
end
>> t = testclass(10,3)
t =
testclass with properties:
S: [1×1 struct]
number: 10
>> t.S
ans =
struct with fields:
d: 4
e: 6
>> save test.mat t
>> clear
>> load test.mat
>> t
t =
testclass with properties:
S: [1×1 struct]
number: 10
>> t.S
ans =
struct with fields:
d: 4
e: 6
Does this help?
6 个评论
Jeremy
2020-3-31
You call the class methods on the class instance (object) after creation, e.g. in your example you would call it like
t = testclass
update_struct(t)
See some examples here:
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Class File Organization 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!