property access of objects arrays

18 vues (au cours des 30 derniers jours)
johhny boy
johhny boy le 15 Fév 2012
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

Réponses (2)

Daniel Shub
Daniel Shub le 15 Fév 2012

Titus Edelhofer
Titus Edelhofer le 15 Fév 2012
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 commentaire
johhny boy
johhny boy le 16 Fév 2012
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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by