【问题标题】:Matlab OOP array of objects classMatlab OOP 对象类数组
【发布时间】:2017-05-11 17:25:20
【问题描述】:

我想了解 Matlab 如何处理数组对象。我已经阅读了几篇关于这个主题的帖子和 Matlab 帮助,但我仍然不完全理解。

让我们来看一个用例:我想管理多个测量通道(通道的数量可能会有所不同)。每个测量通道都是一个具有多个属性的对象。现在我想要一个类来处理频道(channelHandler.m)。在这个类中,我可以简单地向数组添加一个新通道(稍后可能会有无聊的功能)。

所以到目前为止我已经尝试过:

1) 创建measurementChannel.m 类 在构造函数中,到目前为止我只设置了频道名称,没有数据。

classdef measurementChannel
%CHANNEL holds an instance of a single channel

properties
    channelData
    channelName = strings
    channelUnit = strings
    channelDataLength    
    channelOriginMeasurementFile
end

methods
    function obj = channelTest(channelName)
        if nargin > 0
            obj.channelName = channelName;
        end
    end
end  

结束

为了测试这个类,我尝试了这个:

channel(1) = measurementChannel('channelA');
channel(2) = measurementChannel('channelB');
channel(1).channelName
channel(2).channelName

效果很好。

2) 现在我已经创建了 channelHandler 类:

classdef channelHandler

properties (Access = public)
    channelArray
end

methods (Access = public)

    function addChannel(obj, Name)

        testobj = measurementChannel();

        testobj.channelName = Name;

        obj.channelArray = [obj.channelArray testobj];

    end

end

并使用以下命令访问它:

createChannels = channelHandler();

createChannels.addChannel('channel1');
createChannels.addChannel('channel2');

createChannels.channelArray(1).channelName
createChannels.channelArray(2).channelName

这会失败,因为 channelArray 没有被定义为数组,并且会在访问 channelArray(2) 时出错。 所以我也尝试初始化数组(但我需要知道通道的数量)。

所以我的问题是: a) 我真的需要初始化一个对象数组吗? b) 如何修复 channelHandler 类以将对象添加到数组中?

【问题讨论】:

    标签: arrays matlab oop


    【解决方案1】:

    问题是你没有继承from the handle class and therefore the modifications made within addChannel alter a copy of your object rather than the object itself。如果你继承自handle,你粘贴的代码就可以正常工作。

    classdef channelHandler < handle
    

    【讨论】:

    • 只是为了我的理解:如果我使用句柄类,只有对对象的引用存储在channelArray中。为什么不能将数据本身存储在 channelArray 中?
    • @Christoph 引用存储在数组中,但这实际上与存储在channelArray 中的数据本身相同。这意味着如果您将其分配给不同的变量并对其进行修改,则该更改将反映在原始对象中。
    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2014-02-05
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多