How can I access all values of a field in an array of nested structs
13 ビュー (過去 30 日間)
古いコメントを表示
The following code creates an array of nested structs (length = 4).
nested_struct = struct(...
'a', 1, ...
'b', 1 ...
);
s = struct( ...
'c', 0, ...
'nested', nested_struct ...
);
array_of_nested_struct = repmat(s, 4, 1);
How can I easily access an array of all of the values of the field a ?
For example, I'd like to compute the sum as
% sum(array_of_nested_struct.nested.a)
However, this does not work because
array_of_nested_struct.nested
does not produce a struct array.
My only solution seems overly cumbersome, and requries usage of intermediate variables:
% The following is not an array of structures
array_of_nested_struct.nested;
% So convert it into a struct array
nested = [array_of_nested_struct.nested];
% Do the same for the next level
a_value_array = [nested.a];
% Finally compute sum
sum(a_value_array)
is there a better syntax to achieve this result? The syntax should also support code generation without any data copies
Thanks!
2 件のコメント
Stephen23
2023 年 8 月 7 日
"is there a better syntax to achieve this result?"
Don't spread data over lots of different structures if it is intended to be processed together.
回答 (1 件)
Benjamin
2023 年 8 月 7 日
編集済み: Benjamin
2023 年 8 月 7 日
% Given code to create the array_of_nested_struct
nested_struct = struct(...
'a', 1, ...
'b', 1 ...
);
s = struct( ...
'c', 0, ...
'nested', nested_struct ...
);
array_of_nested_struct = repmat(s, 4, 1);
% Use arrayfun to extract 'a' field values and compute the sum directly
sum_a_values = sum(arrayfun(@(x) x.nested.a, array_of_nested_struct));
% Display the sum
disp("Sum of 'a' values: " + sum_a_values);
So this here will give you the array:
array = arrayfun(@(x) x.nested.a, array_of_nested_struct)
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!