I have a class that assigns an immutable UUID to an object in its constructor. The following is a simplified example:
classdef mytest properties (GetAccess = public, SetAccess = immutable) uuid end properties val end methods function obj = mytest(valIn) obj.uuid = char(java.util.UUID.randomUUID.toString); if nargin < 1 valIn = 0; end obj.val = valIn; end end end
This works fine overall, but I just discovered a problem with the behavior of MATLAB when assigning default elements to an array. I suggested that if I typed
>> a(5) = mytest(2);
the constructor will be called 5 times - 4 times without input arguments to populate the default elements from 1 to 4 from the array and once with an input argument of 2 to assign the final element.
However, this is not what MATLAB does - instead, it calls the constructor only once without inputs, and then copies the result four times to populate elements 1 through 4 (and then, as expected for the final element). This means that UUIDs ef elements 1 through 4 end in the same way:
>> {a.uuid}' ans = '4424b91b-0977-4b4c-b18b-c4564875b952' '4424b91b-0977-4b4c-b18b-c4564875b952' '4424b91b-0977-4b4c-b18b-c4564875b952' '4424b91b-0977-4b4c-b18b-c4564875b952' 'dbb8d862-8a1c-4bf9-876f-ef786e11a896'
It turns out this is a documented behavior that I just did not expect, and I understand why MathWorks chose this for this (you may not need the overhead of calling the constructor without input many times separately).
But this is not the behavior that I want for this class. Does anyone know how to make the calling constructor be called for each element? Or maybe you can suggest a different class design that will have the desired behavior?
PS I investigated whether MATLAB can copy these elements by default using the copy method - in this case, inheriting my class from matlab.mixin.Copyable and overriding copyElement behavior can help - but it doesn't seem like copying does this: (.
source share