Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
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.

Réponse acceptée

Stephen23
Stephen23 le 8 Juin 2022
Modifié(e) : Stephen23 le 8 Juin 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 commentaires
Darren Woods
Darren Woods le 9 Juin 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).
Stephen23
Stephen23 le 9 Juin 2022
@Darren Woods: please remember to accept my answer if it helped you!

Connectez-vous pour commenter.

Plus de réponses (1)

Matt J
Matt J le 8 Juin 2022
Modifié(e) : Matt J le 8 Juin 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 commentaire
Darren Woods
Darren Woods le 8 Juin 2022
Modifié(e) : Darren Woods le 8 Juin 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur MATLAB Compiler dans Help Center et File Exchange

Tags

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by