gpt4 book ai didi

MATLAB - 创建对变量的引用(句柄?)

转载 作者:太空宇宙 更新时间:2023-11-03 19:18:23 24 4
gpt4 key购买 nike

假设我有以下类(class):

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

假设我实例化了这个类的一个实例,然后稍微操作它然后复制它。由于它是句柄类,“副本”实际上只是相同对象的另一个实例:

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

但我想观看 A 而无需实例化 myClass。天真地做着

>> value = w.A

不起作用,因为这只是复制值; changning w.A 以后不会改变 value

有没有一种方法可以为 w.A 提供“指针”或“引用”而无需创建单独的句柄类?我宁愿保留符号 w.A 而不是类似 w.A.value 的符号(我必须创建句柄类来包含该值)。

编辑:我使用此功能是为了帮助封装我的代码以供我的研究实验室使用。我正在设计 MATLAB 和 Arduino 之间的接口(interface)来控制空中和地面车辆;我希望访问诸如“vehicle.pwmMax”、“vehicle.flightCeiling”等内容来封装底层对象:“vehicle.Globals.pwmMax .value”等

最佳答案

您可以使用 PropertyReference 类来做到这一点

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:

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

PropertyReference 类的使用有点尴尬,但原始类保持不变。

编辑 - 根据 strictrude27 评论添加 disp 函数重载

关于MATLAB - 创建对变量的引用(句柄?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7085588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com