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.

3 comments:

  1. hello... hapi blogging... have a nice day! just visiting here....

    ReplyDelete
  2. I have a question, i am relatively new at programming, so could someone please tell me why to use an empty matrix when using a for loop?

    ReplyDelete
  3. thanks! I was trying to remember the bracket syntax for extracting an array of field values from a struct array.

    ReplyDelete