vertcat of values stored in structure

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

采纳的回答

Walter Roberson
Walter Roberson 2015-11-16
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.
  1 个评论
Kouichi Nakamura
Kouichi Nakamura 2015-11-16
Oh, thanks a lot. This explains everything. MATLAB assumes S may be non-scalar structure! I thought obj1 and S.obj1 were equivalent and felt that behaviour was weird.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by