1

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 Answer 1

3

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.