Creating classes dynamically in matlab - oop

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?

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

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

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.

Related

OCaml Encapsulation

I'm facing a problem and studying the OCaml documentation did not enable me to find a satisfying solution yet.
The following snippet illustrates my problem:
class A = object (self)
(* this should not be overwrittable in subclass B, but callable
on objects of type B!
*)
method dangerous_one input =
(do dangerous stuff...)
let safe_output = safe_dangerous_one input in
(... more dangerous things done with safe_output ...)
(* This is safe, should be overwrittable and callable in subclass *)
method safe_dangerous_one input = (...)
end
class B = object(self) inherit A as super
method! safe_dangerous_one input = (* subclass behaviour ... *)
end
To sum up the snippet: class A is base class to subclass B.
It has a dangerous method that is complex and has some dark corners I don't want client code to have to deal with.
In fact, I want to prohibit subclasses from overwriting method "dangerous_one".
Instead, they should overwrite the function "safe_dangerous_one".
Furthermore, it should be possible to CALL "b#dangerous_one" where "b : B" which uses the (new) definition of the "safe_dangerous"-parts as specified in class B.
My dilemma appears to be: if I simply make method "dangerous_one" private, nothing keeps the client code in class B from overwriting it, potentially even making it public.
If I hide its implementation from the signature, it can not be overwritten anymore, but I cannot call "b#dangerous_one" anymore - the code becomes inaccessible to calls also.
Is there any way to achieve what I aim to do?
Best,
Nablezen
If I hide its implementation from the signature, it can not be overwritten anymore, but I cannot call "b#dangerous_one" anymore - the code becomes inaccessible to calls also.
You can, you just need to make it private, you can't hide public methods:
class type safe = object
method safe_dangerous_one : in_channel -> int
end
class a : safe = object (self)
method private dangerous_one input = input_binary_int input
method safe_dangerous_one input =
max 255 (self#dangerous_one input)
end
class b parameters = object(self)
inherit a parameters as super
method! safe_dangerous_one input =
super#safe_dangerous_one input + 1
end
If you want unsafe method to be accessible, but not overridable, then just re-publish it at another name (kind of NVI):
class type safe = object
method unsafe_dangerous_one : in_channel -> int
method safe_dangerous_one : in_channel -> int
end
class a : safe = object (self)
method private dangerous_one input = input_binary_int input
method unsafe_dangerous_one input = self#dangerous_one input
method safe_dangerous_one input =
max 255 (self#dangerous_one input)
end
class b = object(self)
inherit a as super
method! safe_dangerous_one input =
super#safe_dangerous_one input + 1
end
And a piece of free advice. In other languages, classes and methods are used as a tool for structuring programs, because they have no better tools. In OCaml you have first class functions, records, structures, etc. So it is better to use a proper tool for at each situation. When you design a class, you should understand, that the method by its original definition (not spoiled by C++/Java/Python/etc) is something overridable. A method is an operation that has an implementation that varies across some genera. So, if you define something as a method, and then trying hard to prevent people from overriding it, then chances are high that you're doing something wrong. If you don't want it to be overridable, then just don't define it as a method at all. In your case you should put dangerous_one operation into a let-bound function. You can bound it in the context of the class, so that you will have an access to all parameters, or you can bind it on a toplevel, the choice is yours:
class a parameters =
let dangerous_one input = input_binary_int input in
object (self)
method safe_dangerous_one input =
max 255 (dangerous_one input)
end
class b = object(self)
inherit a as super
method! safe_dangerous_one input =
super#safe_dangerous_one input + 1
end
Also, a very good source of documentation about OCaml class system is Jason Hickey's Introduction to Objective Caml. It is slightly outdated, but is still very good.

Class structure in Lua/Corona

So I'm working on a game in Lua and I'm trying to use metatables and classing but I think I'm importing my PHP knowledge and doing things slightly sideways.
-- Basic Monster
Monster = {}
function Monster:new(newX, newY)
local newMonster = {x = newX, y = newY}
setmetatable(newMonster, {__index = Monster})
return newMonster
end
function Monster:moveTo(newX, newY)
self.x = newX
self.y = newY
end
function Monster:takeDamage()
self.hitPoints = self.hitPoints - playerWeapon.damage
if self.hitPoints <= 0 then
self.die()
end
end
function Monster:tap()
self.takeDamage()
end
function Monster:die()
self.removeSelf()
end
--Groblin
Groblin = {}
setmetatable(Groblin, {__index = Monster})
function Groblin:new(newX, newY)
local groblin = display.newImage('assets/images/goblin.png');
groblin.hitPoints = 4
physics.addBody(groblin, 'static')
gameGroup.insert(groblin)
return groblin
end
I'm basically looking to be able to spawn several different types of monsters, and retain some base class functionality for them, but I'm uncertain in the above example how I tie in the base class to the Groblin class I made as I feel like I blew out that subclass altogether by what I'm doing inside of Groblin:new.
If you want classes that you can subclass, try using middleclass. It's not very trivial to do subclasses in standard lua and middleclass has taken care of the boilerplate.
Also, make use of local -- use it anywhere it can be used.
A simple way to do this with your example would be:
function Groblin:new(newX, newY)
local groblin = Monster:new( newX, newY )
setmetatable(groblin, {__index = Groblin})
groblin.image = display.newImage('assets/images/goblin.png');
-- ...
return groblin
end
Use the base class ":new()" method to construct the object and then add the unique fields for the subclass. This insures the base class is properly constructed. Re-setting the metatable to "Groblin" in the subclass constructor insures that any methods defined for the Groblin subclass are called if available, and where the Groblin table does not re-define a method the superclass method will be called.
It probably is better to use a library that provides a consistent approach for object creation and subclassing, but hopefully that gives you a better idea of how to do things manually.
Check out http://www.lua.org/pil/16.2.html for inheritance.
Pay a little attention on the explanation of how the use of self in Account:new works out best while SpecialAccount extends Account.
I generally follow a little different approach than the mentioned in above link. In the above approach -
SpecialAccount = Account:new()
s = SpecialAccount:new{limit=1000.00}
You are calling Account:new() twice, and more problem arises when Acoount:new() does some validaiton on constructor parameters and throws exceptions. For ex: ensuring that the limit passed in non-nil.
So I follow this
SpecialAccount = setmetatable({__index = Account})
Does the trick of allowing superclass constructor to be used in subclasses.
PS: I prefer to treat new function as a constructor. It essentially does the same job.

How to clear a persistent variable in a MATLAB method

I have a MATLAB class that contains a method that employs a persistent variable. When certain conditions are met I need to clear the persistent variable without clearing the object to which the method belongs. I've been able to do this, but only by employing clear functions which has excessively broad scope for my purposes.
The classdef .m file for this problem:
classdef testMe
properties
keepMe
end
methods
function obj = hasPersistent(obj)
persistent foo
if isempty(foo)
foo = 1;
disp(['set foo: ' num2str(foo)]);
return
end
foo = foo + 1;
disp(['increment foo: ' num2str(foo)]);
end
function obj = resetFoo(obj)
%%%%%%%%%%%%%%%%%%%%%%%%%
% this is unacceptably broad
clear functions
%%%%%%%%%%%%%%%%%%%%%%%%%
obj = obj.hasPersistent;
end
end
end
A script that employs this class:
test = testMe();
test.keepMe = 'Don''t clear me bro';
test = test.hasPersistent;
test = test.hasPersistent;
test = test.hasPersistent;
%% Need to clear the persistent variable foo without clearing test.keepMe
test = test.resetFoo;
%%
test = test.hasPersistent;
test
The output from this is:
>> testFooClear
set foo: 1
increment foo: 2
increment foo: 3
increment foo: 4
set foo: 1
test =
testMe
Properties:
keepMe: 'Don't clear me bro'
Methods
which is the desired output. The problem is that the line clear functions in the classdef file clears all functions in memory. I need a way to clear with a much smaller scope. For example, if hasPersistent' was a function instead of a method, the appropriately scoped clear statement would beclear hasPersistent`.
I know that clear obj.hasPersistent and clear testMe.hasPersistent both fail to clear the persistent variable. clear obj is similarly a bad idea.
Following the discussion in the comments, I think you want to use make foo a private property, accompanied with appropriate increment/reset public functions.
You definitely don't need a persistent variable to implement what you want. But, in any case, to remove a persistent variable from a class method you have to clear the corresponding class. In your case, clear testMe should do what you want.
A related issue is how to clear a persistent variable in a package function. To remove persistent variable myVar from function foo within package foo_pkg you have to do this:
clear +foo_pkg/foo
This should work as long as the parent folder of folder +foo_pkg is in the MATLAB path.

Can properties of an object handle returned from a function be used without first assigning to a temporary variable?

I have a function that returns a handle to an instantiated object. Something like:
function handle = GetHandle()
handle = SomeHandleClass();
end
I would like to be able to use the return value like I would if I was writing a program in C:
foo = GetHandle().property;
However, I get an error from MATLAB when it tries to parse that:
??? Undefined variable "GetHandle" or class "GetHandle".
The only way I can get this to work without an error is to use a temporary variable as an intermediate step:
handle = GetHandle();
foo = handle.property;
Is there a simple and elegant solution to this, or is this simply impossible with MATLAB's syntax?
To define static properties, you can use the CONSTANT keyword (thanks, #Nzbuu)
Here's one example from MathWorks (with some errors fixed):
classdef NamedConst
properties (Constant)
R = pi/180;
D = 1/NamedConst.R;
AccCode = '0145968740001110202NPQ';
RN = rand(5);
end
end
Constant properties are accessed as className.propertyName, e.g. NamedConst.R. The values of the properties are set whenever the class is loaded for the first time (after the start of Matlab, or after clear classes). Thus, NamedConst.RN will remain constant throughout a session as long as you don't call clear classes.
Hmm, I don't like to disagree with Jonas and his 21.7k points, but I think you can do this using the hgsetget handle class instead of the normal handle class, and then using the get function.
function handle = GetHandle()
handle = employee();
end
classdef employee < hgsetget
properties
Name = ''
end
methods
function e = employee()
e.Name = 'Ghaul';
end
end
end
Then you can use the get function to get the property:
foo = get(GetHandle,'Name')
foo =
Ghaul
EDIT: It is not excactly like C, but pretty close.
The only way to have a static property in MATLAB is as a constant:
classdef someHandleClass < handle
properties (Constant)
myProperty = 3
end
end
then someHandleClass.myProperty will return 3.

How to get the handle of a method in an Object (class inst) within MATLAB

I'm trying to grab a method handle from within an object in MATLAB, yet something in the sort of str2func('obj.MethodName') is not working
The answer is to get a function handle as #Pablo has shown.
Note that your class should be derived from the handle class for this to work correctly (so that the object is passed by reference).
Consider the following example:
Hello.m
classdef hello < handle
properties
name = '';
end
methods
function this = hello()
this.name = 'world';
end
function say(this)
fprintf('Hello %s!\n', this.name);
end
end
end
Now we get a handle to the member function, and use it:
obj = hello(); %# create object
f = #obj.say; %# get handle to function
obj.name = 'there'; %# change object state
obj.say()
f()
The output:
Hello there!
Hello there!
However if we define it as a Value Class instead (change first line to classdef hello), the output would be different:
Hello there!
Hello world!
One could also write
fstr = 'say';
obj.(fstr)();
This has the advantage that it does not require a handle class to work if the object (obj) is modified.
Use #. The following code works for me:
f = #obj.MethodName
No other answer mimics str2func('obj.MethodName'). Actually, this one doesn't either, not exactly. But you can define an auxillary function like so:
function handle = method_handle(obj, mstr)
handle = #(varargin) obj.(mstr)(varargin{:});
end
Then method_handle(obj, 'MethodName') returns a handle to obj.MethodName. Unfortunately, you cannot pass the variable name of obj as a string - eval("obj") will be undefined in the function's scope.