property access of objects arrays

조회 수: 3 (최근 30일)
johhny boy
johhny boy 2012년 2월 15일
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

답변 (2개)

Daniel Shub
Daniel Shub 2012년 2월 15일

Titus Edelhofer
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
  댓글 수: 1
johhny boy
johhny boy 2012년 2월 16일
OK, fair enough. Does this mean that if it is a 2x2 structure
x(1,1).a = 1;
x(1,2).a = 2;
x(2,1).a = 3;
x(2,2).a = 4;
So should x.a mean
x(1).a, x(2).a, x(3).a, x(4).a

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by