Handle Class causing properties to be overwritten when create new object - matlab

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

Related

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

How to define and access to static properties as a top-level member in Matlab?

I want to have a simple static member in a class with simple access i.e I like to have a class_name.static_data instead of class_name.shared_obj.static_data.
I've searched and find the standard method of defining static members in Matlab classes, on mathwork.com as you can see below.
classdef SharedData < handle % an auxiliary class to keep static data
properties
Data1
Data2
end
end
classdef UseData % main class
properties (Constant)
Data = SharedData
end
% Class code here
end
and then we can use it with something like this:
k = UseData
k.Data.Data1=5; % Want to be `k.Data1=5;` instead.
BUT I'm looking to have a top-level static member
( something like
obj_of_UseData.Data1=5;
NOT
obj_of_UseData.Data.Data1=5; )
(i.e. like a top-level member, not second-level one). I seek a method to implement top-level static member , not second-level one.
Thanks
It is possible to follow the advice from the MathWorks related to static data, and still create behavior that makes it look like those variables are members. You can do so by overloading the subsref and subsasgn methods like below. This codes uses the static method way of creating static data, since it is simplest, but the idea translates to the other method, using a handle class, as well.
classdef UseData
properties
Data3
end
methods (Static)
function out = setgetVar(name,value)
persistent data;
if isempty(data)
data = struct('Data1',[],'Data2',[]);
end
if nargin==2
data.(name) = value;
end
out = data.(name);
end
end
methods
function obj = subsref(obj,S)
if isequal(S(1).type,'.')
if strcmp(S(1).subs,'Data1') || strcmp(S(1).subs,'Data2')
obj = UseData.setgetVar(S(1).subs);
return
end
end
obj = builtin('subsref',obj,S);
end
function obj = subsasgn(obj,S,value)
if isequal(S(1).type,'.')
if strcmp(S(1).subs,'Data1') || strcmp(S(1).subs,'Data2')
UseData.setgetVar(S(1).subs,value);
return
end
end
obj = builtin('subsasgn',obj,S,value);
end
end
end
To see it working:
>> x = UseData;
>> y = UseData;
>> x.Data1 = 'bla';
>> y.Data2 = [5,6];
>> x.Data3 = 0;
>> y.Data3 = 10;
>> y.Data1
ans = bla
>> x.Data2
ans =
5 6
>> x.Data3
ans = 0
>> y.Data3
ans = 10

Is it possible to have object of some class as class property as other class in MATLAB?

I am trying make a simple agent and environment class in MATLAB 2014.
I am trying to have the object 'a' of Agent class as one of the properties of the Environment class. I have initialized the object in the Environment class constructor, but whenever I am trying the access the methods of Agent class using this object A, I am getting warning as:
"Confusing function call. Did you mean to reference property 'a'?"
Here is my Environment class and Agent class. How do I call method of Agent class from interact_with_agent_function directly like we call in JAVA?
classdef Environment < handle
properties (Constant = true)
V = 0.5;
T = 1;
end
properties (SetObservable= true)
A;
B;
a;
end
methods
function obj = initialize(obj, A, B)
obj.A = A;
obj.B = B;
a = Agent();
end
function act = call_agent(obj)
act = agent_function(a, obj.A, obj.B, obj.V, obj.T);
end
function action = interact_with_agent(obj)
action = obj.call_agent();
end
end
end
classdef Agent < handle
properties (SetObservable = true)
action;
end
methods
function action = agent_function(obj, A, B, v, t)
obj.action = A + v * t * ((B - A) / norm(B - A));
action = obj.action;
end
end
end
The problem here is as follows:
in the class definition, you created a variable (property) of your Environment class: lowercase a
in the initialize method, you create a local variable a, which is removed after the function finished. You should use obj.a = ... to save the Agent() in the object.
in the call_agent you use an uninitialised local variable a as first input. If you mean to refer to the a property of your class; use obj.a instead
On top of that, it might be useful to know that matlab has a default initialisation function for it's classes, which matches the name of your class; in your case this would be function obj = Agent(obj) and function obj = Environment(obj); see also https://nl.mathworks.com/help/matlab/object-oriented-programming.html for more information on classes in matlab.
You should define your classes this way:
classdef Environment < handle
properties (Constant = true)
V = 0.5;
T = 1;
end
properties (SetObservable= true)
A;
B;
a;
end
methods
% Replace here the init function using the Matlab Constructor
function obj = Environment(obj, A, B)
obj.A = A;
obj.B = B;
obj.a = Agent(); % Call the Agent constructor here
end
function act = call_agent(obj)
% Calling agent_function will automatically put a as the first argument
act = obj.a.agent_function(obj.A, obj.B, obj.V, obj.T);
end
function action = interact_with_agent(obj)
action = obj.call_agent();
end
end
end
classdef Agent < handle
properties (SetObservable = true)
action;
end
methods
% Create Constructor
function obj = Agent()
obj.action = [];
end
function action = agent_function(obj, A, B, v, t)
obj.action = A + v * t * ((B - A) / norm(B - A));
action = obj.action;
end
end
end
I don't know why you are using two function to use the property a.
It is possible to call the function agent_function directly in the function interact_with_agent.
Anyway if you really want to code this way, you should set the function call_agent as static using: methods (Static, Access = private). Like this, the only way to access to the property a will be to use the function interact_with_agent

Simulate 'this' pointer in 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

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.