Hefaestion
Hefaestion

Reputation: 203

Create structure fieldnames from array of numbers

I have a dataset that I would like to categorise and store in a structure based on the value in one column of the dataset. For example, the data can be categorised into element 'label_100', 'label_200' or 'label_300' as I attempt below:

%The labels I would like are based on the dataset
example_data = [repmat(100,1,100),repmat(200,1,100),repmat(300,1,100)];
data_names = unique(example_data);

%create a cell array of strings for the structure fieldnames
for i = 1:length(data_names)
    cell_data_names{i}=sprintf('label_%d', data_names(i));
end

%create a cell array of data (just 0's for now)
others = num2cell(zeros(size(cell_data_names)));

%try and create the structure
data = struct(cell_data_names{:},others{:})

This fails and I get the following error message:

"Error using struct Field names must be strings."

(Also, is there a more direct method to achieve what I am trying to do above?)

Upvotes: 1

Views: 339

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112749

According to the documentation of struct,

S = struct('field1',VALUES1,'field2',VALUES2,...) creates a structure array with the specified fields and values.

So you need to have each value right after its field name. The way you are calling struct now is

S = struct('field1','field2',VALUES1,VALUES2,...)

instead of the correct

S = struct('field1',VALUES1,'field2',VALUES2,...).

You can solve that by concatenating cell_data_names and others vertically and then using {:} to produce a comma-separated list. This will give the cells' contents in column-major order, so each field name fill be immediately followed by the corresponding value:

cell_data_names_others = [cell_data_names; others]
data = struct(cell_data_names_others{:})

Upvotes: 2

Related Questions