Overloading subsasgn results in error when initializing an object array

2 次查看(过去 30 天)
Good day
I have made a class in which I overload the subsasgn method.
classdef dummyClass
properties
A = [1, 2]
end
%%overload subsasgn
methods
function obj = subsasgn(obj, s, varargin)
% subsasgn is overloaded to incorporate some verifications
%%TODO some verifications
%%execute the assignment
% call the builtin with the same arguments
obj = builtin('subsasgn', obj, s, varargin{:});
%%TODO some more verifications
end
end
end
Then I want to initialize an array of dummyClass objects using the following code
clear all
dummyArray(3, 2) = dummyClass()
This gives the following error message:
Error using subsasgn
The following error occurred converting from dummyClass to double:
Error using double
Conversion to double from dummyClass is not possible.
Error in dummyClass/subsasgn (line 15)
obj = builtin('subsasgn', obj, s, varargin{:});
How can I overload the subsasgn method such that the given assignment does not result in an error?
Kind regards
Boudewijn Verhaar

回答(2 个)

Veda Upadhye
Veda Upadhye 2017-8-22
Hi,
It looks like the overloaded "subsasgn" function is being called on initialization of your "dummyClass" objects. The overloaded function "subsasgn" will need to address this kind of assignment in your code. The documentation below includes a code pattern for such scenarios. You may find it useful to follow a similar pattern.
https://www.mathworks.com/help/matlab/matlab_oop/code-patterns-for-subsref-and-subsasgn-methods.html#bu7rrmd
I hope this helps!
Veda

Steffen M.
Steffen M. 2018-2-11
Hi,
in your case the subsasgn function is called at the beginning with an object from type double. If you insert a constructor call it should work.
function obj = subsasgn(obj, s, varargin)
if isnumeric( obj), obj = dummyClass(); end
% call the builtin with the same arguments
obj = builtin('subsasgn', obj, s, varargin{:});
end
Kind regards Steffen

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by