问题
Below I have a snippet of code that I am using to create a structure with field names that are defined in the array 'field_names'. This seems like a very clunky way of creating the structure.
Is there a better way that I can do this in one line? Perhaps there is some syntax trick to help me avoid the for loop?
%array of names to create field names from
field_names = ['num1', 'num2', 'num3', 'etc'];
data = struct()
for i = 1:length(field_names)
data.field_names(i) = rand() %some random value, doesn't matter for now
end
回答1:
So first of all, the way you've written it won't work since field_names
should be a cell
array, and struct
dynamic field referencing requires parentheses:
data.(field_names{i}) = rand();
You can use cell2struct
to construct the struct
using those fieldnames and the desired values.
field_names = {'num1', 'num2', 'num3'};
values = num2cell(rand(size(field_names)));
S = cell2struct(values(:), field_names(:))
% num1: 0.2277
% num2: 0.4357
% num3: 0.3111
You can also create all of the field and values when calling struct
directly:
S = struct('num1', rand(), 'num2', rand(), 'num3', rand());
来源:https://stackoverflow.com/questions/39579184/create-structure-with-field-names-from-an-array