Simulate 'this' pointer in matlab - matlab

I have a class that encapsulates access to an array in a wierd way;
The class constructor takes a function handle which is some kind of transformation of indexes before passing them to the array
classdef MyClass
properties
arr
accessHandle
end
methods
function obj = MyClass(array, trans)
obj.arr = array;
obj.accessHandle = #(i) obj.arr(trans(i))
end
end
The problem is the anonymous function copies the array into it's own workspace and if we change the array, it doesn't change in the function.
Essentially what is needed is to pass to the anonymous function the 'this' pointer/reference like in Java/C++/etc
The simple solution is to create a handle to the array and pass it along to the function:
classdef MyClass
properties
arr
accessHandle
end
methods
function obj = MyClass(array, trans)
obj.arr = array;
tmp = PropertyReference(obj, 'arr'); %See http://stackoverflow.com/questions/7085588/matlab-create-reference-handle-to-variable
%for the definition
obj.accessHandle = #(i) tmp(trans(i));
end
end
end
The problem now is when I pass an instance of the class to a function, the reference passed still refers to the object outside the function:
function foo(ins)
ins.arr = [1 2];
disp(ins.accessHandle(1));
end
cl = MyClass([0 3], #(x) x);
foo(cl) //output 0 instead of 1
disp(ins.accessHandle(1)) //output 0
EDIT: The class should be a value class, the semantics are that when a copy of the class is made, the accessHandle field changes the array handle it uses.
How can I achieve the right semantics ?

Currently, your class is a value class (MATLAB's default). If you want to be able to pass objects around by reference (changes will be reflected in the original object), you'll to make it a handle class by subclassing handle
classdef MyClass < handle
properties
arr
accessHandle
end
methods
function obj = MyClass(array, trans)
obj.arr = array;
obj.accessHandle = #(i) obj.arr(trans(i))
end
end
end
And then you can use it the way you expect
m = MyClass([1 2 3], #(x)x);
m.accessHandle(2)
% 2
m.arr(2) = 5;
m.accessHandle(2)
% 5
More information about the difference between the two can be found here.
Edit
If you need MyClass to be a value class, then you could store the trans value as a property and then have a normal method to access the value
classdef MyClass
properties
arr
trans
end
methods
function obj = MyClass(array, trans)
obj.arr = array;
obj.trans = trans;
end
function res = access(obj, k)
res = obj.arr(obj.trans(k));
end
end
end
Or if you want, you could make accessHandle a dependent property that returns a function handle.
classdef MyClass
properties
arr
trans
end
properties (Dependent)
accessHandle
end
methods
function obj = MyClass(array, trans)
obj.arr = array;
obj.trans = trans;
end
function res = get.accessHandle(obj)
res = #(i)obj.arr(obj.trans(i));
end
end
end

Related

Handle Class causing properties to be overwritten when create new object

Take a look at the following minimal working example,
ClassA.m
classdef ClassA < handle
properties
h1 = 0;
h2 = 0;
end
methods
function obj = ClassA(n1,n2)
if nargin == 2
obj.h1 = n1;
obj.h2 = n2;
end
end
end
end
ClassB.m
classdef ClassB < handle
properties
a = ClassA;
a0 = ClassA;
end
methods
function obj = ClassB(n1,n2)
if nargin == 2
obj.a.h1 = n1.h1;
obj.a.h2 = n1.h2;
obj.a0.h1 = n2.h1;
obj.a0.h2 = n2.h2;
end
end
end
end
main.m
h1 = ClassA(1,1);
h2 = ClassA(2,2);
h3 = ClassA(3,3);
h4 = ClassA(4,4);
x01 = ClassB(h1,h2);
x01.a.h1
x01.a.h2
x12 = ClassB(h3,h4);
x01.a.h1 % should keep its value as 1
x01.a.h2 % should keep its value as 2
The problem occurs when I instantiate a second object of class B which causing x01 to be overwritten. I think this has to do with handle class. Is there any clever way to avoid this problem? Notice ClassA must be handle since I need to modify its properties.
Note what is described in the documentation (emphasis mine):
There are two basic approaches to initializing property values:
In the property definition — MATLAB evaluates the expression only once and assigns the same value to the property of every instance.
In a class constructor — MATLAB evaluates the assignment expression for each instance, which ensures that each instance has a unique value.
This means that, for class B, a = ClassA is evaluated only once, and then every object of that class created gets a copy of a. But because ClassA is a handle object, all objects end up pointing to the same object (it is the handle that is copied, not the object).
So, the solution is follow the 2nd method to initialize property values: in the class constructor:
classdef ClassB < handle
properties
a;
a0;
end
methods
function obj = ClassB(n1,n2)
obj.a = ClassA;
obj.a0 = ClassA;
if nargin == 2
obj.a.h1 = n1.h1;
obj.a.h2 = n1.h2;
obj.a0.h1 = n2.h1;
obj.a0.h2 = n2.h2;
end
end
end
end

How do I write a common set method for multiple properties in MATLAB

I work within a project which has several classes which define properties that use essentially the same set method. To make the code more readable, I want to implement a commonSetter method. The overall goal is to include this commonSetter method in the superclass, so that all the classes could use it.
The question was already posted here, but unfortunately, the answer is not working. I changed the code to the following, but get the error: Maximum recursion limit of 500 reached.
classdef MyClass
properties
A
B
end
methods
function mc = MyClass(a,b) % Constructor
mc.A = a;
mc.B = b;
end
function mc = set.A(mc, value) % setter for A
mc = mc.commonSetter(value, 'A');
end
function mc = set.B(mc, value) % setter for B
mc = mc.commonSetter(value, 'B');
end
end
methods(Access = protected)
function mc = commonSetter(mc, value, property)
% do some stuff
disp('Made it into the commonSetter!')
mc.(property) = value;
end
end
end
So far I know that there is an infinite loop where mc.(property) = value; calls set.A (or set.B), which in turn calls commonSetter.
In my post # MathWorks the following was suggested:
To break that loop I guess you should look at builtin() and subsasgn(). Maybe Overriding subsref and subsasgn - effect on private properties can be of some help.
Currently, I have troubles realizing the suggestions and additionally not very comfortable to overwrite subsasgn() as I'm not sure how it will affect the overall project. I would like to know, if someone has other ideas or knows how to overwrite subsasgn() safely.
To solve the recursion error, you could just let the commonSetter method output the new value instead of the object.
classdef MyClass
properties
A
B
end
methods
function mc = MyClass(a, b)% Constructor
mc.A = a;
mc.B = b;
end
function mc = set.A(mc, value)% setter for A
mc.A = mc.commonSetter(value, 'A'); % update mc.A
end
function mc = set.B(mc, value)% setter for B
mc.B = mc.commonSetter(value, 'B');
end
end
methods (Access = protected)
function new_value = commonSetter(mc, value, property) % only return the new value
% do some stuff
disp('Made it into the commonSetter!')
if value > 5
new_value = -10;
else
new_value = value;
end
end
end
end

Transform equal function handles to other equal function handles

Minimalistic Example:
classdef MyClass
properties
arr
handArr
end
properties(Dependent)
rowAcc
colAcc
end
methods
function obj = MyClass(arr, handRow, handCol)
obj.arr = arr;
obj.handArr{1} = handRow;
if ~isequal(handRow, handCol)
obj.handArr{2} = handCol;
end
end
function r = get.rowAcc(obj)
r = obj.handArr{1}(obj.arr);
end
function c = get.colAcc(obj)
c = obj.handArr{end}(obj.arr);
end
end
end
Now assume I pass equal functions to the constructor, I want the row and col access would also be the same:
f=#(x)#(y) y;
x=MyClass(1, f, f);
isequal(x.rowAcc, x.colAcc) //should be 1
Is this possible?
I have a good reason for this 'insane' requirement:
I have several algorithms which run with 100+ MBs of input and takes those two functions as input, and when they are equal they can be optimized very efficiently; to call the algorithms I need to make transformations to the input functions which are encapsulated inside this class. I can't change the algorithms (not my code) and they use isequal on they're own functions to dispatch.
Two variables pointing to the same anonymous function are considered to be equal
f = #(x)x;
g = f;
isequal(f, g)
% 1
However, if you define the anonymous functions at different times, then they are not considered to be equal because the internal workspaces of the two functions could differ.
f = #(x)x;
g = #(x)x;
isequal(f, g)
% 0
In order to have your property return equal handles, you could have some "shadow" property (accessors_) which caches the accessors and you update these cached values whenever the arr property is changed.
classdef MyClass
properties
arr
handArr
end
properties (Access = 'protected')
accessors_ % An array of accessor functions for rows & columns
end
properties (Dependent)
rowAcc
colAcc
end
methods
function set.arr(obj, value)
% Set the value
obj.arr = value;
% Update the accessors_
self.accessors_ = obj.handArr{1}(obj.arr);
% Only assign another accessor if we have a second one
if numel(obj.handArr) > 1
self.accessors_(2) = obj.handArr{2}(obj.arr);
end
end
function res = get.rowAcc(obj)
res = obj.accessors_(1);
end
function res = get.colAcc(obj)
% If only one was stored, this will return a duplicate of it
res = obj.accessors_(end);
end
end
end
This also has the added benefit that you aren't creating function handles every time that colAcc and rowAcc are retrieved.

Matlab set property from class method

I'm trying to access a class property from within a method function. When I modify the property from the constructor, the setter is called and the property is changed. But when I modify the property from another method, the property reverts to the previous value, when the function is terminated, even though the setter is called again.
What is wrong with my code, please help me!
Thanks
The code is below:
classdef random
properties
x
end
methods
function obj=random(obj)
obj.x = 2
obj.foo(1)
obj %output x:2, but it should be 1!
end
function foo(obj,A)
obj.x = A;
obj %output x:1
end
function obj = set.x(obj,newVal)
obj.x = newVal;
end
end
end
Somebody correct me if I am wrong, but I assume the obj in foo is passed by value. So it does get updated within that function space but not returned. So what works is to have it return the object and catch that in the constructor. Try:
classdef random
properties
x
end
methods
function obj=random(obj)
obj.x = 2;
obj = obj.func1(4);
disp(obj.x);
end
function [obj] = func1(obj,A)
obj.x = A;
disp(obj.x);
end
function obj = set.x(obj,newVal)
obj.x = newVal;
end
end
end

How to change the property of an instance in Matlab

I'm new to MATLAB, and I want to write a method of a class that change the property of this object:
classdef Foo
properties
a = 6;
end
methods
function obj = Foo()
end
function change(obj,bar)
obj.a = bar
end
end
end
foo = Foo()
foo.change(7) //here I am trying to change the property to 7
It turns out the property is still 6.
MATLAB makes a difference between value classes and handle classes. Instances of value classes are implicitely copied on assignments (and hence behave like ordinary MATLAB matrices), instances of handle classes are not (and hence behave like instances in other OOP languages).
Therefore, you have to return the modified object for value classes:
classdef ValueClass
properties
a = 6;
end
methods
function this = change(this, v)
this.a = v;
end
end
end
Call it like this:
value = ValueClass();
value = value.change(23);
value.a
Alternatively, you can derive your class from the handle class:
classdef HandleClass < handle
properties
a = 6;
end
methods
function change(this, v)
this.a = v;
end
end
end
And call it like this:
h = HandleClass();
h.change(23);
h.a
There's more information in the MATLAB documentation.