Apply function to all fields of a structure

39 ビュー (過去 30 日間)
dandan
dandan 2018 年 2 月 6 日
回答済み: Stuart McGarrity 2018 年 5 月 29 日
Say I have a structure with a bunch of fields, and I would like to add a subfield to each field with the mean of its values, such as:
structure(1).field1.mean = mean(structure(1).field1.values);
But I'd like to do this for all elements in the structure (i.e., structure(:)) and for many fields (i.e., structure.field1, structure.field2, structure.field3, etc.), sort of like a wildcard call.
The best I've come up with so far is a double for loop with dynamic field names:
fieldnames={'field1' 'field2' 'field3'};
for i=1:length(structure)
for j=1:length(fieldnames)
structure(i).(fieldnames{j}).mean = mean(structure(i).(fieldnames{j}).values);
end
end
But this seems sloppy... Is there a way to do this without for loops? Thanks!

回答 (2 件)

James Tursa
James Tursa 2018 年 2 月 6 日
What you have is likely the best way to do this. Since there will need to be a loop of some sort to do this anyway (even if it is in the background of a function call), may as well just write it out like you have since it is easy to read and understand what is happening.

Stuart McGarrity
Stuart McGarrity 2018 年 5 月 29 日
Take a look at structfun and arrayfun.

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by