MATLAB Answers


property access of objects arrays

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

  0 件のコメント

サインイン to comment.


2 件の回答

Daniel Shub
回答者: Daniel Shub
2012 年 2 月 15 日

  0 件のコメント

サインイン to comment.

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
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}

  1 件のコメント

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

サインイン to comment.

Translated by