MATLAB: Vertcat of values stored in structure

MATLABoopvertcat

I prepared this simple classdef.
classdef myclassA
properties
prop
end
methods
function obj = myclassA(val)
obj.prop = val;
end
function out = horzcat(varargin)
disp('horzcat was invoked');
out = builtin('horzcat',varargin{:});
end
function out = vertcat(varargin)
disp('vertcat was invoked');
out = builtin('vertcat',varargin{:});
end
end
end
Then I performed concatenation of objects.
>> obj1 = myclassA(1);
>> obj2 = myclassA(2);
>> [obj1,obj2]
horzcat was invoked
ans =
1x2 myclassA array with properties:
prop
>> [obj1;obj2]
vertcat was invoked
ans =
2x1 myclassA array with properties:
prop
So far so good. However, when I put the same objects into a structure, I've got rather unexpected behaviours of vertcat.
>> S.obj1 = obj1;
>> S.pbj2 = obj2;
>> [S.obj1,S.obj2]
horzcat was invoked
ans =
1x2 myclassA array with properties:
prop
>> [S.obj1;S.obj2]
horzcat was invoked
horzcat was invoked
vertcat was invoked
ans =
2x1 myclassA array with properties:
prop
Here, the two objects were processed by horzcat twice and then by vertcat once. I wonder if this is expected behaviour (I doubt it) or it is a bug.
When I used vertcat explicitly rather than [a;b], I obtained results in a expected way.
>> vertcat(S.obj1,S.obj2)]
vertcat was invoked
ans =
2x1 myclassA array with properties:
prop
MATLAB R2015b, on Mac OS X El Capitan

Best Answer

When you use S.obj1 then it needs to do structure expansion [S(1).obj1, S(2).obj1, S(3).obj1, ... S(end).obj1)] and that is where the horzcat comes from. If you had used S(1).obj1 then horzcat would not have been invoked because there would be no structure expansion.
When there is only one object in the structure it does seem to be a waste to go through structure expansion. I do not know if there is some subtle reason that it must do so, but that is what appears to be happening.