MATLAB-创建变量的引用(句柄?) [英] MATLAB - create reference (handle?) to variable
问题描述
假设我有以下课程:
classdef myClass < handle
properties
A = 1
end
methods
function obj = myClass(val)
obj.A = val;
end
end
end
说我实例化该类的一个实例,然后对其进行轻微的操作,然后将其复制.因为是句柄类,所以复制"实际上只是 same 对象的另一个实例:
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
但是我想观看A
而无需实例化myClass.天真地做
But I would like to watch A
without needing to instantiate myClass. Naively doing
>> value = w.A
不起作用,因为这只会复制值;以后更改w.A
不会更改value
.
doesn't work, since this just copies the value; changning w.A
later on will not change value
.
有没有一种方法可以为w.A
提供指针"或引用"而不必创建单独的句柄类?我宁愿保留符号w.A
而不是w.A.value
之类的东西(我必须创建包含该值的handle类).
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).
我正在使用此功能是为了帮助封装我的代码以供我的研究实验室使用.我正在设计MATLAB和Arduino之间的接口,以控制空中和地面车辆;我希望访问诸如"vehicle.pwmMax
","vehicle.flightCeiling
"等之类的东西,以封装基础对象:"vehicle.Globals.pwmMax.value
"等.
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.
推荐答案
您可以使用PropertyReference类
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
继续您的示例,然后可以按如下方式使用PropertyReference:
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
PropertyReference类的用法有点尴尬,但原始类保持不变.
Usage of the PropertyReference class is a bit awkward but the original class remains unchanged.
编辑-根据strictrude27注释添加了disp函数重载
EDIT - Added disp function overload as per strictlyrude27 comment
这篇关于MATLAB-创建变量的引用(句柄?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!