使用另一个类的属性定义Matlab类

时间:2016-09-15 18:15:22

标签: matlab class oop

我试图通过定义Node类来在Matlab中构建神经网络(ANN)的类框架:

function NodeObject = Node(Input, Weights, Activation)

Features.Input      = [];
Features.Weights    = [];
Features.Activation = [];

Features.Input      = Input;
Features.Weights    = Weights;
Features.Activation = Activation;

NodeObject = class(Features, 'Node');

此处输入是整数(预期输入数),Weights是长度为Features.Input的向量,Features.Activation是一个引用存储在方法中的激活函数的字符串。

接下来我要做的是构建一个节点的单元格数组,并根据这个数组定义一个Network类:

function Architecture = Network(NodeArray) 

ANN.Layers      = []; % Number of layers in architecture
ANN.LayerWidths = []; % Vector of length ANN.Layers containing width of each layer
ANN.NodeArray   = []; % Original input is cell array with layers in ascending order (input at top, output at bottom) with nodes in each row.
ANN.InputSizes  = [];

% Find number of layers
ANN.Layers = length(NodeArray(:,1));

% Find width of each layer
Widths = zeros(ANN.Layers,1);
for i = 1:length(Widths)
    Widths(i) = length(NodeArray(:,i));
end
ANN.LayerWidths = Widths;

% Pass NodeArray to Network class
ANN.NodeArray = NodeArray;

% Construct cell of input sizes
InputSizes = [];
for i = 1:ANN.Layers
    for j = 1:Widths(i)
        InputSizes(i,j) = NodeArray{i,j}.Inputs;
    end
end

ANN.InputSizes = InputSizes;



Architecture = class(ANN, 'Network');

属性ANN.InputSizes尝试从Node对象中提取属性,但我的代码不允许我这样做。如何修改此问题,或者您是否一起推荐针对此问题的不同架构?目前,我的课程NodeNetwork包含在两个单独的目录中,但我感觉还有其他我没有看到的内容。作为参考,我绝对没有OOP的经验,而且从我收集的内容看来,Matlab似乎并不是实现这些结构的最佳环境。目前虽然我没有足够的经验来用另一种语言实现这种类型的框架。

1 个答案:

答案 0 :(得分:4)

您的InputSizes不是一个单元格。您将其初始化为double数组([]),然后将其填充。如果要将其定义为单元格,则应执行类似

的操作
InputSizes = cell();
for i = 1:ANN.Layers
    for j = 1:Widths(i)
        InputSizes{i,j} = NodeArray{i,j}.Inputs;
    end
end

所有这一切,您应该真正考虑使用classdef文件定义您的类,因为它更直接。

<强> Node.m

classdef Node < handle

    properties
        Inputs
        Weights
        Activation
    end

    methods
        function obj = Node(inputs, weights, activation)
            obj.Inputs = inputs;
            obj.Weights = weights;
            obj.Activation = activation;
        end
    end
end

<强> Network.m

classdef Network < handle
    properties
        NodeArray
    end

    properties (Dependent)
        Layers
        LayerWidths
        InputSizes          
    end

    methods
        function obj = Network(nodes)
            obj.NodeArray = nodes;
        end

        function result = get.Layers(obj)
            result = size(obj.NodeArray, 1);
        end

        function result = get.LayerWidths(obj)
            result = size(obj.NodeArray, 2);
        end

        function result = get.InputSizes(obj)
            result = arrayfun(@(x)x.Inputs, obj.NodeArray, 'uniformoutput', 0);
        end
    end
end

就建议更好的布局而言,这取决于个别开发者的意见。