Not able to assign a value to a member of class in MATLAB
7 views (last 30 days)
Show older comments
Below is the class definition and I want to change obj.inputs by using setInputs method:
classdef LinearLayer
%UNTITLED2 Summary of this class goes here
% Detailed explanation goes here
properties
weights = [];
bias = [];
inputs = [];
end
methods
function obj = LinearLayer(weights,bias)
%UNTITLED2 Construct an instance of this class
% Detailed explanation goes here
obj.weights = weights;
obj.bias = bias;
end
function obj = setInputs(obj,inputArg)
obj.inputs = inputArg;
end
function outputArg = forward(obj,inputArg)
%METHOD1 Summary of this method goes here
% Detailed explanation goes here
% obj.setInputs(inputArg);
outputArg = obj.weights*inputArg+obj.bias;
end
function [outputArg,dweight,dbias] = backward(obj,inputArg)
outputArg = inputArg*obj.weights;
dweight = - (inputArg')*(obj.x');
dbias = -inputArg';
end
end
end
The main script is:
weights = [-1,-2,0,1,2;...
-2,-1,1,2,3];
bias = [-1;1];
linearlayer = LinearLayer(weights,bias);
inputs = [1,2,3,4,5]';
linearlayer.setInputs(inputs);
After running the main script, linearlayer.inputs = [] instead of [1;2;3;4;5]
0 Comments
Accepted Answer
Steven Lord
on 6 May 2022
Your class is a value class rather than a handle class. This documentation page discusses the differences between the two.
You've written your setInputs method so it returns the modified object, but your call to setInputs has no output argument and so the modified object it returns is discarded. You could call:
linearlayer = linearlayer.setInputs(inputs);
and store the modified object back in the original variable. But unless the setInputs method was part of a "contract" that my class was trying to satisfy (some other function or class expected or required it to have that method) I'd probably just use indexing to update the property.
linearlayer.inputs = inputs;
0 Comments
More Answers (0)
See Also
Categories
Find more on Elementary Polygons in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!