Overloading subsasgn results in error when initializing an object array

2 views (last 30 days)
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

Answers (2)

Veda Upadhye
Veda Upadhye on 22 Aug 2017
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. on 11 Feb 2018
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

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!