Extracting fields from struct arrays

From NA-Wiki

Jump to: navigation, search

Struct arrays are very powerful data structures in the Matlab language that give a small amount of object orientation if desired. However, they require some extra massaging before they become convenient to use. This article is about how to extract all values of a particular field from all array entries.

Say we have a struct array, s

s = 
1x4 struct array with fields:
    m1
    m2
    m3

The command s(1) will extract struct one from the struct array. But what if we want to get all values of m1 into another vector? We may do s.m1, but that gives (in this example where m1 is a scalar with random value)

> s.m1
ans =
    0.3955
ans =
    0.6099
ans =
    0.6490
ans =
    0.9203

The problem is that this is a list and not a vector (so doing a = s.m1 will not work). The solution is to use concatenation of the list into a matrix:

> a = [s.m1]
a =
    0.3955    0.6099    0.6490    0.9203

or if we want the values as a column vector

> a = cat(1,s.m1)
a =
    0.3955
    0.6099
    0.6490
    0.9203

The concatenation command will be different depending on the dimensions of the field one extracts.

Personal tools