1

Suppose I'm given a struct of arrays, e.g.:

s = 

foo: [3x3 double]
bar: [3x1 double]

Is there an easy way to extract a struct with the same field names as s and with each field populated by the ixth row of the same field in s? I can assume that every field has the same number of rows. Given the above, I could do

ix = 1;
s1.foo = s.foo(ix, :);
s1.bar = s.bar(ix, :);

But if s has more than a couple fields, this gets unwieldy. Is there a function that would do the equivalent, a la s1 = extractstruct(s, ix)?

2
  • In fact, it would be sweet to have a function fieldfun Commented Dec 11, 2011 at 21:55
  • @Oli, try structfun Commented Dec 12, 2011 at 0:08

1 Answer 1

1

It s not as short as s1 = extractstruct(s, ix), but I would do that:

s.foo = rand(3);
s.bar = rand(1,3);
xi=1;

s2=reshape([fieldnames(s)'; cellfun(@(x) x(xi,:),struct2cell(s)','UniformOutput',0)],1,[]);
s2=struct(s2{:})


s2 = 

    foo: [0.8147 0.9134 0.2785]
    bar: [0.7922 0.9595 0.6557]
Sign up to request clarification or add additional context in comments.

3 Comments

Should 'Un)],1,[]iformOutput' be 'UniformOutput'?
Also, to be exactly my problem, it should be s.bar = rand(3,1) so that it has the same number of rows. /nitpicky
This would be better with cell2struct rather than struct.

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.