How to index every field of a structure and reassign to a structure with a single element in each field
20 ビュー (過去 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
0 件のコメント
採用された回答
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
その他の回答 (2 件)
Chad Greene
2019 年 7 月 18 日
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 件のコメント
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!