How can i access field values of a struct by indexing?

13 visualizaciones (últimos 30 días)
My struct has several fields containing a matrix. How can I get the first 100 values of each field without using a for loop.
a = b.(fieldnames(b))(1:100,:); % wont work
  1 comentario
Rik
Rik el 6 de Nov. de 2017
Playing around with struct2cell or struct2table could probably solve this.

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 6 de Nov. de 2017
a = structfun(@(F) F(1:100,:), b, 'uniform', 0)
  4 comentarios
Rik
Rik el 26 de En. de 2021
That is true in general. The best you can hope for is parity (given proper pre-allocation). Every function that hides a loop (cellfun, arrayfun, etc) will have an overhead. Matlab is getting better and better at for-loops.
The only exception to this rule is if you have actual array operations:
%slow:
s=0;for n=1:numel(data),s=s+data(n);end
%fast
s=sum(data);
Walter Roberson
Walter Roberson el 26 de En. de 2021
Anonymous functions are more expensive than plain function handles such as @sin

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by