0

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]
3
  • 1
    Something like X = [S.x] ? Commented Feb 20, 2015 at 19:18
  • @Benoit_11 Brilliant, please submit it as an answer so I can accept it. I had tried S.x but was missing the enclosing square brackets. Commented Feb 20, 2015 at 19:19
  • Alright haha glad it worked! I'l add a bit more details then :) Commented Feb 20, 2015 at 19:21

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I'm going to be cheeky and ask if you also know how to do the reverse, i.e. given X, set all s.x in S respectively. I tried [S.x] = X but I get "too many output arguments".
I think the function deal is what you need: S.x = deal(X). Is that the case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.