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

1 次查看(过去 30 天)
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.

采纳的回答

Stephen23
Stephen23 2022-6-8
编辑:Stephen23 2022-6-8
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 个评论
Darren Woods
Darren Woods 2022-6-9
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).

请先登录,再进行评论。

更多回答(1 个)

Matt J
Matt J 2022-6-8
编辑:Matt J 2022-6-8
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 个评论
Darren Woods
Darren Woods 2022-6-8
编辑:Darren Woods 2022-6-8
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB Compiler 的更多信息

标签

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by