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
0 个评论
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File 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!