How to extract some values from a structure?

1 visualización (últimos 30 días)
Benson Gou
Benson Gou el 10 de Jun. de 2021
Comentada: Benson Gou el 10 de Jun. de 2021
Dear All,
I have a structure A which has several fields. Each field has 100 values. I want to extract the first 20 values from each field and save them in a structure B. I tried to use the following code:
B = A(1:20).
It does not work. Would you please tell me how I can get structure B?
Thanks.
Benson

Respuesta aceptada

Stephen23
Stephen23 el 10 de Jun. de 2021
Assuming that structure A is scalar (so far you did not tell us this important information):
A.x = randi(9,1,100);
A.y = randi(9,1,100);
A.z = randi(9,1,100)
A = struct with fields:
x: [4 9 2 1 1 1 7 2 2 2 9 2 7 4 9 7 4 8 8 1 3 4 1 7 1 8 6 5 2 3 3 5 7 3 3 8 3 8 8 6 7 9 7 2 9 2 3 4 1 6 4 6 7 9 2 6 7 9 1 7 6 7 2 9 5 5 6 8 3 5 3 2 1 7 9 3 4 1 1 6 1 8 1 8 5 3 5 3 1 1 8 5 7 2 7 5 6 9 9 4] y: [8 9 7 2 1 9 6 6 7 1 9 9 6 7 1 8 2 5 5 4 7 7 7 2 6 6 6 3 6 4 6 1 6 1 6 2 3 2 5 5 1 7 5 2 9 5 6 5 6 8 7 1 6 8 9 5 4 8 5 4 8 8 8 6 3 8 2 5 4 6 6 2 6 4 4 5 4 8 3 8 3 8 6 5 3 3 6 5 7 8 2 1 1 6 7 2 3 5 3 6] z: [8 9 8 7 3 5 4 8 4 3 2 3 2 2 6 1 4 3 4 8 5 9 4 1 6 1 2 5 9 5 2 2 2 3 3 2 6 1 2 4 8 5 2 4 8 3 5 1 7 3 3 5 5 9 1 9 8 9 5 1 1 1 1 6 5 4 2 3 1 9 8 1 8 1 3 8 5 5 9 7 5 5 6 2 7 5 2 8 3 2 9 8 1 7 5 2 9 6 6 6]
fun = @(v)v(1:20);
B = structfun(fun,A,'uni',0)
B = struct with fields:
x: [4 9 2 1 1 1 7 2 2 2 9 2 7 4 9 7 4 8 8 1] y: [8 9 7 2 1 9 6 6 7 1 9 9 6 7 1 8 2 5 5 4] z: [8 9 8 7 3 5 4 8 4 3 2 3 2 2 6 1 4 3 4 8]

Más respuestas (0)

Categorías

Más información sobre Oceanography and Hydrology en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by