1

我有一个数据集,我想根据数据集中一列中的值对它进行分类并存储在一个结构中。例如,数据可以分类为元素“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{:})

这失败了,我收到以下错误消息:

“错误使用结构字段名称必须是字符串。”

(另外,有没有更直接的方法来实现我上面想要做的事情?)

4

1 回答 1

2

根据文档struct

S = struct('field1',VALUES1,'field2',VALUES2,...)创建具有指定字段和值的结构体数组。

因此,您需要将每个值都放在其字段名称之后。你现在打电话的方式struct

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

而不是正确的

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

您可以通过连接cell_data_namesothers垂直然后使用{:}来生成逗号分隔的列表来解决这个问题。这将以列优先顺序给出单元格的内容,因此每个字段名称填充后紧跟相应的值:

cell_data_names_others = [cell_data_names; others]
data = struct(cell_data_names_others{:})
于 2016-09-19T22:11:44.390 回答