Creating classes dynamically in matlab

2019-04-28 21:33发布

问题:

Given a structure, is there a way to create a class in MATLAB? Take for instance

>> p = struct(); p.x = 0; p.y = 0;
>> p

p = 

    x: 0
    y: 0

>> name = 'Point'

name =

Point

What I would like to do, is given a string containing the name of the class and a struct with containing the fields I would like to create a class without having to write a file explicitly writing the definition.

Right now if we use class(p) we will obtain struct. What I want to do is create an object of the type Point so that when I do class(obj) then I get Point.

Any ideas how to accomplish this besides writing a file in MATLAB with the class definition and then executing it?

回答1:

Either you have specific functionality (methods) associated with the Point class as opposed to e.g. the Line class, in which case you should write out the classes by hand, anyway, or you can make a single dynamicprops class that can have dynamically created properties, and unless you really need to call a method named class, you much simplify your life by calling classname instead.

classdef myDynamicClass < dynamicprops
properties (Hidden)
myClass %# this stores the class name
end
methods
function obj = myDynamicClass(myClassName,varargin)
%# synopsis: obj = myDynamicClass(myClassName,propertyName,propertyValue,...)
%# myClassName is the name of the class that is returned by 'classname(obj)'
%# propertyName/propertyValue define the dynamic properties

obj.myClass = myClassName;

for i=1:2:length(varargin)
addprop(obj,varargin{i})
obj.(varargin{i}) = varargin{i+1};
end
end

function out = classname(obj)
out = obj.myClass;
end

end 
end


回答2:

I don't know of any way of creating objects dynamically, so I'd say the answer to your question is no. However, to solve your problem, I would propose something very similar to what Mikhail said:

Work with a struct with fields x, y and classname:

p.x=0;
p.y=0;
p.classname='Point';

and then write a function myclass(x) which returns x.classname. If for some reason you need to use class() you could even overload it with your own function which checks if x is one of your special structs and calls builtin('class', x) otherwise:

function out=class(varargin)
if nargin==1 && isstruct(varargin{1}) ... #check if we were given a struct
   && isfield(varargin{1}, 'classname') ... #...which contains a field classname
   && ischar(varargin{1}.classname) %# ... which is a string
    out=varargin{1}.classname; %# ok, our special case :-)
else
    out=builtin('class',varargin{:}); %# normal case - call builtin class()
end


回答3:

One solution that I've used in the past is to write a MATLAB function that takes this information (i.e. the class name and fields) and writes an M-file containing the required classdef construct.

This works well if you're using this information to describe a prototype that you want to expand later.



标签: oop matlab