Borrar filtros
Borrar filtros

How do you iterate over multiple fields in a structure?

43 visualizaciones (últimos 30 días)
Anwesh Saha
Anwesh Saha el 21 de En. de 2023
Editada: Stephen23 el 21 de En. de 2023
I have a 1X1 struct with 48 fields in it. Each field is 1X5120 int 32. I want to downsample each of these fields using the downsample(y, n) function.
However, I would like to accomplish this using a loop. How can it be done?
  1 comentario
Stephen23
Stephen23 el 21 de En. de 2023
Editada: Stephen23 el 21 de En. de 2023
You could make this task easier by improving the data design.
Numbered fieldnames (or variable names) like that is usually a sign that you are doing something wrong.
Rather than forcing meta-data (e.g. pseudo-indices) into the fieldnames like you are doing, your data would be much better stored in a non-scalar structure or a simple cell array. Then you can use basic indexing to loop over the data.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 21 de En. de 2023
Editada: Stephen23 el 21 de En. de 2023
One approach is to use FIELDNAMES() and dynamic fieldnames:
For example, where S is your scalar structure:
n = 5;
C = fieldnames(S);
for k = 1:numel(C)
F = C{k};
A = S.(F);
B = downsample(A,n);
S.(F) = B;
end
Another simple option is to use STRUCTFUN():
For example:
n = 5;
fnh = @(v) downsample(v,n);
S = structfun(fnh, S)

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by