Showing posts with label structure array. Show all posts
Showing posts with label structure array. Show all posts

Friday, June 19, 2009

Brackets for structure arrays in MATLAB

Structure array is a common type of data used in MATLAB. To deal with it, brackets are used extensively. However, when to use the correct brackets- ( ) and [ ]? Sometimes this can be confusing. Here is a summary about them.

Suppose we have structure arrays
a.b =[1 2; 3 4]
and
c(1).b =[1 2], c(2).b =[3 4].

>> a.b= [1 2; 3 4]
a =
b: [2x2 double]
>> c(1).b =[1 2]
c =
b: [1 2]
>> c(2).b =[3 4]
c =
1x2 struct array with fields:
b
Now, let's try ( ) on both of them.
>> (a.b)
ans =
1 2
3 4
>> (c.b)
ans =
1 2
ans =
3 4

and [ ]
>> [a.b]
ans =
1 2
3 4
>> [c.b]
ans =
1 2 3 4

Through the example, it is easy to see the difference. If we also have d ='more', what will happen if we type c(1).(d) =1?
>> c(1).(d) =1
c =
1x2 struct array with fields:
b
more
Thus ( ) can be used to create dynamic field names. So far, { } haven't been mentioned because this pair of curly braces are mostly for cells.