Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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.

Respuesta aceptada

Stephen23
Stephen23 el 8 de Jun. de 2022
Editada: Stephen23 el 8 de Jun. de 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 comentarios
Darren Woods
Darren Woods el 9 de Jun. de 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).

Iniciar sesión para comentar.

Más respuestas (1)

Matt J
Matt J el 8 de Jun. de 2022
Editada: Matt J el 8 de Jun. de 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 comentario
Darren Woods
Darren Woods el 8 de Jun. de 2022
Editada: Darren Woods el 8 de Jun. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre MATLAB Compiler en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by