How does a 'network' object act as a function when performing forward propagation?

I'm using the Neural Network Toolbox. Let us create a dummy network, called net:
input = 1:10;
net = feedforwardnet(5);
net = trainlm(net, input, 2*input);
This network is an object of class network, as evidenced by the class command:
class(net)
ans =
network
What is happening, then, when I perform forward propagation using the following command?
output = net(input);
How am I passing an argument into an object, and not a function? What is happening here? Is this some clever trick, or am I missing something really obvious? How do I replicate this in a custom-made class?
Thank you.

 Accepted Answer

Indexing into an object A invokes particular methods on that object if they exist.
y = A(indices) % subsref
A(indices) = z % subsasgn
Most commonly, subsref extracts elements from an array. But as a class author you could theoretically do whatever you wanted in your overload of subsref for your class. The Neural Network Toolbox developers have overloaded subsref for their class to simulate the network using the "indices" as input data.
As a simpler example that does something similar, look at the DocPolynom example in the object-oriented programming documentation, particularly the implementation of its subsref method. The case in that code for '()' uses polyval to evaluate the polynomial using the coefficients stored in the object.

1 Comment

Perfect answer, thank you!
Some code for future reference. The () operator is overloaded, but the . operator is left with its default behavior so it remains possible to call methods like so: myObject.myMethod(input). There's some hackery involved in maintaining the default behavior of the . operator -- I'm not certain it works flawlessly, but I haven't managed to make it fail in my tests.
classdef MyClass
properties
x;
end
methods
function self = MyClass(x)
self.x = x;
end
function output = myMethod(self, input)
output = self.x * input;
end
function output = subsref(self, inputStruct)
switch inputStruct(1).type
case '()'
input = inputStruct.subs{:};
output = self.myMethod(input);
case '.'
c = class(obj);
n = nargout(strcat(c, '>', c, '.', s(1).subs));
[varargout{1:n}] = builtin('subsref', obj, s);
end
end
end
end
Example usage:
obj = MyClass(7);
% You can still use the '.' operator to call methods
obj.myMethod([1 2 3])
ans =
7 14 21
% But now you can call a method implicitly
obj([1 2 3])
ans =
7 14 21

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!