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?
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.
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
andclassname
:and then write a function
myclass(x)
which returnsx.classname
. If for some reason you need to useclass()
you could even overload it with your own function which checks ifx
is one of your special structs and callsbuiltin('class', x)
otherwise:Either you have specific functionality (methods) associated with the
Point
class as opposed to e.g. theLine
class, in which case you should write out the classes by hand, anyway, or you can make a singledynamicprops
class that can have dynamically created properties, and unless you really need to call a method namedclass
, you much simplify your life by callingclassname
instead.