2016-09-19 70 views
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{:}) 

這種失敗,我得到以下錯誤消息:

「錯誤使用struct 字段名稱必須是字符串。「

(此外,有沒有更直接的方法來實現什麼,我想上面做什麼?)

+0

使用'cell2struct(別人,cell_data_names)'代替'struct'。 –

回答

2

按照documentation of 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{:})