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

2 ビュー (過去 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).
Stephen23
Stephen23 2022 年 6 月 9 日
@Darren Woods: please remember to accept my answer if it helped you!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeMATLAB Compiler についてさらに検索

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by