Convert a struct to an Object of a class.

25 views (last 30 days)
Hi everybody,
I have problem concerning the Construction of a userdefined class.
I have class called C and a struct S with excactly the same fields. Now I would like to create an Instance of my Class that sets its properties corresponding to the struct S.
Is there any command I can use (actually like an opposite struct(obj) ) ? I tried it with the command class, but this didn't work out.
I would be glad if somone could help me.
Best regards, Boris
  1 Comment
Adam
Adam on 25 Jul 2017
Edited: Adam on 25 Jul 2017
As far as I am aware you would have to set them manually, although this can be done more neatly than hard-coding using dynamic strings and the fieldnames function, assuming all the properties of your class are public. If not then there is no way you can set them from an external source.
struct( myClassObject );
is a simplification of a class to a struct, going the other way is not clearly defined because the class can have more complexity than the struct, though theoretically, with default properties it ought to be possible.
On the few occasions I have wanted to do this I just create a static function on my class to as e.g.
methods( Static, Access = public )
function obj = createFromStruct( myStruct )
...
end
end

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 25 Jul 2017
Edited: Guillaume on 25 Jul 2017
Conceptually, there is not much difference between a structure and a class, both are a container for fields. The main difference is a that the fields of a structure are always read/write whereas some of the fields of a class can be read only (or even private). Therefore, it is always possible to convert a class to a structure (fields are guaranteed to be writeable) but the opposite may not be true. Hence matlab provides a function for the former but nothing for the latter.
The proper way of enabling this, as Adam commented, is to either overload the constructor so it accepts a structure as input, or use a static method.
A less ideal way of doing this would be a free function:
function object = struct2class(classname, s)
%converts structure s to an object of class classname.
%assumes classname has a constructor which takes no arguments
object = eval(classname); %create object
for fn = fieldnames(s)' %enumerat fields
try
object.(fn{1}) = s.(fn{1}); %and copy
catch
warning('Could not copy field %s', fn{1});
end
end
end
  1 Comment
Boris Pasternack
Boris Pasternack on 25 Jul 2017
Hi Guillaume,
thanks as well for your example. This will definitely help if no better solution comes up.

Sign in to comment.

More Answers (3)

Steven Lord
Steven Lord on 25 Jul 2017
If the constructor of the class has a syntax that accepts a struct array and uses it to instantiate an instance of that class, yes.
If the constructor accepts a list of parameter name/value pairs and uses those parameters to instantiate an instance of that class, yes. Use fieldnames and struct2cell to generate a cell array that you can convert into a comma-separated list. I have not tried this example code, but it should work.
clear s
s.category = 'tree';
s.height = 37.4;
s.name = 'birch';
F = fieldnames(s);
C = struct2cell(s);
PV = [reshape(F, 1, []); reshape(C, 1, [])];
% myclass is a class whose constructor accepts parameter name/value pairs
classInstance = myclass(PV{:});
Otherwise it depends what the constructor accepts and needs; you would need to determine how to get the right information from the struct into the constructor in the format it expects.
  2 Comments
Boris Pasternack
Boris Pasternack on 25 Jul 2017
Hi Steven Lord,
thanks for your answer. In the beginning you wrote that by handing over the struct to the constructor this would be possible. How would this work?
Your second option is what I want to avoid if not necessary. But Thank you for the good example :)
Steven Lord
Steven Lord on 25 Jul 2017
The class author would need to implement the constructor to accept a struct array using code something like.
if isa(X, 'struct')
% loop over the fieldnames of the struct
% and set the properties of the object appropriately
end

Sign in to comment.


Boris Pasternack
Boris Pasternack on 25 Jul 2017
Hello again,
thank you for your help! I found a way that I don't have the struct in the first place.
Anyway, I am glad to have heard all of your suggestions for the next time I encounter this problem.

mrw2ee
mrw2ee on 18 Jun 2019
If you derive your class from matlab.mixin.SetGet, you can use the set method
tmp = [fieldnames(s),struct2cell(s)]';
set(obj,tmp{:});
I often use variations on this to initialize object parameters from inputParser results.

Categories

Find more on Structures 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!