How to remove a range of rows from all nested structures of a parent structure?

2 views (last 30 days)
Hi,
Imagine a 1x1 structure that contains a series of 10 structures that each contain 20x1 doubles. Is there a programmatic way to reduce all of these 10 structures to contain only 1 double, that being the first row's double in each case. In the end I would have 1x1 structure that contains 10 structures that each contain 1 double each.
Many thanks,
Darren.

Accepted Answer

Stephen23
Stephen23 on 8 Jun 2022
Edited: Stephen23 on 8 Jun 2022
s.a.fa = [1,2,3];
s.a.fb = [7,8,9];
s.a.fn = [4,5,6];
s.a
ans = struct with fields:
fa: [1 2 3] fb: [7 8 9] fn: [4 5 6]
s.a = structfun(@(v)v(1),s.a, 'uni',0);
s.a
ans = struct with fields:
fa: 1 fb: 7 fn: 4
  2 Comments
Darren Woods
Darren Woods on 9 Jun 2022
Hi Stephen,
Thanks for your assistance. This works perfectly for me.
To add some explanation for the curious reader, @(v)v(1) is taking each field within the structure and returning the first value. This works in my case on fields of [x,y double]. Further, if you wanted the full first row of each field, then you would use @(v)v(1,:). The comma,separated pair 'uni',0 specifies that the returned output can have any data type (the alternative is that the function has to return a column vector of scalars, e.g. the max value of each field, or the average value of each field, etc).

Sign in to comment.

More Answers (1)

Matt J
Matt J on 8 Jun 2022
Edited: Matt J on 8 Jun 2022
s.a.f=[1,2,3];
s.b.f=[4,5,6];
s.a,s.b
ans = struct with fields:
f: [1 2 3]
ans = struct with fields:
f: [4 5 6]
for F=string(fieldnames(s)')
s.(F)=structfun(@(f)f(1), s.(F),'uni',0);
end
s.a,s.b
ans = struct with fields:
f: 1
ans = struct with fields:
f: 4
  1 Comment
Darren Woods
Darren Woods on 8 Jun 2022
Edited: Darren Woods on 8 Jun 2022
Thanks Matt,
In my case I have:
s.a.fa=[1,2,3];
...
s.a.fn=[4,5,6];
Actually I have s.a.fa = [10x1 double] and so on, and I want to loop through fa...fn with the logic you propose.
Running the solution above leads to the following output:
> Error using structfun
> Inputs to STRUCTFUN must be scalar structures.

Sign in to comment.

Categories

Find more on MATLAB Compiler in Help Center and File Exchange

Tags

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!