property access of objects arrays
조회 수: 3 (최근 30일)
이전 댓글 표시
Create an object array and then try to access a public property of this array
C(1,1) = class1;
C(2,1) = class1;
C(1,2) = class1;
C(2,2) = class1;
%suppose class1 has a public property called 'a' , then :
C.a % returns C(1,1).a
[o1 o2 o3 o4] = C.a %returns o1 = C(1,1).a, o2 = C(2,1).a, o3 = C(1,2).a and o4 = C(2,2).a
[C.a] %returns [C(1,1).a C(2,1).a C(1,2).a C(2,2).a]
when you look at the above its looks like it acts as a method, where the 'a' property is called for each of the elements of the array. But I cant understand the last statement [C.a] .
When working with a normal function, putting square brackets around a function call does not make it return more than 1 output (if you call it without more than one output argument), but in this case it does. So this is not exactly a function call either.
Can anyone explain whats going on here
댓글 수: 0
답변 (2개)
Daniel Shub
2012년 2월 15일
A potentially related question: http://www.mathworks.com/matlabcentral/answers/12116-cell-array-expansion
댓글 수: 0
Titus Edelhofer
2012년 2월 15일
Hi Johhny,
the [] work here similar to accessing a field of a structure. There it is easy to explain using "comma seperated lists". Suppose you have the following structure:
x(1).a = 1;
x(2).a = 2;
Now if you access a via
x.a
this is treated by MATLAB as if you typed
x(1).a, x(2).a
Now if you combine using [], you get a vector:
y = [x(1).a x(2).a]
% or shorter
y = [x.a]
This is the same as for your class ...
Same by the way for strings and cells:
x(1).b = 'Hello';
x(2).b = 'MATLAB';
z = {x.b}
Titus
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!