MATLAB Answers

# Accessing data in nested structure arrays

21 views (last 30 days)
Tim Baur on 26 Feb 2021
Edited: Stephen Cobeldick on 26 Feb 2021
Hi everyone,
I'm trying to access data which is nested in a structure array with multiple subfields.
I tried getfield, extractfield and multiple ways to directly access what I need
Example with what I can access easily:
a.b(1).c.d = [1 2 3];
a.b(2).c.d = [3 4 5];
a.b(3).c.d = [5 6 7];
% Direct access
>> [a.b(1).c.d]
ans =
1 2 3
% Field extraction
>> extractfield(a.b(1).c,'d')
ans =
1 2 3
% Field extraction >> only at level below array
>> extractfield(a.b,'c')
ans =
1×3 cell array
{1×1 struct} {1×1 struct} {1×1 struct}
What I' missing now is something like this which results in a vector of the first elements of d for all array entries of b (>> [1 3 5])
[a.b(:).c.d(1)]
>> [1 3 5]
Looking forward to your answers and thanks in advance!
Tim
##### 1 CommentShowHide None
Stephen Cobeldick on 26 Feb 2021
"Direct access": the square brackets are superfluous because you are not concatenating anything. Get rid of them.
a.b(1).c.d = [1,2,3];
a.b(2).c.d = [3,4,5];
a.b(3).c.d = [5,6,7];
a.b(1).c.d % square brackets removed
ans = 1×3
1 2 3

Sign in to comment.

### Accepted Answer

Stephen Cobeldick on 26 Feb 2021
Edited: Stephen Cobeldick on 26 Feb 2021
a.b(1).c.d = [1,2,3];
a.b(2).c.d = [3,4,5];
a.b(3).c.d = [5,6,7];
Either
V = arrayfun(@(s)s.c.d(1),a.b)
V = 1×3
1 3 5
Or
tmp = [a.b.c]; % comma-separated list -> concatenate scalar structures
tmp = vertcat(tmp.d); % comma-separated list -> concatenate numeric vectors
V = tmp(:,1)
V = 3×1
1 3 5
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

R2020a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!