MATLAB Answers

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

조회 수: 56(최근 30일)
John Petersen
John Petersen 10 Mar 2017
Answered: Chad Greene 18 Jul 2019
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

  댓글 수: 0

로그인 to comment.

채택된 답변

KSSV
KSSV 10 Mar 2017
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

John Petersen
John Petersen 10 Mar 2017
Thanks KSSV, Interesting approach. I just had to change the indexing so that I could keep the element I want.

로그인 to comment.

More Answers (1)

Chad Greene
Chad Greene 18 Jul 2019
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

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by