Reputation: 297
Our software, lets call it Mine, relies on another simulation software, lets call it Sim. Unfortunately, there is a bug in Sim.
In order to aide in the debugging process for Sim, I need to supply the simulation file and the inputs for it.
This would mean passing Mine's MATLAB objects and their classes. Unfortunately, these classes are confidential material. So is there a way, I could down-cast(?) or convert the objects back to structs? This would provide the input values for the Sim but would not reveal to the owners of Sim how these values are derived.
Thanks.
Upvotes: 2
Views: 6686
Reputation: 1
That's how I translate object into a structure and save it as a(count) = output_struct;
. Here there is iteration on nested objects and saving empty fields.
function output_struct = object2struct(obj)
output_struct = struct();
properties = fieldnames(obj);
for i = 1:length(properties)
propname = properties{i};
propval = obj.(propname);
if ~isempty(propval)
for j = 1:length(propval)
val = propval(j);
if ~isstruct(val) && ~isobject(val) || isdatetime(val)
output_struct.(propname)(j) = val;
else
output_struct.(propname)(j) = object2struct(val);
end
end
else
output_struct.(propname) = [];
end
end
Upvotes: 0
Reputation: 2205
I am not sure if I understand your use case, but I needed to do something similar. I control an experiment through Matlab. Each device is controlled via an object (instance of some custom class). The state of each device is stored in public properties of its object. I occasionally want to save the state of my equipment, which means I have to loop over all public properties, recursively, and put all data into a struct.
Maybe the code best speaks for itself.
function output_struct = obj2struct(obj)
% Converts obj into a struct by examining the public properties of obj. If
% a property contains another object, this function recursively calls
% itself on that object. Else, it copies the property and its value to
% output_struct. This function treats structs the same as objects.
%
% Note: This function skips over serial, visa and tcpip objects, which
% contain lots of information that is unnecessary (for us).
properties = fieldnames(obj); % works on structs & classes (public properties)
for i = 1:length(properties)
val = obj.(properties{i});
if ~isstruct(val) && ~isobject(val)
output_struct.(properties{i}) = val;
else
if isa(val, 'serial') || isa(val, 'visa') || isa(val, 'tcpip')
% don't convert communication objects
continue
end
temp = obj2struct(val);
if ~isempty(temp)
output_struct.(properties{i}) = temp;
end
end
end
Upvotes: 1