property access of objects arrays
16 ビュー (過去 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 で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!