필터 지우기
필터 지우기

vertcat of values stored in structure

조회 수: 2 (최근 30일)
Kouichi Nakamura
Kouichi Nakamura 2015년 11월 16일
댓글: Kouichi Nakamura 2015년 11월 16일
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