MATLAB - create reference (handle?) to variable

Dang Khoa picture Dang Khoa · Aug 16, 2011 · Viewed 7.6k times · Source

Suppose I have the following class:

classdef myClass < handle
    properties
        A = 1
    end
    methods
        function obj = myClass(val)
            obj.A = val;
        end
    end
end

Say I instantiate an instance of this class, then manipulate it slightly and then copy it. As it's a handle class, the "copy" is really just another instance of the same object:

>> q = myClass(10);
>> q.A = 15;
>> w = q;
>> disp(w.A)
   15

But I would like to watch A without needing to instantiate myClass. Naively doing

>> value = w.A

doesn't work, since this just copies the value; changning w.A later on will not change value.

Is there a way to provide a "pointer" or "reference" to w.A without having to create a separate handle class? I'd rather keep the notation w.A rather than something like w.A.value (with me having to create the handle class to contain that value).

EDIT: I am using this functionality in order to help encapsulate my code for use with my research lab. I am designing an interface between MATLAB and Arduino to control air and ground vehicles; I was hoping to access stuff like "vehicle.pwmMax", "vehicle.flightCeiling", etc, to encapsulate the underlying object: "vehicle.Globals.pwmMax.value", etc.

Answer

grantnz picture grantnz · Aug 17, 2011

You could do this by with a PropertyReference class

classdef PropertyReference < handle
    %PropertyReference Reference to a property in another object    
    properties
        sourceHandle
        sourceFieldName
    end

    properties (Dependent = true)
         Value
    end

    methods                
        function obj = PropertyReference (source, fieldName)            
            obj.sourceHandle = source;
            obj.sourceFieldName = fieldName
        end
        function value = get.Value( obj )
            value = obj.sourceHandle.(obj.sourceFieldName);
        end

        function set.Value( obj, value )
            obj.sourceHandle.(obj.sourceFieldName) = value;
        end
        function disp( obj )
            disp(obj.Value);
        end
    end              
end

Continuing your example, you could then use PropertyReference as follows:

q = myClass(10);
>> q.A = 15;
>> ref = PropertyReference(q,'A');
>> disp(ref)
   15
>> q.A = 42;
>> disp(ref)
   42

Usage of the PropertyReference class is a bit awkward but the original class remains unchanged.

EDIT - Added disp function overload as per strictlyrude27 comment