Not able to assign a value to a member of class in MATLAB

6 次查看(过去 30 天)
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]

采纳的回答

Steven Lord
Steven Lord 2022-5-6
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 个)

类别

Help CenterFile Exchange 中查找有关 Elementary Polygons 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by