MGA
MGA

Reputation: 1668

MATLAB vectorization: extracting vector of struct fields from vector of structs

I have a vector S of structs s, each struct having a field x.

I would like to extract the vector X containing the value x from each struct in S.

Is there a way to do this with vectorization?

Example:

s1.x = 42;
s2.x = 87;
s3.x = 24;

S = [s1, s2, s3];

I want to get:

X = [42, 87, 24]

Upvotes: 0

Views: 99

Answers (1)

Benoit_11
Benoit_11

Reputation: 13945

You can use square brackets to concatenate the content of the field x of the structure as follows:

X = [S.x]

which puts every data associated with the field x in a single array.

You could also use the cat function to concatenate horizontally:

X = cat(2,S.x)

Upvotes: 2

Related Questions