Create structure with field names from an array

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-11 15:44:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!