필터 지우기
필터 지우기

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

조회 수: 11 (최근 30일)
Henning Wilhelm
Henning Wilhelm 2017년 11월 6일
댓글: Walter Roberson 2021년 1월 26일
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
Rik
Rik 2017년 11월 6일
Playing around with struct2cell or struct2table could probably solve this.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2017년 11월 6일
a = structfun(@(F) F(1:100,:), b, 'uniform', 0)
  댓글 수: 4
Rik
Rik 2021년 1월 26일
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 2021년 1월 26일
Anonymous functions are more expensive than plain function handles such as @sin

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by