I am developing a MATLAB OOP project for the first time. My parent class will have a very large matrix which the children(many) need to access. How can I prevent the children from duplicating the data ?
In pseudo code I require that,
classdef parent
properties
largeMatrix;
end
end
classdef child < parent
methods
function obj = child(parent)
Data.parent of this child = Share from parent
end
...
something = largeMatrix(n,m);
end
end
p = parent; p.largeMatrix = rand(100);
c1 = child(p);
c2 = child(p);
Both children c1 and c2 should access same data created in the original rand(100), but should not be copying the largeMatrix as I need many children, and would like the program to be memory efficient. The largeMatrix will be read from a file.
PS: This is the first time I am posting in this forum, so do forgive me if I have posted it wrongly.
MATLAB copies the array on write.
Suppose that your parent class is (no need to subclass a handle):
classdef parent
properties
largeMatrix;
end
end
and your child class is:
classdef child < parent
methods
function obj = child(parent)
obj.largeMatrix = parent.largeMatrix;
end
end
end
Now, let's create parent and assign a large matrix to its property largeMatrix:
p = parent;
p.largeMatrix = rand(1e4); % 750 MB circa
Check out the jump in the memory:
Now, let's create a child and check that the data was referenced:
c = child(p);
size(c.largeMatrix)
As you can see no jump in the memory:
Finally, let's make a simple change in the child's data:
c.largeMatrix(1) = 1;
As you can see, only on write the array is effectively copied:
To prevent writes on child.largeMatrix define the property in the parent class with attribute (Abstract = true) and in the child (SetAccess = immutable).
A class is just a data type, it does not hold any data. If you instantiate an object parent of the Parent class, and then an object child of the Child class, then by default child will not inherit any data from parent. You can copy the data from one object to another by using a copy constructor.
child = parent; % this copies the data in `parent` to `child`
However, in this case Matlab creates a copy of the data in parent.
You can avoid copying the data by using handle objects. You can assign the handle object to multiple variables or pass it to functions without causing MATLAB to make a copy of the original object. For example,
classdef A < handle
properties
largeMatrix; % wrap your large data into a handle class
end
end
classdef B
properties
data;
end
methods
function obj = B(mydata)
obj.data = mydata;
end
end
end
Then in the main program you can assign
a = A();
a.largeMatrix = rand(100);
b1 = B(a);
b2 = B(a);
b3 = b1; % can even do this
% no copies of largeMatrix were made, because `a` is a handle object
% accessing largeMatrix
b1.data.largeMatrix
b3.data.largeMatrix
Related
so i made 2 module scripts
here's the code:
local base = {}
base.__index = base
base.Number = 5
function base:New()
local t = setmetatable({}, self)
t.__index = t
return t
end
return base
second:
local base = script.Parent.Base
local child = require(base):New()
return child
this one is normal script:
local child = require(script.Parent.Child1)
print(child.Number)
and i get this message after i try executing it
stack begin
script
'ServerScriptService.Script', Line 1
Stack End
it should've executed "5"
but its not working and i don't know why
In your Base class, you set the __index metamethod to the base object, then in the constructor you say setmetatable({}, base) these two lines mean that when someone asks for a property on the empty table, that it should be found on the base object instead. But they you overwrite that behavior by setting the __index metamethod again. This removes the relationship between the new object and its base class.
So to fix this, just remove that line in the constructor.
function base:New()
local t = setmetatable({}, base)
return t
end
In Matlab class it seems to be syntactically correct to declare property that is Dependent (computed not stored) and Observable in the same time. Consider code
properties (Access = private)
instanceOfAnotherClass
end
properties (SetAccess = private, Dependent, SetObservable)
propertyTwo
end
methods
function val = get.propertyTwo(this)
val = this.instanceOfAnotherClass.propertyOne;
end
end
Does this work as expected? That is, if the property propertyOne of an object stored in instanceOfAnotherClass is changed is there property change event triggered by propertyTwo? Note that propertyOne is not Observable.
Edit:
It does not work (as I expected). 'PostSet' event is not triggered. So how do I deal with this kind of situation? Is there a better solution then to create propertyTwo as a non Dependent and set it to the same value as 'propertyOne' every time 'propertyOne' changes?
Edit2:
In reaction to Amro's edit of his answer I will explain situation more complex.
Consider this 2 classes:
classdef AClass < handle
properties
a
end
end
classdef BClass < handle
properties (Access = private)
aClassInst
end
properties (Dependent, SetObservable, SetAccess = private)
b
end
methods
function this = BClass(aClass)
this.aClassInst = aClass;
end
function val = get.b(this)
val = this.aClassInst.a;
end
end
end
The class that uses all this code should not get access to AClass. It interacts only with instance of BClass and wants to listen to changes of property b. however if I make property a of AClass observable that would not solve my problem, would it? The 'PostSet' events are not going to propagate to property b, are they?
It might be syntactically correct, but the listener callback will never execute. Example:
classdef MyClass < handle
properties (Access = public)
a
end
properties (SetAccess = private, Dependent, SetObservable)
b
end
methods
function val = get.b(this)
val = this.a;
end
end
end
Now try:
c = MyClass();
lh = addlistener(c, 'b', 'PostSet',#(o,e)disp(e.EventName));
c.a = 1;
disp(c.b)
As you can see the 'PostSet' callback is never executed.
EDIT
The way I see it, SetObservable should really be set on a not b. Its because b is read-only and can only change if a changes. Now the PostSet event would notify us that both properties have changed.
Use the same example I used above, simply move SetObservable from b to a. Of course now you listen to the event as:
lh = addlistener(c, 'a', 'PostSet',#(o,e)disp(e.EventName));
EDIT#2
Sorry I didn't pay attention to the fact that you have composition (BClass has an instance of AClass as private property).
Consider this possible solution:
AClass.m
classdef AClass < handle
properties (SetObservable)
a %# observable property
end
end
BClass.m
classdef BClass < handle
properties (Access = private)
aClassInst %# instance of AClass
lh %# event listener on aClassInst.a
end
properties (Dependent, SetAccess = private)
b %# dependent property, read-only
end
events (ListenAccess = public, NotifyAccess = private)
bPostSet %# custom event raised on b PostSet
end
methods
function this = BClass(aClass)
%# store AClass instance handle
this.aClassInst = aClass;
%# listen on PostSet event for property a of AClass instance
this.lh = addlistener(this.aClassInst, 'a', ...
'PostSet', #this.aPostSet_EventHandler);
end
function val = get.b(this)
val = this.aClassInst.a;
end
end
methods (Access = private)
function aPostSet_EventHandler(this, src, evt)
%# raise bPostSet event, notifying all registered listeners
notify(this, 'bPostSet')
end
end
end
Basically we set property a of AClass as observable.
Next inside the constructor of BClass, we register a listener for the AClass instance passed to listen on property a changes. In the callback we notify listeners of this object that b has changed as well
Since we can't really raise a PostSet manually, I created a custom event bPostSet which we raise in the previous callback function. You can always customize the event data passed, refer to the documentation to see how.
Here is a test case:
%# create the objects
a = AClass();
b = BClass(a);
%# change property a. We will not recieve any notification
disp('a.a = 1')
a.a = 1;
%# now lets listen for the 'bChanged' event on b
lh = addlistener(b, 'bPostSet',#(o,e) disp('-- changed'));
%# try to change the property a again. We shall see notification
disp('a.a = 2')
a.a = 2;
%# remove event handler
delete(lh)
%# no more notifications
disp('a.a = 3')
a.a = 3;
The output was:
a.a = 1
a.a = 2
-- changed
a.a = 3
Notice how we only interact with the BClass instance when we register our listener. Of course since all classes derive from handle class, the instance a and the private property aClassInst both refer to the same object. So any changes to a.a are immediately reflected on b.aClassInst.a, this causes the internal aPostSet_EventHandler to execute, which in turn notify all registered listeners to our custom event.
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.
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.
Consider the following Matlab (2009a) classes:
classdef BigDeal < handle
properties
hugeness = magic(2000);
end
methods
function self = BigDeal()
end
end
end
classdef BigProxy < handle
properties(Dependent)
hugeness
end
properties(Access = private)
bigDeal
end
methods
function self = BigProxy(bigDeal)
self.bigDeal = bigDeal;
end
function value = get.hugeness(self)
value = self.bigDeal.hugeness;
end
end
end
Now consider the following use of them:
Setup:
>> b = BigDeal
b =
BigDeal handle
Properties:
hugeness: [10x10 double]
Methods, Events, Superclasses
OneLayer:
>> pb = BigProxy(b)
pb =
BigProxy handle
Properties:
hugeness: [10x10 double]
Methods, Events, Superclasses
TwoLayers:
>> ppb = BigProxy(pb)
ppb =
BigProxy handle with no properties.
Methods, Events, Superclasses
Question: Why is my double layered proxy unable to see the hugeness when the single layer can? Dependent properties can be calculated - but does this go only one layer deep for some reason?
Update: See my answer below for workaround.
The problem here is two-fold:
The BigProxy object constructor is designed to accept an input object that has a (non-dependent) hugeness property (like a BigDeal object), which the BigProxy object can then access to compute the value for its own dependent hugeness property.
You are passing a BigProxy object to the BigProxy constructor when you create ppb, and you apparently can't compute a dependent property from another dependent property. For example, this is the error that is thrown when I try to access ppb.hugeness:
??? In class 'BigProxy', the get method for Dependent property 'hugeness'
attempts to access the stored property value. Dependent properties don't
store a value and can't be accessed from their get method.
In other words, the outer BigProxy object tries to compute the value for its dependent hugeness property by accessing the stored value of hugeness for the inner BigProxy object, but there is no stored value since it's a dependent property.
I think the fix for a situation like this would be for the BigProxy constructor to check the type of its input argument to make sure it is a BigDeal object, and throw an error otherwise.
Gnovice provided a good answer to the question "why," thus I awarded him the green check of glory. However, for those wanting a work around, you can do something like this:
classdef BigDeal < handle
properties
hugeness = magic(10000);
end
methods
function self = BigDeal()
end
end
end
classdef BigProxy < handle
properties(Dependent)
hugeness
end
properties(Access = private)
bigDeal
end
methods
function self = BigProxy(bigDeal)
self.bigDeal = bigDeal;
end
function value = get.hugeness(self)
value = self.getHugeness;
end
end
methods(Access = private)
function value = getHugeness(self)
if isa(self.bigDeal,'BigProxy')
value = self.bigDeal.getHugeness;
else
value = self.bigDeal.hugeness;
end
end
end
end
which will allow you to do the following
>> b = BigDeal;
>> pb = BigProxy(b);
>> ppb = BigProxy(pb);
And each of {b,pb,ppb} will all have the same public methods and properties. The only drawback is that I have had to (unnecessarily IMHO) clutter up BigProxy with a new private getter.