# How to index every field of a structure and reassign to a structure with a single element in each field

조회 수: 42 (최근 30일)
John Petersen 2017년 3월 10일
답변: George Abrahams 2022년 12월 30일
I have a structure where every field is an array of the same length. I need to pass this structure on but only with a single element in each field. I thought of doing it this way
A.b = [1:10];
A.c = [2:11];
A.d = [3:12];
a = structfun(@(x) x(1),A)
but this results in
a = [1;2;3];
The answer I want for the first element is
a.b = 1;
a.c = 2;
a.d = 3;
I will want to run this in a for loop for use in the next function like this
for ii = 1:length(A.b)
...
a = structfun(@(x) x(ii),A); % but modified so that 'a' is a struct like 'A', not an array.
nextfcn(a);
...
end

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

### 채택된 답변

KSSV 2017년 3월 10일
A.b = [1:10];
A.c = [2:11];
A.d = [3:12];
a= A ;
for f=fieldnames(a)'
a.(f{1})(2:end)=[];
end
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
John Petersen 2017년 3월 10일
Thanks KSSV, Interesting approach. I just had to change the indexing so that I could keep the element I want.

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

### 추가 답변 (2개)

Alternatively, you could stick with the approach you were using, but include the 'uniformoutput',false option.
a = structfun(@(x) x(1),A,'Uni',false)
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

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

George Abrahams 2022년 12월 30일
Old question, but my fieldfun function on File Exchange / GitHub does what you expected structfun to do: output a structure a with the same fields as structure A.
A = struct( 'b', 1:10, 'c', 2:11, 'd', 3:12 );
nthelement = @(n) fieldfun( @(x) x(n), A );
a = nthelement(1)
% a = struct with fields:
% b: 1
% c: 2
% d: 3
a = arrayfun( nthelement, 1:numel(A.b) )
% a = 1×10 struct array with fields:
% b
% c
% d

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

### 카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by