从数字数组创建结构字段名
Create structure fieldnames from array of numbers
我有一个数据集,我想根据数据集一列中的值将其分类并存储在结构中。例如,数据可以分类为元素 'label_100'、'label_200' 或 'label_300',如下所示:
%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{:})
这失败了,我收到以下错误消息:
“使用结构时出错
字段名称必须是字符串。"
(另外,有没有更直接的方法来实现我上面想做的事情?)
S = struct('field1',VALUES1,'field2',VALUES2,...)
creates a
structure array with the specified fields and values.
因此您需要在每个值的字段名称之后紧跟其后。您现在调用 struct
的方式是
S = struct('field1','field2',VALUES1,VALUES2,...)
而不是正确的
S = struct('field1',VALUES1,'field2',VALUES2,...).
您可以通过垂直连接 cell_data_names
和 others
然后使用 {:}
生成逗号分隔列表来解决该问题。这将以列优先顺序给出单元格的内容,因此每个字段名称后面紧跟相应的值:
cell_data_names_others = [cell_data_names; others]
data = struct(cell_data_names_others{:})
我有一个数据集,我想根据数据集一列中的值将其分类并存储在结构中。例如,数据可以分类为元素 'label_100'、'label_200' 或 'label_300',如下所示:
%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{:})
这失败了,我收到以下错误消息:
“使用结构时出错 字段名称必须是字符串。"
(另外,有没有更直接的方法来实现我上面想做的事情?)
S = struct('field1',VALUES1,'field2',VALUES2,...)
creates a structure array with the specified fields and values.
因此您需要在每个值的字段名称之后紧跟其后。您现在调用 struct
的方式是
S = struct('field1','field2',VALUES1,VALUES2,...)
而不是正确的
S = struct('field1',VALUES1,'field2',VALUES2,...).
您可以通过垂直连接 cell_data_names
和 others
然后使用 {:}
生成逗号分隔列表来解决该问题。这将以列优先顺序给出单元格的内容,因此每个字段名称后面紧跟相应的值:
cell_data_names_others = [cell_data_names; others]
data = struct(cell_data_names_others{:})